1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Provides the Expression parsing implementation.
12 /// Expressions in C99 basically consist of a bunch of binary operators with
13 /// unary operators and other random stuff at the leaves.
15 /// In the C99 grammar, these unary operators bind tightest and are represented
16 /// as the 'cast-expression' production. Everything else is either a binary
17 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
18 /// handled by ParseCastExpression, the higher level pieces are handled by
19 /// ParseBinaryExpression.
21 //===----------------------------------------------------------------------===//
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/Basic/PrettyStackTrace.h"
26 #include "clang/Lex/LiteralSupport.h"
27 #include "clang/Parse/Parser.h"
28 #include "clang/Parse/RAIIObjectsForParser.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/ParsedTemplate.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/TypoCorrection.h"
34 #include "llvm/ADT/SmallVector.h"
36 using namespace clang
;
38 /// Simple precedence-based parser for binary/ternary operators.
40 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
41 /// production. C99 specifies that the LHS of an assignment operator should be
42 /// parsed as a unary-expression, but consistency dictates that it be a
43 /// conditional-expession. In practice, the important thing here is that the
44 /// LHS of an assignment has to be an l-value, which productions between
45 /// unary-expression and conditional-expression don't produce. Because we want
46 /// consistency, we parse the LHS as a conditional-expression, then check for
47 /// l-value-ness in semantic analysis stages.
50 /// pm-expression: [C++ 5.5]
52 /// pm-expression '.*' cast-expression
53 /// pm-expression '->*' cast-expression
55 /// multiplicative-expression: [C99 6.5.5]
56 /// Note: in C++, apply pm-expression instead of cast-expression
58 /// multiplicative-expression '*' cast-expression
59 /// multiplicative-expression '/' cast-expression
60 /// multiplicative-expression '%' cast-expression
62 /// additive-expression: [C99 6.5.6]
63 /// multiplicative-expression
64 /// additive-expression '+' multiplicative-expression
65 /// additive-expression '-' multiplicative-expression
67 /// shift-expression: [C99 6.5.7]
68 /// additive-expression
69 /// shift-expression '<<' additive-expression
70 /// shift-expression '>>' additive-expression
72 /// compare-expression: [C++20 expr.spaceship]
74 /// compare-expression '<=>' shift-expression
76 /// relational-expression: [C99 6.5.8]
77 /// compare-expression
78 /// relational-expression '<' compare-expression
79 /// relational-expression '>' compare-expression
80 /// relational-expression '<=' compare-expression
81 /// relational-expression '>=' compare-expression
83 /// equality-expression: [C99 6.5.9]
84 /// relational-expression
85 /// equality-expression '==' relational-expression
86 /// equality-expression '!=' relational-expression
88 /// AND-expression: [C99 6.5.10]
89 /// equality-expression
90 /// AND-expression '&' equality-expression
92 /// exclusive-OR-expression: [C99 6.5.11]
94 /// exclusive-OR-expression '^' AND-expression
96 /// inclusive-OR-expression: [C99 6.5.12]
97 /// exclusive-OR-expression
98 /// inclusive-OR-expression '|' exclusive-OR-expression
100 /// logical-AND-expression: [C99 6.5.13]
101 /// inclusive-OR-expression
102 /// logical-AND-expression '&&' inclusive-OR-expression
104 /// logical-OR-expression: [C99 6.5.14]
105 /// logical-AND-expression
106 /// logical-OR-expression '||' logical-AND-expression
108 /// conditional-expression: [C99 6.5.15]
109 /// logical-OR-expression
110 /// logical-OR-expression '?' expression ':' conditional-expression
111 /// [GNU] logical-OR-expression '?' ':' conditional-expression
112 /// [C++] the third operand is an assignment-expression
114 /// assignment-expression: [C99 6.5.16]
115 /// conditional-expression
116 /// unary-expression assignment-operator assignment-expression
117 /// [C++] throw-expression [C++ 15]
119 /// assignment-operator: one of
120 /// = *= /= %= += -= <<= >>= &= ^= |=
122 /// expression: [C99 6.5.17]
123 /// assignment-expression ...[opt]
124 /// expression ',' assignment-expression ...[opt]
126 ExprResult
Parser::ParseExpression(TypeCastState isTypeCast
) {
127 ExprResult
LHS(ParseAssignmentExpression(isTypeCast
));
128 return ParseRHSOfBinaryExpression(LHS
, prec::Comma
);
131 /// This routine is called when the '@' is seen and consumed.
132 /// Current token is an Identifier and is not a 'try'. This
133 /// routine is necessary to disambiguate \@try-statement from,
134 /// for example, \@encode-expression.
137 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc
) {
138 ExprResult
LHS(ParseObjCAtExpression(AtLoc
));
139 return ParseRHSOfBinaryExpression(LHS
, prec::Comma
);
142 /// This routine is called when a leading '__extension__' is seen and
143 /// consumed. This is necessary because the token gets consumed in the
144 /// process of disambiguating between an expression and a declaration.
146 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc
) {
147 ExprResult
LHS(true);
149 // Silence extension warnings in the sub-expression
150 ExtensionRAIIObject
O(Diags
);
152 LHS
= ParseCastExpression(AnyCastExpr
);
155 if (!LHS
.isInvalid())
156 LHS
= Actions
.ActOnUnaryOp(getCurScope(), ExtLoc
, tok::kw___extension__
,
159 return ParseRHSOfBinaryExpression(LHS
, prec::Comma
);
162 /// Parse an expr that doesn't include (top-level) commas.
163 ExprResult
Parser::ParseAssignmentExpression(TypeCastState isTypeCast
) {
164 if (Tok
.is(tok::code_completion
)) {
166 Actions
.CodeCompleteExpression(getCurScope(),
167 PreferredType
.get(Tok
.getLocation()));
171 if (Tok
.is(tok::kw_throw
))
172 return ParseThrowExpression();
173 if (Tok
.is(tok::kw_co_yield
))
174 return ParseCoyieldExpression();
176 ExprResult LHS
= ParseCastExpression(AnyCastExpr
,
177 /*isAddressOfOperand=*/false,
179 return ParseRHSOfBinaryExpression(LHS
, prec::Assignment
);
182 /// Parse an assignment expression where part of an Objective-C message
183 /// send has already been parsed.
185 /// In this case \p LBracLoc indicates the location of the '[' of the message
186 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
187 /// the receiver of the message.
189 /// Since this handles full assignment-expression's, it handles postfix
190 /// expressions and other binary operators for these expressions as well.
192 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc
,
193 SourceLocation SuperLoc
,
194 ParsedType ReceiverType
,
195 Expr
*ReceiverExpr
) {
197 = ParseObjCMessageExpressionBody(LBracLoc
, SuperLoc
,
198 ReceiverType
, ReceiverExpr
);
199 R
= ParsePostfixExpressionSuffix(R
);
200 return ParseRHSOfBinaryExpression(R
, prec::Assignment
);
204 Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast
) {
205 assert(Actions
.ExprEvalContexts
.back().Context
==
206 Sema::ExpressionEvaluationContext::ConstantEvaluated
&&
207 "Call this function only if your ExpressionEvaluationContext is "
208 "already ConstantEvaluated");
209 ExprResult
LHS(ParseCastExpression(AnyCastExpr
, false, isTypeCast
));
210 ExprResult
Res(ParseRHSOfBinaryExpression(LHS
, prec::Conditional
));
211 return Actions
.ActOnConstantExpression(Res
);
214 ExprResult
Parser::ParseConstantExpression() {
215 // C++03 [basic.def.odr]p2:
216 // An expression is potentially evaluated unless it appears where an
217 // integral constant expression is required (see 5.19) [...].
218 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
219 EnterExpressionEvaluationContext
ConstantEvaluated(
220 Actions
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
221 return ParseConstantExpressionInExprEvalContext(NotTypeCast
);
224 ExprResult
Parser::ParseArrayBoundExpression() {
225 EnterExpressionEvaluationContext
ConstantEvaluated(
226 Actions
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
227 // If we parse the bound of a VLA... we parse a non-constant
228 // constant-expression!
229 Actions
.ExprEvalContexts
.back().InConditionallyConstantEvaluateContext
= true;
230 return ParseConstantExpressionInExprEvalContext(NotTypeCast
);
233 ExprResult
Parser::ParseCaseExpression(SourceLocation CaseLoc
) {
234 EnterExpressionEvaluationContext
ConstantEvaluated(
235 Actions
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
236 ExprResult
LHS(ParseCastExpression(AnyCastExpr
, false, NotTypeCast
));
237 ExprResult
Res(ParseRHSOfBinaryExpression(LHS
, prec::Conditional
));
238 return Actions
.ActOnCaseExpr(CaseLoc
, Res
);
241 /// Parse a constraint-expression.
244 /// constraint-expression: C++2a[temp.constr.decl]p1
245 /// logical-or-expression
247 ExprResult
Parser::ParseConstraintExpression() {
248 EnterExpressionEvaluationContext
ConstantEvaluated(
249 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
);
250 ExprResult
LHS(ParseCastExpression(AnyCastExpr
));
251 ExprResult
Res(ParseRHSOfBinaryExpression(LHS
, prec::LogicalOr
));
252 if (Res
.isUsable() && !Actions
.CheckConstraintExpression(Res
.get())) {
253 Actions
.CorrectDelayedTyposInExpr(Res
);
259 /// \brief Parse a constraint-logical-and-expression.
262 /// C++2a[temp.constr.decl]p1
263 /// constraint-logical-and-expression:
264 /// primary-expression
265 /// constraint-logical-and-expression '&&' primary-expression
269 Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause
) {
270 EnterExpressionEvaluationContext
ConstantEvaluated(
271 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
);
272 bool NotPrimaryExpression
= false;
273 auto ParsePrimary
= [&] () {
274 ExprResult E
= ParseCastExpression(PrimaryExprOnly
,
275 /*isAddressOfOperand=*/false,
276 /*isTypeCast=*/NotTypeCast
,
277 /*isVectorLiteral=*/false,
278 &NotPrimaryExpression
);
281 auto RecoverFromNonPrimary
= [&] (ExprResult E
, bool Note
) {
282 E
= ParsePostfixExpressionSuffix(E
);
283 // Use InclusiveOr, the precedence just after '&&' to not parse the
284 // next arguments to the logical and.
285 E
= ParseRHSOfBinaryExpression(E
, prec::InclusiveOr
);
287 Diag(E
.get()->getExprLoc(),
289 ? diag::note_unparenthesized_non_primary_expr_in_requires_clause
290 : diag::err_unparenthesized_non_primary_expr_in_requires_clause
)
291 << FixItHint::CreateInsertion(E
.get()->getBeginLoc(), "(")
292 << FixItHint::CreateInsertion(
293 PP
.getLocForEndOfToken(E
.get()->getEndLoc()), ")")
294 << E
.get()->getSourceRange();
298 if (NotPrimaryExpression
||
299 // Check if the following tokens must be a part of a non-primary
301 getBinOpPrecedence(Tok
.getKind(), GreaterThanIsOperator
,
302 /*CPlusPlus11=*/true) > prec::LogicalAnd
||
303 // Postfix operators other than '(' (which will be checked for in
304 // CheckConstraintExpression).
305 Tok
.isOneOf(tok::period
, tok::plusplus
, tok::minusminus
) ||
306 (Tok
.is(tok::l_square
) && !NextToken().is(tok::l_square
))) {
307 E
= RecoverFromNonPrimary(E
, /*Note=*/false);
310 NotPrimaryExpression
= false;
312 bool PossibleNonPrimary
;
313 bool IsConstraintExpr
=
314 Actions
.CheckConstraintExpression(E
.get(), Tok
, &PossibleNonPrimary
,
315 IsTrailingRequiresClause
);
316 if (!IsConstraintExpr
|| PossibleNonPrimary
) {
317 // Atomic constraint might be an unparenthesized non-primary expression
318 // (such as a binary operator), in which case we might get here (e.g. in
319 // 'requires 0 + 1 && true' we would now be at '+', and parse and ignore
320 // the rest of the addition expression). Try to parse the rest of it here.
321 if (PossibleNonPrimary
)
322 E
= RecoverFromNonPrimary(E
, /*Note=*/!IsConstraintExpr
);
323 Actions
.CorrectDelayedTyposInExpr(E
);
328 ExprResult LHS
= ParsePrimary();
331 while (Tok
.is(tok::ampamp
)) {
332 SourceLocation LogicalAndLoc
= ConsumeToken();
333 ExprResult RHS
= ParsePrimary();
334 if (RHS
.isInvalid()) {
335 Actions
.CorrectDelayedTyposInExpr(LHS
);
338 ExprResult Op
= Actions
.ActOnBinOp(getCurScope(), LogicalAndLoc
,
339 tok::ampamp
, LHS
.get(), RHS
.get());
340 if (!Op
.isUsable()) {
341 Actions
.CorrectDelayedTyposInExpr(RHS
);
342 Actions
.CorrectDelayedTyposInExpr(LHS
);
350 /// \brief Parse a constraint-logical-or-expression.
353 /// C++2a[temp.constr.decl]p1
354 /// constraint-logical-or-expression:
355 /// constraint-logical-and-expression
356 /// constraint-logical-or-expression '||'
357 /// constraint-logical-and-expression
361 Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause
) {
362 ExprResult
LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause
));
365 while (Tok
.is(tok::pipepipe
)) {
366 SourceLocation LogicalOrLoc
= ConsumeToken();
368 ParseConstraintLogicalAndExpression(IsTrailingRequiresClause
);
369 if (!RHS
.isUsable()) {
370 Actions
.CorrectDelayedTyposInExpr(LHS
);
373 ExprResult Op
= Actions
.ActOnBinOp(getCurScope(), LogicalOrLoc
,
374 tok::pipepipe
, LHS
.get(), RHS
.get());
375 if (!Op
.isUsable()) {
376 Actions
.CorrectDelayedTyposInExpr(RHS
);
377 Actions
.CorrectDelayedTyposInExpr(LHS
);
385 bool Parser::isNotExpressionStart() {
386 tok::TokenKind K
= Tok
.getKind();
387 if (K
== tok::l_brace
|| K
== tok::r_brace
||
388 K
== tok::kw_for
|| K
== tok::kw_while
||
389 K
== tok::kw_if
|| K
== tok::kw_else
||
390 K
== tok::kw_goto
|| K
== tok::kw_try
)
392 // If this is a decl-specifier, we can't be at the start of an expression.
393 return isKnownToBeDeclarationSpecifier();
396 bool Parser::isFoldOperator(prec::Level Level
) const {
397 return Level
> prec::Unknown
&& Level
!= prec::Conditional
&&
398 Level
!= prec::Spaceship
;
401 bool Parser::isFoldOperator(tok::TokenKind Kind
) const {
402 return isFoldOperator(getBinOpPrecedence(Kind
, GreaterThanIsOperator
, true));
405 /// Parse a binary expression that starts with \p LHS and has a
406 /// precedence of at least \p MinPrec.
408 Parser::ParseRHSOfBinaryExpression(ExprResult LHS
, prec::Level MinPrec
) {
409 prec::Level NextTokPrec
= getBinOpPrecedence(Tok
.getKind(),
410 GreaterThanIsOperator
,
411 getLangOpts().CPlusPlus11
);
412 SourceLocation ColonLoc
;
414 auto SavedType
= PreferredType
;
416 // Every iteration may rely on a preferred type for the whole expression.
417 PreferredType
= SavedType
;
418 // If this token has a lower precedence than we are allowed to parse (e.g.
419 // because we are called recursively, or because the token is not a binop),
421 if (NextTokPrec
< MinPrec
)
424 // Consume the operator, saving the operator token for error reporting.
428 if (OpToken
.is(tok::caretcaret
)) {
429 return ExprError(Diag(Tok
, diag::err_opencl_logical_exclusive_or
));
432 // If we're potentially in a template-id, we may now be able to determine
433 // whether we're actually in one or not.
434 if (OpToken
.isOneOf(tok::comma
, tok::greater
, tok::greatergreater
,
435 tok::greatergreatergreater
) &&
436 checkPotentialAngleBracketDelimiter(OpToken
))
439 // Bail out when encountering a comma followed by a token which can't
440 // possibly be the start of an expression. For instance:
441 // int f() { return 1, }
442 // We can't do this before consuming the comma, because
443 // isNotExpressionStart() looks at the token stream.
444 if (OpToken
.is(tok::comma
) && isNotExpressionStart()) {
445 PP
.EnterToken(Tok
, /*IsReinject*/true);
450 // If the next token is an ellipsis, then this is a fold-expression. Leave
451 // it alone so we can handle it in the paren expression.
452 if (isFoldOperator(NextTokPrec
) && Tok
.is(tok::ellipsis
)) {
453 // FIXME: We can't check this via lookahead before we consume the token
454 // because that tickles a lexer bug.
455 PP
.EnterToken(Tok
, /*IsReinject*/true);
460 // In Objective-C++, alternative operator tokens can be used as keyword args
461 // in message expressions. Unconsume the token so that it can reinterpreted
462 // as an identifier in ParseObjCMessageExpressionBody. i.e., we support:
463 // [foo meth:0 and:0];
465 if (getLangOpts().ObjC
&& getLangOpts().CPlusPlus
&&
466 Tok
.isOneOf(tok::colon
, tok::r_square
) &&
467 OpToken
.getIdentifierInfo() != nullptr) {
468 PP
.EnterToken(Tok
, /*IsReinject*/true);
473 // Special case handling for the ternary operator.
474 ExprResult
TernaryMiddle(true);
475 if (NextTokPrec
== prec::Conditional
) {
476 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
)) {
477 // Parse a braced-init-list here for error recovery purposes.
478 SourceLocation BraceLoc
= Tok
.getLocation();
479 TernaryMiddle
= ParseBraceInitializer();
480 if (!TernaryMiddle
.isInvalid()) {
481 Diag(BraceLoc
, diag::err_init_list_bin_op
)
482 << /*RHS*/ 1 << PP
.getSpelling(OpToken
)
483 << Actions
.getExprRange(TernaryMiddle
.get());
484 TernaryMiddle
= ExprError();
486 } else if (Tok
.isNot(tok::colon
)) {
487 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
488 ColonProtectionRAIIObject
X(*this);
490 // Handle this production specially:
491 // logical-OR-expression '?' expression ':' conditional-expression
492 // In particular, the RHS of the '?' is 'expression', not
493 // 'logical-OR-expression' as we might expect.
494 TernaryMiddle
= ParseExpression();
496 // Special case handling of "X ? Y : Z" where Y is empty:
497 // logical-OR-expression '?' ':' conditional-expression [GNU]
498 TernaryMiddle
= nullptr;
499 Diag(Tok
, diag::ext_gnu_conditional_expr
);
502 if (TernaryMiddle
.isInvalid()) {
503 Actions
.CorrectDelayedTyposInExpr(LHS
);
505 TernaryMiddle
= nullptr;
508 if (!TryConsumeToken(tok::colon
, ColonLoc
)) {
509 // Otherwise, we're missing a ':'. Assume that this was a typo that
510 // the user forgot. If we're not in a macro expansion, we can suggest
511 // a fixit hint. If there were two spaces before the current token,
512 // suggest inserting the colon in between them, otherwise insert ": ".
513 SourceLocation FILoc
= Tok
.getLocation();
514 const char *FIText
= ": ";
515 const SourceManager
&SM
= PP
.getSourceManager();
516 if (FILoc
.isFileID() || PP
.isAtStartOfMacroExpansion(FILoc
, &FILoc
)) {
517 assert(FILoc
.isFileID());
518 bool IsInvalid
= false;
519 const char *SourcePtr
=
520 SM
.getCharacterData(FILoc
.getLocWithOffset(-1), &IsInvalid
);
521 if (!IsInvalid
&& *SourcePtr
== ' ') {
523 SM
.getCharacterData(FILoc
.getLocWithOffset(-2), &IsInvalid
);
524 if (!IsInvalid
&& *SourcePtr
== ' ') {
525 FILoc
= FILoc
.getLocWithOffset(-1);
531 Diag(Tok
, diag::err_expected
)
532 << tok::colon
<< FixItHint::CreateInsertion(FILoc
, FIText
);
533 Diag(OpToken
, diag::note_matching
) << tok::question
;
534 ColonLoc
= Tok
.getLocation();
538 PreferredType
.enterBinary(Actions
, Tok
.getLocation(), LHS
.get(),
540 // Parse another leaf here for the RHS of the operator.
541 // ParseCastExpression works here because all RHS expressions in C have it
542 // as a prefix, at least. However, in C++, an assignment-expression could
543 // be a throw-expression, which is not a valid cast-expression.
544 // Therefore we need some special-casing here.
545 // Also note that the third operand of the conditional operator is
546 // an assignment-expression in C++, and in C++11, we can have a
547 // braced-init-list on the RHS of an assignment. For better diagnostics,
548 // parse as if we were allowed braced-init-lists everywhere, and check that
549 // they only appear on the RHS of assignments later.
551 bool RHSIsInitList
= false;
552 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
)) {
553 RHS
= ParseBraceInitializer();
554 RHSIsInitList
= true;
555 } else if (getLangOpts().CPlusPlus
&& NextTokPrec
<= prec::Conditional
)
556 RHS
= ParseAssignmentExpression();
558 RHS
= ParseCastExpression(AnyCastExpr
);
560 if (RHS
.isInvalid()) {
561 // FIXME: Errors generated by the delayed typo correction should be
562 // printed before errors from parsing the RHS, not after.
563 Actions
.CorrectDelayedTyposInExpr(LHS
);
564 if (TernaryMiddle
.isUsable())
565 TernaryMiddle
= Actions
.CorrectDelayedTyposInExpr(TernaryMiddle
);
569 // Remember the precedence of this operator and get the precedence of the
570 // operator immediately to the right of the RHS.
571 prec::Level ThisPrec
= NextTokPrec
;
572 NextTokPrec
= getBinOpPrecedence(Tok
.getKind(), GreaterThanIsOperator
,
573 getLangOpts().CPlusPlus11
);
575 // Assignment and conditional expressions are right-associative.
576 bool isRightAssoc
= ThisPrec
== prec::Conditional
||
577 ThisPrec
== prec::Assignment
;
579 // Get the precedence of the operator to the right of the RHS. If it binds
580 // more tightly with RHS than we do, evaluate it completely first.
581 if (ThisPrec
< NextTokPrec
||
582 (ThisPrec
== NextTokPrec
&& isRightAssoc
)) {
583 if (!RHS
.isInvalid() && RHSIsInitList
) {
584 Diag(Tok
, diag::err_init_list_bin_op
)
585 << /*LHS*/0 << PP
.getSpelling(Tok
) << Actions
.getExprRange(RHS
.get());
588 // If this is left-associative, only parse things on the RHS that bind
589 // more tightly than the current operator. If it is left-associative, it
590 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
591 // A=(B=(C=D)), where each paren is a level of recursion here.
592 // The function takes ownership of the RHS.
593 RHS
= ParseRHSOfBinaryExpression(RHS
,
594 static_cast<prec::Level
>(ThisPrec
+ !isRightAssoc
));
595 RHSIsInitList
= false;
597 if (RHS
.isInvalid()) {
598 // FIXME: Errors generated by the delayed typo correction should be
599 // printed before errors from ParseRHSOfBinaryExpression, not after.
600 Actions
.CorrectDelayedTyposInExpr(LHS
);
601 if (TernaryMiddle
.isUsable())
602 TernaryMiddle
= Actions
.CorrectDelayedTyposInExpr(TernaryMiddle
);
606 NextTokPrec
= getBinOpPrecedence(Tok
.getKind(), GreaterThanIsOperator
,
607 getLangOpts().CPlusPlus11
);
610 if (!RHS
.isInvalid() && RHSIsInitList
) {
611 if (ThisPrec
== prec::Assignment
) {
612 Diag(OpToken
, diag::warn_cxx98_compat_generalized_initializer_lists
)
613 << Actions
.getExprRange(RHS
.get());
614 } else if (ColonLoc
.isValid()) {
615 Diag(ColonLoc
, diag::err_init_list_bin_op
)
617 << Actions
.getExprRange(RHS
.get());
620 Diag(OpToken
, diag::err_init_list_bin_op
)
621 << /*RHS*/1 << PP
.getSpelling(OpToken
)
622 << Actions
.getExprRange(RHS
.get());
627 ExprResult OrigLHS
= LHS
;
628 if (!LHS
.isInvalid()) {
629 // Combine the LHS and RHS into the LHS (e.g. build AST).
630 if (TernaryMiddle
.isInvalid()) {
631 // If we're using '>>' as an operator within a template
632 // argument list (in C++98), suggest the addition of
633 // parentheses so that the code remains well-formed in C++0x.
634 if (!GreaterThanIsOperator
&& OpToken
.is(tok::greatergreater
))
635 SuggestParentheses(OpToken
.getLocation(),
636 diag::warn_cxx11_right_shift_in_template_arg
,
637 SourceRange(Actions
.getExprRange(LHS
.get()).getBegin(),
638 Actions
.getExprRange(RHS
.get()).getEnd()));
641 Actions
.ActOnBinOp(getCurScope(), OpToken
.getLocation(),
642 OpToken
.getKind(), LHS
.get(), RHS
.get());
643 if (BinOp
.isInvalid())
644 BinOp
= Actions
.CreateRecoveryExpr(LHS
.get()->getBeginLoc(),
645 RHS
.get()->getEndLoc(),
646 {LHS
.get(), RHS
.get()});
650 ExprResult CondOp
= Actions
.ActOnConditionalOp(
651 OpToken
.getLocation(), ColonLoc
, LHS
.get(), TernaryMiddle
.get(),
653 if (CondOp
.isInvalid()) {
654 std::vector
<clang::Expr
*> Args
;
655 // TernaryMiddle can be null for the GNU conditional expr extension.
656 if (TernaryMiddle
.get())
657 Args
= {LHS
.get(), TernaryMiddle
.get(), RHS
.get()};
659 Args
= {LHS
.get(), RHS
.get()};
660 CondOp
= Actions
.CreateRecoveryExpr(LHS
.get()->getBeginLoc(),
661 RHS
.get()->getEndLoc(), Args
);
666 // In this case, ActOnBinOp or ActOnConditionalOp performed the
667 // CorrectDelayedTyposInExpr check.
668 if (!getLangOpts().CPlusPlus
)
672 // Ensure potential typos aren't left undiagnosed.
673 if (LHS
.isInvalid()) {
674 Actions
.CorrectDelayedTyposInExpr(OrigLHS
);
675 Actions
.CorrectDelayedTyposInExpr(TernaryMiddle
);
676 Actions
.CorrectDelayedTyposInExpr(RHS
);
681 /// Parse a cast-expression, unary-expression or primary-expression, based
684 /// \p isAddressOfOperand exists because an id-expression that is the
685 /// operand of address-of gets special treatment due to member pointers.
687 ExprResult
Parser::ParseCastExpression(CastParseKind ParseKind
,
688 bool isAddressOfOperand
,
689 TypeCastState isTypeCast
,
690 bool isVectorLiteral
,
691 bool *NotPrimaryExpression
) {
693 ExprResult Res
= ParseCastExpression(ParseKind
,
698 NotPrimaryExpression
);
700 Diag(Tok
, diag::err_expected_expression
);
705 class CastExpressionIdValidator final
: public CorrectionCandidateCallback
{
707 CastExpressionIdValidator(Token Next
, bool AllowTypes
, bool AllowNonTypes
)
708 : NextToken(Next
), AllowNonTypes(AllowNonTypes
) {
709 WantTypeSpecifiers
= WantFunctionLikeCasts
= AllowTypes
;
712 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
713 NamedDecl
*ND
= candidate
.getCorrectionDecl();
715 return candidate
.isKeyword();
717 if (isa
<TypeDecl
>(ND
))
718 return WantTypeSpecifiers
;
720 if (!AllowNonTypes
|| !CorrectionCandidateCallback::ValidateCandidate(candidate
))
723 if (!NextToken
.isOneOf(tok::equal
, tok::arrow
, tok::period
))
726 for (auto *C
: candidate
) {
727 NamedDecl
*ND
= C
->getUnderlyingDecl();
728 if (isa
<ValueDecl
>(ND
) && !isa
<FunctionDecl
>(ND
))
734 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
735 return std::make_unique
<CastExpressionIdValidator
>(*this);
744 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
745 /// a unary-expression.
747 /// \p isAddressOfOperand exists because an id-expression that is the operand
748 /// of address-of gets special treatment due to member pointers. NotCastExpr
749 /// is set to true if the token is not the start of a cast-expression, and no
750 /// diagnostic is emitted in this case and no tokens are consumed.
753 /// cast-expression: [C99 6.5.4]
755 /// '(' type-name ')' cast-expression
757 /// unary-expression: [C99 6.5.3]
758 /// postfix-expression
759 /// '++' unary-expression
760 /// '--' unary-expression
761 /// [Coro] 'co_await' cast-expression
762 /// unary-operator cast-expression
763 /// 'sizeof' unary-expression
764 /// 'sizeof' '(' type-name ')'
765 /// [C++11] 'sizeof' '...' '(' identifier ')'
766 /// [GNU] '__alignof' unary-expression
767 /// [GNU] '__alignof' '(' type-name ')'
768 /// [C11] '_Alignof' '(' type-name ')'
769 /// [C++11] 'alignof' '(' type-id ')'
770 /// [GNU] '&&' identifier
771 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
772 /// [C++] new-expression
773 /// [C++] delete-expression
775 /// unary-operator: one of
776 /// '&' '*' '+' '-' '~' '!'
777 /// [GNU] '__extension__' '__real' '__imag'
779 /// primary-expression: [C99 6.5.1]
781 /// [C++] id-expression
784 /// [C++] boolean-literal [C++ 2.13.5]
785 /// [C++11] 'nullptr' [C++11 2.14.7]
786 /// [C++11] user-defined-literal
787 /// '(' expression ')'
788 /// [C11] generic-selection
789 /// [C++2a] requires-expression
790 /// '__func__' [C99 6.4.2.2]
791 /// [GNU] '__FUNCTION__'
792 /// [MS] '__FUNCDNAME__'
793 /// [MS] 'L__FUNCTION__'
794 /// [MS] '__FUNCSIG__'
795 /// [MS] 'L__FUNCSIG__'
796 /// [GNU] '__PRETTY_FUNCTION__'
797 /// [GNU] '(' compound-statement ')'
798 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
799 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
800 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
802 /// [GNU] '__builtin_FILE' '(' ')'
803 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
804 /// [GNU] '__builtin_FUNCTION' '(' ')'
805 /// [MS] '__builtin_FUNCSIG' '(' ')'
806 /// [GNU] '__builtin_LINE' '(' ')'
807 /// [CLANG] '__builtin_COLUMN' '(' ')'
808 /// [GNU] '__builtin_source_location' '(' ')'
809 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
811 /// [OBJC] '[' objc-message-expr ']'
812 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
813 /// [OBJC] '\@protocol' '(' identifier ')'
814 /// [OBJC] '\@encode' '(' type-name ')'
815 /// [OBJC] objc-string-literal
816 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
817 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
818 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
819 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
820 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
821 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
822 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
823 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
824 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
825 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
826 /// [C++] 'this' [C++ 9.3.2]
827 /// [G++] unary-type-trait '(' type-id ')'
828 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
829 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
830 /// [clang] '^' block-literal
832 /// constant: [C99 6.4.4]
834 /// floating-constant
835 /// enumeration-constant -> identifier
836 /// character-constant
838 /// id-expression: [C++ 5.1]
842 /// unqualified-id: [C++ 5.1]
844 /// operator-function-id
845 /// conversion-function-id
849 /// new-expression: [C++ 5.3.4]
850 /// '::'[opt] 'new' new-placement[opt] new-type-id
851 /// new-initializer[opt]
852 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
853 /// new-initializer[opt]
855 /// delete-expression: [C++ 5.3.5]
856 /// '::'[opt] 'delete' cast-expression
857 /// '::'[opt] 'delete' '[' ']' cast-expression
859 /// [GNU/Embarcadero] unary-type-trait:
860 /// '__is_arithmetic'
861 /// '__is_floating_point'
863 /// '__is_lvalue_expr'
864 /// '__is_rvalue_expr'
865 /// '__is_complete_type'
870 /// '__is_lvalue_reference'
871 /// '__is_rvalue_reference'
872 /// '__is_fundamental'
877 /// '__is_member_object_pointer'
878 /// '__is_member_function_pointer'
879 /// '__is_member_pointer'
883 /// '__is_standard_layout'
887 /// [GNU] unary-type-trait:
888 /// '__has_nothrow_assign'
889 /// '__has_nothrow_copy'
890 /// '__has_nothrow_constructor'
891 /// '__has_trivial_assign' [TODO]
892 /// '__has_trivial_copy' [TODO]
893 /// '__has_trivial_constructor'
894 /// '__has_trivial_destructor'
895 /// '__has_virtual_destructor'
896 /// '__is_abstract' [TODO]
898 /// '__is_empty' [TODO]
902 /// '__is_polymorphic'
903 /// '__is_sealed' [MS]
906 /// '__has_unique_object_representations'
908 /// [Clang] unary-type-trait:
910 /// '__trivially_copyable'
912 /// binary-type-trait:
913 /// [GNU] '__is_base_of'
914 /// [MS] '__is_convertible_to'
915 /// '__is_convertible'
918 /// [Embarcadero] array-type-trait:
922 /// [Embarcadero] expression-trait:
923 /// '__is_lvalue_expr'
924 /// '__is_rvalue_expr'
927 ExprResult
Parser::ParseCastExpression(CastParseKind ParseKind
,
928 bool isAddressOfOperand
,
930 TypeCastState isTypeCast
,
931 bool isVectorLiteral
,
932 bool *NotPrimaryExpression
) {
934 tok::TokenKind SavedKind
= Tok
.getKind();
935 auto SavedType
= PreferredType
;
938 // Are postfix-expression suffix operators permitted after this
939 // cast-expression? If not, and we find some, we'll parse them anyway and
941 bool AllowSuffix
= true;
943 // This handles all of cast-expression, unary-expression, postfix-expression,
944 // and primary-expression. We handle them together like this for efficiency
945 // and to simplify handling of an expression starting with a '(' token: which
946 // may be one of a parenthesized expression, cast-expression, compound literal
947 // expression, or statement expression.
949 // If the parsed tokens consist of a primary-expression, the cases below
950 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
951 // to handle the postfix expression suffixes. Cases that cannot be followed
952 // by postfix exprs should set AllowSuffix to false.
955 // If this expression is limited to being a unary-expression, the paren can
956 // not start a cast expression.
957 ParenParseOption ParenExprType
;
959 case CastParseKind::UnaryExprOnly
:
960 assert(getLangOpts().CPlusPlus
&& "not possible to get here in C");
962 case CastParseKind::AnyCastExpr
:
963 ParenExprType
= ParenParseOption::CastExpr
;
965 case CastParseKind::PrimaryExprOnly
:
966 ParenExprType
= FoldExpr
;
970 SourceLocation RParenLoc
;
971 Res
= ParseParenExpression(ParenExprType
, false/*stopIfCastExr*/,
972 isTypeCast
== IsTypeCast
, CastTy
, RParenLoc
);
974 // FIXME: What should we do if a vector literal is followed by a
975 // postfix-expression suffix? Usually postfix operators are permitted on
980 switch (ParenExprType
) {
981 case SimpleExpr
: break; // Nothing else to do.
982 case CompoundStmt
: break; // Nothing else to do.
983 case CompoundLiteral
:
984 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
985 // postfix-expression exist, parse them now.
988 // We have parsed the cast-expression and no postfix-expr pieces are
992 // We only parsed a fold-expression. There might be postfix-expr pieces
993 // afterwards; parse them now.
1000 // primary-expression
1001 case tok::numeric_constant
:
1002 // constant: integer-constant
1003 // constant: floating-constant
1005 Res
= Actions
.ActOnNumericConstant(Tok
, /*UDLScope*/getCurScope());
1011 Res
= ParseCXXBoolLiteral();
1014 case tok::kw___objc_yes
:
1015 case tok::kw___objc_no
:
1016 Res
= ParseObjCBoolLiteral();
1019 case tok::kw_nullptr
:
1020 if (getLangOpts().CPlusPlus
)
1021 Diag(Tok
, diag::warn_cxx98_compat_nullptr
);
1023 Diag(Tok
, getLangOpts().C23
? diag::warn_c23_compat_keyword
1024 : diag::ext_c_nullptr
) << Tok
.getName();
1026 Res
= Actions
.ActOnCXXNullPtrLiteral(ConsumeToken());
1029 case tok::annot_primary_expr
:
1030 case tok::annot_overload_set
:
1031 Res
= getExprAnnotation(Tok
);
1032 if (!Res
.isInvalid() && Tok
.getKind() == tok::annot_overload_set
)
1033 Res
= Actions
.ActOnNameClassifiedAsOverloadSet(getCurScope(), Res
.get());
1034 ConsumeAnnotationToken();
1035 if (!Res
.isInvalid() && Tok
.is(tok::less
))
1036 checkPotentialAngleBracket(Res
);
1039 case tok::annot_non_type
:
1040 case tok::annot_non_type_dependent
:
1041 case tok::annot_non_type_undeclared
: {
1044 Res
= tryParseCXXIdExpression(SS
, isAddressOfOperand
, Replacement
);
1045 assert(!Res
.isUnset() &&
1046 "should not perform typo correction on annotation token");
1050 case tok::kw___super
:
1051 case tok::kw_decltype
:
1052 // Annotate the token and tail recurse.
1053 if (TryAnnotateTypeOrScopeToken())
1055 assert(Tok
.isNot(tok::kw_decltype
) && Tok
.isNot(tok::kw___super
));
1056 return ParseCastExpression(ParseKind
, isAddressOfOperand
, isTypeCast
,
1057 isVectorLiteral
, NotPrimaryExpression
);
1059 case tok::identifier
:
1060 ParseIdentifier
: { // primary-expression: identifier
1061 // unqualified-id: identifier
1062 // constant: enumeration-constant
1063 // Turn a potentially qualified name into a annot_typename or
1064 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
1065 if (getLangOpts().CPlusPlus
) {
1066 // Avoid the unnecessary parse-time lookup in the common case
1067 // where the syntax forbids a type.
1068 const Token
&Next
= NextToken();
1070 // If this identifier was reverted from a token ID, and the next token
1071 // is a parenthesis, this is likely to be a use of a type trait. Check
1073 if (Next
.is(tok::l_paren
) &&
1074 Tok
.is(tok::identifier
) &&
1075 Tok
.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
1076 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
1077 // Build up the mapping of revertible type traits, for future use.
1078 if (RevertibleTypeTraits
.empty()) {
1079 #define RTT_JOIN(X,Y) X##Y
1080 #define REVERTIBLE_TYPE_TRAIT(Name) \
1081 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
1082 = RTT_JOIN(tok::kw_,Name)
1084 REVERTIBLE_TYPE_TRAIT(__is_abstract
);
1085 REVERTIBLE_TYPE_TRAIT(__is_aggregate
);
1086 REVERTIBLE_TYPE_TRAIT(__is_arithmetic
);
1087 REVERTIBLE_TYPE_TRAIT(__is_array
);
1088 REVERTIBLE_TYPE_TRAIT(__is_assignable
);
1089 REVERTIBLE_TYPE_TRAIT(__is_base_of
);
1090 REVERTIBLE_TYPE_TRAIT(__is_bounded_array
);
1091 REVERTIBLE_TYPE_TRAIT(__is_class
);
1092 REVERTIBLE_TYPE_TRAIT(__is_complete_type
);
1093 REVERTIBLE_TYPE_TRAIT(__is_compound
);
1094 REVERTIBLE_TYPE_TRAIT(__is_const
);
1095 REVERTIBLE_TYPE_TRAIT(__is_constructible
);
1096 REVERTIBLE_TYPE_TRAIT(__is_convertible
);
1097 REVERTIBLE_TYPE_TRAIT(__is_convertible_to
);
1098 REVERTIBLE_TYPE_TRAIT(__is_destructible
);
1099 REVERTIBLE_TYPE_TRAIT(__is_empty
);
1100 REVERTIBLE_TYPE_TRAIT(__is_enum
);
1101 REVERTIBLE_TYPE_TRAIT(__is_floating_point
);
1102 REVERTIBLE_TYPE_TRAIT(__is_final
);
1103 REVERTIBLE_TYPE_TRAIT(__is_function
);
1104 REVERTIBLE_TYPE_TRAIT(__is_fundamental
);
1105 REVERTIBLE_TYPE_TRAIT(__is_integral
);
1106 REVERTIBLE_TYPE_TRAIT(__is_interface_class
);
1107 REVERTIBLE_TYPE_TRAIT(__is_literal
);
1108 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr
);
1109 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference
);
1110 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer
);
1111 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer
);
1112 REVERTIBLE_TYPE_TRAIT(__is_member_pointer
);
1113 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable
);
1114 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible
);
1115 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible
);
1116 REVERTIBLE_TYPE_TRAIT(__is_nullptr
);
1117 REVERTIBLE_TYPE_TRAIT(__is_object
);
1118 REVERTIBLE_TYPE_TRAIT(__is_pod
);
1119 REVERTIBLE_TYPE_TRAIT(__is_pointer
);
1120 REVERTIBLE_TYPE_TRAIT(__is_polymorphic
);
1121 REVERTIBLE_TYPE_TRAIT(__is_reference
);
1122 REVERTIBLE_TYPE_TRAIT(__is_referenceable
);
1123 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr
);
1124 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference
);
1125 REVERTIBLE_TYPE_TRAIT(__is_same
);
1126 REVERTIBLE_TYPE_TRAIT(__is_scalar
);
1127 REVERTIBLE_TYPE_TRAIT(__is_scoped_enum
);
1128 REVERTIBLE_TYPE_TRAIT(__is_sealed
);
1129 REVERTIBLE_TYPE_TRAIT(__is_signed
);
1130 REVERTIBLE_TYPE_TRAIT(__is_standard_layout
);
1131 REVERTIBLE_TYPE_TRAIT(__is_trivial
);
1132 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable
);
1133 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible
);
1134 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable
);
1135 REVERTIBLE_TYPE_TRAIT(__is_unbounded_array
);
1136 REVERTIBLE_TYPE_TRAIT(__is_union
);
1137 REVERTIBLE_TYPE_TRAIT(__is_unsigned
);
1138 REVERTIBLE_TYPE_TRAIT(__is_void
);
1139 REVERTIBLE_TYPE_TRAIT(__is_volatile
);
1140 REVERTIBLE_TYPE_TRAIT(__reference_binds_to_temporary
);
1141 REVERTIBLE_TYPE_TRAIT(__reference_constructs_from_temporary
);
1142 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
1143 REVERTIBLE_TYPE_TRAIT(RTT_JOIN(__, Trait));
1144 #include "clang/Basic/TransformTypeTraits.def"
1145 #undef REVERTIBLE_TYPE_TRAIT
1149 // If we find that this is in fact the name of a type trait,
1150 // update the token kind in place and parse again to treat it as
1151 // the appropriate kind of type trait.
1152 llvm::SmallDenseMap
<IdentifierInfo
*, tok::TokenKind
>::iterator Known
1153 = RevertibleTypeTraits
.find(II
);
1154 if (Known
!= RevertibleTypeTraits
.end()) {
1155 Tok
.setKind(Known
->second
);
1156 return ParseCastExpression(ParseKind
, isAddressOfOperand
,
1157 NotCastExpr
, isTypeCast
,
1158 isVectorLiteral
, NotPrimaryExpression
);
1162 if ((!ColonIsSacred
&& Next
.is(tok::colon
)) ||
1163 Next
.isOneOf(tok::coloncolon
, tok::less
, tok::l_paren
,
1165 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1166 if (TryAnnotateTypeOrScopeToken())
1168 if (!Tok
.is(tok::identifier
))
1169 return ParseCastExpression(ParseKind
, isAddressOfOperand
,
1170 NotCastExpr
, isTypeCast
,
1172 NotPrimaryExpression
);
1176 // Consume the identifier so that we can see if it is followed by a '(' or
1178 IdentifierInfo
&II
= *Tok
.getIdentifierInfo();
1179 SourceLocation ILoc
= ConsumeToken();
1181 // Support 'Class.property' and 'super.property' notation.
1182 if (getLangOpts().ObjC
&& Tok
.is(tok::period
) &&
1183 (Actions
.getTypeName(II
, ILoc
, getCurScope()) ||
1184 // Allow the base to be 'super' if in an objc-method.
1185 (&II
== Ident_super
&& getCurScope()->isInObjcMethodScope()))) {
1188 if (Tok
.is(tok::code_completion
) && &II
!= Ident_super
) {
1190 Actions
.CodeCompleteObjCClassPropertyRefExpr(
1191 getCurScope(), II
, ILoc
, ExprStatementTokLoc
== ILoc
);
1194 // Allow either an identifier or the keyword 'class' (in C++).
1195 if (Tok
.isNot(tok::identifier
) &&
1196 !(getLangOpts().CPlusPlus
&& Tok
.is(tok::kw_class
))) {
1197 Diag(Tok
, diag::err_expected_property_name
);
1200 IdentifierInfo
&PropertyName
= *Tok
.getIdentifierInfo();
1201 SourceLocation PropertyLoc
= ConsumeToken();
1203 Res
= Actions
.ActOnClassPropertyRefExpr(II
, PropertyName
,
1208 // In an Objective-C method, if we have "super" followed by an identifier,
1209 // the token sequence is ill-formed. However, if there's a ':' or ']' after
1210 // that identifier, this is probably a message send with a missing open
1211 // bracket. Treat it as such.
1212 if (getLangOpts().ObjC
&& &II
== Ident_super
&& !InMessageExpression
&&
1213 getCurScope()->isInObjcMethodScope() &&
1214 ((Tok
.is(tok::identifier
) &&
1215 (NextToken().is(tok::colon
) || NextToken().is(tok::r_square
))) ||
1216 Tok
.is(tok::code_completion
))) {
1217 Res
= ParseObjCMessageExpressionBody(SourceLocation(), ILoc
, nullptr,
1222 // If we have an Objective-C class name followed by an identifier
1223 // and either ':' or ']', this is an Objective-C class message
1224 // send that's missing the opening '['. Recovery
1225 // appropriately. Also take this path if we're performing code
1226 // completion after an Objective-C class name.
1227 if (getLangOpts().ObjC
&&
1228 ((Tok
.is(tok::identifier
) && !InMessageExpression
) ||
1229 Tok
.is(tok::code_completion
))) {
1230 const Token
& Next
= NextToken();
1231 if (Tok
.is(tok::code_completion
) ||
1232 Next
.is(tok::colon
) || Next
.is(tok::r_square
))
1233 if (ParsedType Typ
= Actions
.getTypeName(II
, ILoc
, getCurScope()))
1234 if (Typ
.get()->isObjCObjectOrInterfaceType()) {
1235 // Fake up a Declarator to use with ActOnTypeName.
1236 DeclSpec
DS(AttrFactory
);
1237 DS
.SetRangeStart(ILoc
);
1238 DS
.SetRangeEnd(ILoc
);
1239 const char *PrevSpec
= nullptr;
1241 DS
.SetTypeSpecType(TST_typename
, ILoc
, PrevSpec
, DiagID
, Typ
,
1242 Actions
.getASTContext().getPrintingPolicy());
1244 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
1245 DeclaratorContext::TypeName
);
1246 TypeResult Ty
= Actions
.ActOnTypeName(getCurScope(),
1251 Res
= ParseObjCMessageExpressionBody(SourceLocation(),
1258 // Make sure to pass down the right value for isAddressOfOperand.
1259 if (isAddressOfOperand
&& isPostfixExpressionSuffixStart())
1260 isAddressOfOperand
= false;
1262 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1263 // need to know whether or not this identifier is a function designator or
1266 CXXScopeSpec ScopeSpec
;
1267 SourceLocation TemplateKWLoc
;
1269 CastExpressionIdValidator
Validator(
1271 /*AllowTypes=*/isTypeCast
!= NotTypeCast
,
1272 /*AllowNonTypes=*/isTypeCast
!= IsTypeCast
);
1273 Validator
.IsAddressOfOperand
= isAddressOfOperand
;
1274 if (Tok
.isOneOf(tok::periodstar
, tok::arrowstar
)) {
1275 Validator
.WantExpressionKeywords
= false;
1276 Validator
.WantRemainingKeywords
= false;
1278 Validator
.WantRemainingKeywords
= Tok
.isNot(tok::r_paren
);
1280 Name
.setIdentifier(&II
, ILoc
);
1281 Res
= Actions
.ActOnIdExpression(
1282 getCurScope(), ScopeSpec
, TemplateKWLoc
, Name
, Tok
.is(tok::l_paren
),
1283 isAddressOfOperand
, &Validator
,
1284 /*IsInlineAsmIdentifier=*/false,
1285 Tok
.is(tok::r_paren
) ? nullptr : &Replacement
);
1286 if (!Res
.isInvalid() && Res
.isUnset()) {
1287 UnconsumeToken(Replacement
);
1288 return ParseCastExpression(ParseKind
, isAddressOfOperand
,
1289 NotCastExpr
, isTypeCast
,
1290 /*isVectorLiteral=*/false,
1291 NotPrimaryExpression
);
1293 if (!Res
.isInvalid() && Tok
.is(tok::less
))
1294 checkPotentialAngleBracket(Res
);
1297 case tok::char_constant
: // constant: character-constant
1298 case tok::wide_char_constant
:
1299 case tok::utf8_char_constant
:
1300 case tok::utf16_char_constant
:
1301 case tok::utf32_char_constant
:
1302 Res
= Actions
.ActOnCharacterConstant(Tok
, /*UDLScope*/getCurScope());
1305 case tok::kw___func__
: // primary-expression: __func__ [C99 6.4.2.2]
1306 case tok::kw___FUNCTION__
: // primary-expression: __FUNCTION__ [GNU]
1307 case tok::kw___FUNCDNAME__
: // primary-expression: __FUNCDNAME__ [MS]
1308 case tok::kw___FUNCSIG__
: // primary-expression: __FUNCSIG__ [MS]
1309 case tok::kw_L__FUNCTION__
: // primary-expression: L__FUNCTION__ [MS]
1310 case tok::kw_L__FUNCSIG__
: // primary-expression: L__FUNCSIG__ [MS]
1311 case tok::kw___PRETTY_FUNCTION__
: // primary-expression: __P..Y_F..N__ [GNU]
1312 // Function local predefined macros are represented by PredefinedExpr except
1313 // when Microsoft extensions are enabled and one of these macros is adjacent
1314 // to a string literal or another one of these macros.
1315 if (!(getLangOpts().MicrosoftExt
&&
1316 tokenIsLikeStringLiteral(Tok
, getLangOpts()) &&
1317 tokenIsLikeStringLiteral(NextToken(), getLangOpts()))) {
1318 Res
= Actions
.ActOnPredefinedExpr(Tok
.getLocation(), SavedKind
);
1322 [[fallthrough
]]; // treat MS function local macros as concatenable strings
1323 case tok::string_literal
: // primary-expression: string-literal
1324 case tok::wide_string_literal
:
1325 case tok::utf8_string_literal
:
1326 case tok::utf16_string_literal
:
1327 case tok::utf32_string_literal
:
1328 Res
= ParseStringLiteralExpression(true);
1330 case tok::kw__Generic
: // primary-expression: generic-selection [C11 6.5.1]
1331 Res
= ParseGenericSelectionExpression();
1333 case tok::kw___builtin_available
:
1334 Res
= ParseAvailabilityCheckExpr(Tok
.getLocation());
1336 case tok::kw___builtin_va_arg
:
1337 case tok::kw___builtin_offsetof
:
1338 case tok::kw___builtin_choose_expr
:
1339 case tok::kw___builtin_astype
: // primary-expression: [OCL] as_type()
1340 case tok::kw___builtin_convertvector
:
1341 case tok::kw___builtin_COLUMN
:
1342 case tok::kw___builtin_FILE
:
1343 case tok::kw___builtin_FILE_NAME
:
1344 case tok::kw___builtin_FUNCTION
:
1345 case tok::kw___builtin_FUNCSIG
:
1346 case tok::kw___builtin_LINE
:
1347 case tok::kw___builtin_source_location
:
1348 if (NotPrimaryExpression
)
1349 *NotPrimaryExpression
= true;
1350 // This parses the complete suffix; we can return early.
1351 return ParseBuiltinPrimaryExpression();
1352 case tok::kw___null
:
1353 Res
= Actions
.ActOnGNUNullExpr(ConsumeToken());
1356 case tok::plusplus
: // unary-expression: '++' unary-expression [C99]
1357 case tok::minusminus
: { // unary-expression: '--' unary-expression [C99]
1358 if (NotPrimaryExpression
)
1359 *NotPrimaryExpression
= true;
1360 // C++ [expr.unary] has:
1361 // unary-expression:
1362 // ++ cast-expression
1363 // -- cast-expression
1364 Token SavedTok
= Tok
;
1367 PreferredType
.enterUnary(Actions
, Tok
.getLocation(), SavedTok
.getKind(),
1368 SavedTok
.getLocation());
1369 // One special case is implicitly handled here: if the preceding tokens are
1370 // an ambiguous cast expression, such as "(T())++", then we recurse to
1371 // determine whether the '++' is prefix or postfix.
1372 Res
= ParseCastExpression(getLangOpts().CPlusPlus
?
1373 UnaryExprOnly
: AnyCastExpr
,
1374 /*isAddressOfOperand*/false, NotCastExpr
,
1377 // If we return with NotCastExpr = true, we must not consume any tokens,
1378 // so put the token back where we found it.
1379 assert(Res
.isInvalid());
1380 UnconsumeToken(SavedTok
);
1383 if (!Res
.isInvalid()) {
1384 Expr
*Arg
= Res
.get();
1385 Res
= Actions
.ActOnUnaryOp(getCurScope(), SavedTok
.getLocation(),
1387 if (Res
.isInvalid())
1388 Res
= Actions
.CreateRecoveryExpr(SavedTok
.getLocation(),
1389 Arg
->getEndLoc(), Arg
);
1393 case tok::amp
: { // unary-expression: '&' cast-expression
1394 if (NotPrimaryExpression
)
1395 *NotPrimaryExpression
= true;
1396 // Special treatment because of member pointers
1397 SourceLocation SavedLoc
= ConsumeToken();
1398 PreferredType
.enterUnary(Actions
, Tok
.getLocation(), tok::amp
, SavedLoc
);
1400 Res
= ParseCastExpression(AnyCastExpr
, /*isAddressOfOperand=*/true);
1401 if (!Res
.isInvalid()) {
1402 Expr
*Arg
= Res
.get();
1403 Res
= Actions
.ActOnUnaryOp(getCurScope(), SavedLoc
, SavedKind
, Arg
);
1404 if (Res
.isInvalid())
1405 Res
= Actions
.CreateRecoveryExpr(Tok
.getLocation(), Arg
->getEndLoc(),
1411 case tok::star
: // unary-expression: '*' cast-expression
1412 case tok::plus
: // unary-expression: '+' cast-expression
1413 case tok::minus
: // unary-expression: '-' cast-expression
1414 case tok::tilde
: // unary-expression: '~' cast-expression
1415 case tok::exclaim
: // unary-expression: '!' cast-expression
1416 case tok::kw___real
: // unary-expression: '__real' cast-expression [GNU]
1417 case tok::kw___imag
: { // unary-expression: '__imag' cast-expression [GNU]
1418 if (NotPrimaryExpression
)
1419 *NotPrimaryExpression
= true;
1420 SourceLocation SavedLoc
= ConsumeToken();
1421 PreferredType
.enterUnary(Actions
, Tok
.getLocation(), SavedKind
, SavedLoc
);
1422 Res
= ParseCastExpression(AnyCastExpr
);
1423 if (!Res
.isInvalid()) {
1424 Expr
*Arg
= Res
.get();
1425 Res
= Actions
.ActOnUnaryOp(getCurScope(), SavedLoc
, SavedKind
, Arg
,
1426 isAddressOfOperand
);
1427 if (Res
.isInvalid())
1428 Res
= Actions
.CreateRecoveryExpr(SavedLoc
, Arg
->getEndLoc(), Arg
);
1433 case tok::kw_co_await
: { // unary-expression: 'co_await' cast-expression
1434 if (NotPrimaryExpression
)
1435 *NotPrimaryExpression
= true;
1436 SourceLocation CoawaitLoc
= ConsumeToken();
1437 Res
= ParseCastExpression(AnyCastExpr
);
1438 if (!Res
.isInvalid())
1439 Res
= Actions
.ActOnCoawaitExpr(getCurScope(), CoawaitLoc
, Res
.get());
1443 case tok::kw___extension__
:{//unary-expression:'__extension__' cast-expr [GNU]
1444 // __extension__ silences extension warnings in the subexpression.
1445 if (NotPrimaryExpression
)
1446 *NotPrimaryExpression
= true;
1447 ExtensionRAIIObject
O(Diags
); // Use RAII to do this.
1448 SourceLocation SavedLoc
= ConsumeToken();
1449 Res
= ParseCastExpression(AnyCastExpr
);
1450 if (!Res
.isInvalid())
1451 Res
= Actions
.ActOnUnaryOp(getCurScope(), SavedLoc
, SavedKind
, Res
.get());
1454 case tok::kw__Alignof
: // unary-expression: '_Alignof' '(' type-name ')'
1455 if (!getLangOpts().C11
)
1456 Diag(Tok
, diag::ext_c11_feature
) << Tok
.getName();
1458 case tok::kw_alignof
: // unary-expression: 'alignof' '(' type-id ')'
1459 case tok::kw___alignof
: // unary-expression: '__alignof' unary-expression
1460 // unary-expression: '__alignof' '(' type-name ')'
1461 case tok::kw_sizeof
: // unary-expression: 'sizeof' unary-expression
1462 // unary-expression: 'sizeof' '(' type-name ')'
1463 case tok::kw_vec_step
: // unary-expression: OpenCL 'vec_step' expression
1464 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1465 case tok::kw___builtin_omp_required_simd_align
:
1466 case tok::kw___builtin_vectorelements
:
1467 if (NotPrimaryExpression
)
1468 *NotPrimaryExpression
= true;
1469 AllowSuffix
= false;
1470 Res
= ParseUnaryExprOrTypeTraitExpression();
1472 case tok::ampamp
: { // unary-expression: '&&' identifier
1473 if (NotPrimaryExpression
)
1474 *NotPrimaryExpression
= true;
1475 SourceLocation AmpAmpLoc
= ConsumeToken();
1476 if (Tok
.isNot(tok::identifier
))
1477 return ExprError(Diag(Tok
, diag::err_expected
) << tok::identifier
);
1479 if (getCurScope()->getFnParent() == nullptr)
1480 return ExprError(Diag(Tok
, diag::err_address_of_label_outside_fn
));
1482 Diag(AmpAmpLoc
, diag::ext_gnu_address_of_label
);
1483 LabelDecl
*LD
= Actions
.LookupOrCreateLabel(Tok
.getIdentifierInfo(),
1485 Res
= Actions
.ActOnAddrLabel(AmpAmpLoc
, Tok
.getLocation(), LD
);
1487 AllowSuffix
= false;
1490 case tok::kw_const_cast
:
1491 case tok::kw_dynamic_cast
:
1492 case tok::kw_reinterpret_cast
:
1493 case tok::kw_static_cast
:
1494 case tok::kw_addrspace_cast
:
1495 if (NotPrimaryExpression
)
1496 *NotPrimaryExpression
= true;
1497 Res
= ParseCXXCasts();
1499 case tok::kw___builtin_bit_cast
:
1500 if (NotPrimaryExpression
)
1501 *NotPrimaryExpression
= true;
1502 Res
= ParseBuiltinBitCast();
1504 case tok::kw_typeid
:
1505 if (NotPrimaryExpression
)
1506 *NotPrimaryExpression
= true;
1507 Res
= ParseCXXTypeid();
1509 case tok::kw___uuidof
:
1510 if (NotPrimaryExpression
)
1511 *NotPrimaryExpression
= true;
1512 Res
= ParseCXXUuidof();
1515 Res
= ParseCXXThis();
1517 case tok::kw___builtin_sycl_unique_stable_name
:
1518 Res
= ParseSYCLUniqueStableNameExpression();
1521 case tok::annot_typename
:
1522 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1523 TypeResult Type
= getTypeAnnotation(Tok
);
1525 // Fake up a Declarator to use with ActOnTypeName.
1526 DeclSpec
DS(AttrFactory
);
1527 DS
.SetRangeStart(Tok
.getLocation());
1528 DS
.SetRangeEnd(Tok
.getLastLoc());
1530 const char *PrevSpec
= nullptr;
1532 DS
.SetTypeSpecType(TST_typename
, Tok
.getAnnotationEndLoc(),
1533 PrevSpec
, DiagID
, Type
,
1534 Actions
.getASTContext().getPrintingPolicy());
1536 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
1537 DeclaratorContext::TypeName
);
1538 TypeResult Ty
= Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
1542 ConsumeAnnotationToken();
1543 Res
= ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1549 case tok::annot_decltype
:
1551 case tok::kw_wchar_t
:
1552 case tok::kw_char8_t
:
1553 case tok::kw_char16_t
:
1554 case tok::kw_char32_t
:
1559 case tok::kw___int64
:
1560 case tok::kw___int128
:
1561 case tok::kw__ExtInt
:
1562 case tok::kw__BitInt
:
1563 case tok::kw_signed
:
1564 case tok::kw_unsigned
:
1567 case tok::kw_double
:
1568 case tok::kw___bf16
:
1569 case tok::kw__Float16
:
1570 case tok::kw___float128
:
1571 case tok::kw___ibm128
:
1574 case tok::kw_typename
:
1575 case tok::kw_typeof
:
1576 case tok::kw___vector
:
1577 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1578 #include "clang/Basic/OpenCLImageTypes.def"
1580 if (!getLangOpts().CPlusPlus
) {
1581 Diag(Tok
, diag::err_expected_expression
);
1585 // Everything henceforth is a postfix-expression.
1586 if (NotPrimaryExpression
)
1587 *NotPrimaryExpression
= true;
1589 if (SavedKind
== tok::kw_typename
) {
1590 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1591 // typename-specifier braced-init-list
1592 if (TryAnnotateTypeOrScopeToken())
1595 if (!Actions
.isSimpleTypeSpecifier(Tok
.getKind()))
1596 // We are trying to parse a simple-type-specifier but might not get such
1597 // a token after error recovery.
1601 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1602 // simple-type-specifier braced-init-list
1604 DeclSpec
DS(AttrFactory
);
1606 ParseCXXSimpleTypeSpecifier(DS
);
1607 if (Tok
.isNot(tok::l_paren
) &&
1608 (!getLangOpts().CPlusPlus11
|| Tok
.isNot(tok::l_brace
)))
1609 return ExprError(Diag(Tok
, diag::err_expected_lparen_after_type
)
1610 << DS
.getSourceRange());
1612 if (Tok
.is(tok::l_brace
))
1613 Diag(Tok
, diag::warn_cxx98_compat_generalized_initializer_lists
);
1615 Res
= ParseCXXTypeConstructExpression(DS
);
1619 case tok::annot_cxxscope
: { // [C++] id-expression: qualified-id
1620 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1621 // (We can end up in this situation after tentative parsing.)
1622 if (TryAnnotateTypeOrScopeToken())
1624 if (!Tok
.is(tok::annot_cxxscope
))
1625 return ParseCastExpression(ParseKind
, isAddressOfOperand
, NotCastExpr
,
1626 isTypeCast
, isVectorLiteral
,
1627 NotPrimaryExpression
);
1629 Token Next
= NextToken();
1630 if (Next
.is(tok::annot_template_id
)) {
1631 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Next
);
1632 if (TemplateId
->Kind
== TNK_Type_template
) {
1633 // We have a qualified template-id that we know refers to a
1634 // type, translate it into a type and continue parsing as a
1637 ParseOptionalCXXScopeSpecifier(SS
, /*ObjectType=*/nullptr,
1638 /*ObjectHasErrors=*/false,
1639 /*EnteringContext=*/false);
1640 AnnotateTemplateIdTokenAsType(SS
, ImplicitTypenameContext::Yes
);
1641 return ParseCastExpression(ParseKind
, isAddressOfOperand
, NotCastExpr
,
1642 isTypeCast
, isVectorLiteral
,
1643 NotPrimaryExpression
);
1647 // Parse as an id-expression.
1648 Res
= ParseCXXIdExpression(isAddressOfOperand
);
1652 case tok::annot_template_id
: { // [C++] template-id
1653 TemplateIdAnnotation
*TemplateId
= takeTemplateIdAnnotation(Tok
);
1654 if (TemplateId
->Kind
== TNK_Type_template
) {
1655 // We have a template-id that we know refers to a type,
1656 // translate it into a type and continue parsing as a cast
1659 AnnotateTemplateIdTokenAsType(SS
, ImplicitTypenameContext::Yes
);
1660 return ParseCastExpression(ParseKind
, isAddressOfOperand
,
1661 NotCastExpr
, isTypeCast
, isVectorLiteral
,
1662 NotPrimaryExpression
);
1665 // Fall through to treat the template-id as an id-expression.
1669 case tok::kw_operator
: // [C++] id-expression: operator/conversion-function-id
1670 Res
= ParseCXXIdExpression(isAddressOfOperand
);
1673 case tok::coloncolon
: {
1674 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1675 // annotates the token, tail recurse.
1676 if (TryAnnotateTypeOrScopeToken())
1678 if (!Tok
.is(tok::coloncolon
))
1679 return ParseCastExpression(ParseKind
, isAddressOfOperand
, isTypeCast
,
1680 isVectorLiteral
, NotPrimaryExpression
);
1682 // ::new -> [C++] new-expression
1683 // ::delete -> [C++] delete-expression
1684 SourceLocation CCLoc
= ConsumeToken();
1685 if (Tok
.is(tok::kw_new
)) {
1686 if (NotPrimaryExpression
)
1687 *NotPrimaryExpression
= true;
1688 Res
= ParseCXXNewExpression(true, CCLoc
);
1689 AllowSuffix
= false;
1692 if (Tok
.is(tok::kw_delete
)) {
1693 if (NotPrimaryExpression
)
1694 *NotPrimaryExpression
= true;
1695 Res
= ParseCXXDeleteExpression(true, CCLoc
);
1696 AllowSuffix
= false;
1700 // This is not a type name or scope specifier, it is an invalid expression.
1701 Diag(CCLoc
, diag::err_expected_expression
);
1705 case tok::kw_new
: // [C++] new-expression
1706 if (NotPrimaryExpression
)
1707 *NotPrimaryExpression
= true;
1708 Res
= ParseCXXNewExpression(false, Tok
.getLocation());
1709 AllowSuffix
= false;
1712 case tok::kw_delete
: // [C++] delete-expression
1713 if (NotPrimaryExpression
)
1714 *NotPrimaryExpression
= true;
1715 Res
= ParseCXXDeleteExpression(false, Tok
.getLocation());
1716 AllowSuffix
= false;
1719 case tok::kw_requires
: // [C++2a] requires-expression
1720 Res
= ParseRequiresExpression();
1721 AllowSuffix
= false;
1724 case tok::kw_noexcept
: { // [C++0x] 'noexcept' '(' expression ')'
1725 if (NotPrimaryExpression
)
1726 *NotPrimaryExpression
= true;
1727 Diag(Tok
, diag::warn_cxx98_compat_noexcept_expr
);
1728 SourceLocation KeyLoc
= ConsumeToken();
1729 BalancedDelimiterTracker
T(*this, tok::l_paren
);
1731 if (T
.expectAndConsume(diag::err_expected_lparen_after
, "noexcept"))
1733 // C++11 [expr.unary.noexcept]p1:
1734 // The noexcept operator determines whether the evaluation of its operand,
1735 // which is an unevaluated operand, can throw an exception.
1736 EnterExpressionEvaluationContext
Unevaluated(
1737 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
);
1738 Res
= ParseExpression();
1742 if (!Res
.isInvalid())
1743 Res
= Actions
.ActOnNoexceptExpr(KeyLoc
, T
.getOpenLocation(), Res
.get(),
1744 T
.getCloseLocation());
1745 AllowSuffix
= false;
1749 #define TYPE_TRAIT(N,Spelling,K) \
1750 case tok::kw_##Spelling:
1751 #include "clang/Basic/TokenKinds.def"
1752 Res
= ParseTypeTrait();
1755 case tok::kw___array_rank
:
1756 case tok::kw___array_extent
:
1757 if (NotPrimaryExpression
)
1758 *NotPrimaryExpression
= true;
1759 Res
= ParseArrayTypeTrait();
1762 case tok::kw___is_lvalue_expr
:
1763 case tok::kw___is_rvalue_expr
:
1764 if (NotPrimaryExpression
)
1765 *NotPrimaryExpression
= true;
1766 Res
= ParseExpressionTrait();
1770 if (NotPrimaryExpression
)
1771 *NotPrimaryExpression
= true;
1772 SourceLocation AtLoc
= ConsumeToken();
1773 return ParseObjCAtExpression(AtLoc
);
1776 Res
= ParseBlockLiteralExpression();
1778 case tok::code_completion
: {
1780 Actions
.CodeCompleteExpression(getCurScope(),
1781 PreferredType
.get(Tok
.getLocation()));
1784 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1785 #include "clang/Basic/TransformTypeTraits.def"
1786 // HACK: libstdc++ uses some of the transform-type-traits as alias
1787 // templates, so we need to work around this.
1788 if (!NextToken().is(tok::l_paren
)) {
1789 Tok
.setKind(tok::identifier
);
1790 Diag(Tok
, diag::ext_keyword_as_ident
)
1791 << Tok
.getIdentifierInfo()->getName() << 0;
1792 goto ParseIdentifier
;
1794 goto ExpectedExpression
;
1796 if (getLangOpts().CPlusPlus11
) {
1797 if (getLangOpts().ObjC
) {
1798 // C++11 lambda expressions and Objective-C message sends both start with a
1799 // square bracket. There are three possibilities here:
1800 // we have a valid lambda expression, we have an invalid lambda
1801 // expression, or we have something that doesn't appear to be a lambda.
1802 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1803 Res
= TryParseLambdaExpression();
1804 if (!Res
.isInvalid() && !Res
.get()) {
1805 // We assume Objective-C++ message expressions are not
1806 // primary-expressions.
1807 if (NotPrimaryExpression
)
1808 *NotPrimaryExpression
= true;
1809 Res
= ParseObjCMessageExpression();
1813 Res
= ParseLambdaExpression();
1816 if (getLangOpts().ObjC
) {
1817 Res
= ParseObjCMessageExpression();
1827 // Check to see whether Res is a function designator only. If it is and we
1828 // are compiling for OpenCL, we need to return an error as this implies
1829 // that the address of the function is being taken, which is illegal in CL.
1831 if (ParseKind
== PrimaryExprOnly
)
1832 // This is strictly a primary-expression - no postfix-expr pieces should be
1837 // FIXME: Don't parse a primary-expression suffix if we encountered a parse
1839 if (Res
.isInvalid())
1842 switch (Tok
.getKind()) {
1846 case tok::minusminus
:
1847 // "expected ';'" or similar is probably the right diagnostic here. Let
1848 // the caller decide what to do.
1849 if (Tok
.isAtStartOfLine())
1861 // This was a unary-expression for which a postfix-expression suffix is
1862 // not permitted by the grammar (eg, a sizeof expression or
1863 // new-expression or similar). Diagnose but parse the suffix anyway.
1864 Diag(Tok
.getLocation(), diag::err_postfix_after_unary_requires_parens
)
1865 << Tok
.getKind() << Res
.get()->getSourceRange()
1866 << FixItHint::CreateInsertion(Res
.get()->getBeginLoc(), "(")
1867 << FixItHint::CreateInsertion(PP
.getLocForEndOfToken(PrevTokLocation
),
1871 // These can be followed by postfix-expr pieces.
1872 PreferredType
= SavedType
;
1873 Res
= ParsePostfixExpressionSuffix(Res
);
1874 if (getLangOpts().OpenCL
&&
1875 !getActions().getOpenCLOptions().isAvailableOption(
1876 "__cl_clang_function_pointers", getLangOpts()))
1877 if (Expr
*PostfixExpr
= Res
.get()) {
1878 QualType Ty
= PostfixExpr
->getType();
1879 if (!Ty
.isNull() && Ty
->isFunctionType()) {
1880 Diag(PostfixExpr
->getExprLoc(),
1881 diag::err_opencl_taking_function_address_parser
);
1889 /// Once the leading part of a postfix-expression is parsed, this
1890 /// method parses any suffixes that apply.
1893 /// postfix-expression: [C99 6.5.2]
1894 /// primary-expression
1895 /// postfix-expression '[' expression ']'
1896 /// postfix-expression '[' braced-init-list ']'
1897 /// postfix-expression '[' expression-list [opt] ']' [C++23 12.4.5]
1898 /// postfix-expression '(' argument-expression-list[opt] ')'
1899 /// postfix-expression '.' identifier
1900 /// postfix-expression '->' identifier
1901 /// postfix-expression '++'
1902 /// postfix-expression '--'
1903 /// '(' type-name ')' '{' initializer-list '}'
1904 /// '(' type-name ')' '{' initializer-list ',' '}'
1906 /// argument-expression-list: [C99 6.5.2]
1907 /// argument-expression ...[opt]
1908 /// argument-expression-list ',' assignment-expression ...[opt]
1911 Parser::ParsePostfixExpressionSuffix(ExprResult LHS
) {
1912 // Now that the primary-expression piece of the postfix-expression has been
1913 // parsed, see if there are any postfix-expression pieces here.
1915 auto SavedType
= PreferredType
;
1917 // Each iteration relies on preferred type for the whole expression.
1918 PreferredType
= SavedType
;
1919 switch (Tok
.getKind()) {
1920 case tok::code_completion
:
1921 if (InMessageExpression
)
1925 Actions
.CodeCompletePostfixExpression(
1926 getCurScope(), LHS
, PreferredType
.get(Tok
.getLocation()));
1929 case tok::identifier
:
1930 // If we see identifier: after an expression, and we're not already in a
1931 // message send, then this is probably a message send with a missing
1932 // opening bracket '['.
1933 if (getLangOpts().ObjC
&& !InMessageExpression
&&
1934 (NextToken().is(tok::colon
) || NextToken().is(tok::r_square
))) {
1935 LHS
= ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1936 nullptr, LHS
.get());
1939 // Fall through; this isn't a message send.
1942 default: // Not a postfix-expression suffix.
1944 case tok::l_square
: { // postfix-expression: p-e '[' expression ']'
1945 // If we have a array postfix expression that starts on a new line and
1946 // Objective-C is enabled, it is highly likely that the user forgot a
1947 // semicolon after the base expression and that the array postfix-expr is
1948 // actually another message send. In this case, do some look-ahead to see
1949 // if the contents of the square brackets are obviously not a valid
1950 // expression and recover by pretending there is no suffix.
1951 if (getLangOpts().ObjC
&& Tok
.isAtStartOfLine() &&
1952 isSimpleObjCMessageExpression())
1955 // Reject array indices starting with a lambda-expression. '[[' is
1956 // reserved for attributes.
1957 if (CheckProhibitedCXX11Attribute()) {
1958 (void)Actions
.CorrectDelayedTyposInExpr(LHS
);
1961 BalancedDelimiterTracker
T(*this, tok::l_square
);
1963 Loc
= T
.getOpenLocation();
1964 ExprResult Length
, Stride
;
1965 SourceLocation ColonLocFirst
, ColonLocSecond
;
1966 ExprVector ArgExprs
;
1967 bool HasError
= false;
1968 PreferredType
.enterSubscript(Actions
, Tok
.getLocation(), LHS
.get());
1970 // We try to parse a list of indexes in all language mode first
1971 // and, in we find 0 or one index, we try to parse an OpenMP array
1972 // section. This allow us to support C++23 multi dimensional subscript and
1973 // OpenMp sections in the same language mode.
1974 if (!getLangOpts().OpenMP
|| Tok
.isNot(tok::colon
)) {
1975 if (!getLangOpts().CPlusPlus23
) {
1977 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
)) {
1978 Diag(Tok
, diag::warn_cxx98_compat_generalized_initializer_lists
);
1979 Idx
= ParseBraceInitializer();
1981 Idx
= ParseExpression(); // May be a comma expression
1983 LHS
= Actions
.CorrectDelayedTyposInExpr(LHS
);
1984 Idx
= Actions
.CorrectDelayedTyposInExpr(Idx
);
1985 if (Idx
.isInvalid()) {
1988 ArgExprs
.push_back(Idx
.get());
1990 } else if (Tok
.isNot(tok::r_square
)) {
1991 if (ParseExpressionList(ArgExprs
)) {
1992 LHS
= Actions
.CorrectDelayedTyposInExpr(LHS
);
1998 if (ArgExprs
.size() <= 1 && getLangOpts().OpenMP
) {
1999 ColonProtectionRAIIObject
RAII(*this);
2000 if (Tok
.is(tok::colon
)) {
2002 ColonLocFirst
= ConsumeToken();
2003 if (Tok
.isNot(tok::r_square
) &&
2004 (getLangOpts().OpenMP
< 50 ||
2005 ((Tok
.isNot(tok::colon
) && getLangOpts().OpenMP
>= 50)))) {
2006 Length
= ParseExpression();
2007 Length
= Actions
.CorrectDelayedTyposInExpr(Length
);
2010 if (getLangOpts().OpenMP
>= 50 &&
2011 (OMPClauseKind
== llvm::omp::Clause::OMPC_to
||
2012 OMPClauseKind
== llvm::omp::Clause::OMPC_from
) &&
2013 Tok
.is(tok::colon
)) {
2015 ColonLocSecond
= ConsumeToken();
2016 if (Tok
.isNot(tok::r_square
)) {
2017 Stride
= ParseExpression();
2022 SourceLocation RLoc
= Tok
.getLocation();
2023 LHS
= Actions
.CorrectDelayedTyposInExpr(LHS
);
2025 if (!LHS
.isInvalid() && !HasError
&& !Length
.isInvalid() &&
2026 !Stride
.isInvalid() && Tok
.is(tok::r_square
)) {
2027 if (ColonLocFirst
.isValid() || ColonLocSecond
.isValid()) {
2028 LHS
= Actions
.ActOnOMPArraySectionExpr(
2029 LHS
.get(), Loc
, ArgExprs
.empty() ? nullptr : ArgExprs
[0],
2030 ColonLocFirst
, ColonLocSecond
, Length
.get(), Stride
.get(), RLoc
);
2032 LHS
= Actions
.ActOnArraySubscriptExpr(getCurScope(), LHS
.get(), Loc
,
2044 case tok::l_paren
: // p-e: p-e '(' argument-expression-list[opt] ')'
2045 case tok::lesslessless
: { // p-e: p-e '<<<' argument-expression-list '>>>'
2046 // '(' argument-expression-list[opt] ')'
2047 tok::TokenKind OpKind
= Tok
.getKind();
2048 InMessageExpressionRAIIObject
InMessage(*this, false);
2050 Expr
*ExecConfig
= nullptr;
2052 BalancedDelimiterTracker
PT(*this, tok::l_paren
);
2054 if (OpKind
== tok::lesslessless
) {
2055 ExprVector ExecConfigExprs
;
2056 SourceLocation OpenLoc
= ConsumeToken();
2058 if (ParseSimpleExpressionList(ExecConfigExprs
)) {
2059 (void)Actions
.CorrectDelayedTyposInExpr(LHS
);
2063 SourceLocation CloseLoc
;
2064 if (TryConsumeToken(tok::greatergreatergreater
, CloseLoc
)) {
2065 } else if (LHS
.isInvalid()) {
2066 SkipUntil(tok::greatergreatergreater
, StopAtSemi
);
2068 // There was an error closing the brackets
2069 Diag(Tok
, diag::err_expected
) << tok::greatergreatergreater
;
2070 Diag(OpenLoc
, diag::note_matching
) << tok::lesslessless
;
2071 SkipUntil(tok::greatergreatergreater
, StopAtSemi
);
2075 if (!LHS
.isInvalid()) {
2076 if (ExpectAndConsume(tok::l_paren
))
2079 Loc
= PrevTokLocation
;
2082 if (!LHS
.isInvalid()) {
2083 ExprResult ECResult
= Actions
.ActOnCUDAExecConfigExpr(getCurScope(),
2087 if (ECResult
.isInvalid())
2090 ExecConfig
= ECResult
.get();
2094 Loc
= PT
.getOpenLocation();
2097 ExprVector ArgExprs
;
2098 auto RunSignatureHelp
= [&]() -> QualType
{
2099 QualType PreferredType
= Actions
.ProduceCallSignatureHelp(
2100 LHS
.get(), ArgExprs
, PT
.getOpenLocation());
2101 CalledSignatureHelp
= true;
2102 return PreferredType
;
2104 if (OpKind
== tok::l_paren
|| !LHS
.isInvalid()) {
2105 if (Tok
.isNot(tok::r_paren
)) {
2106 if (ParseExpressionList(ArgExprs
, [&] {
2107 PreferredType
.enterFunctionArgument(Tok
.getLocation(),
2110 (void)Actions
.CorrectDelayedTyposInExpr(LHS
);
2111 // If we got an error when parsing expression list, we don't call
2112 // the CodeCompleteCall handler inside the parser. So call it here
2113 // to make sure we get overload suggestions even when we are in the
2114 // middle of a parameter.
2115 if (PP
.isCodeCompletionReached() && !CalledSignatureHelp
)
2118 } else if (LHS
.isInvalid()) {
2119 for (auto &E
: ArgExprs
)
2120 Actions
.CorrectDelayedTyposInExpr(E
);
2126 if (LHS
.isInvalid()) {
2127 SkipUntil(tok::r_paren
, StopAtSemi
);
2128 } else if (Tok
.isNot(tok::r_paren
)) {
2129 bool HadDelayedTypo
= false;
2130 if (Actions
.CorrectDelayedTyposInExpr(LHS
).get() != LHS
.get())
2131 HadDelayedTypo
= true;
2132 for (auto &E
: ArgExprs
)
2133 if (Actions
.CorrectDelayedTyposInExpr(E
).get() != E
)
2134 HadDelayedTypo
= true;
2135 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
2136 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
2137 // the unmatched l_paren.
2139 SkipUntil(tok::r_paren
, StopAtSemi
);
2144 Expr
*Fn
= LHS
.get();
2145 SourceLocation RParLoc
= Tok
.getLocation();
2146 LHS
= Actions
.ActOnCallExpr(getCurScope(), Fn
, Loc
, ArgExprs
, RParLoc
,
2148 if (LHS
.isInvalid()) {
2149 ArgExprs
.insert(ArgExprs
.begin(), Fn
);
2151 Actions
.CreateRecoveryExpr(Fn
->getBeginLoc(), RParLoc
, ArgExprs
);
2160 // postfix-expression: p-e '->' template[opt] id-expression
2161 // postfix-expression: p-e '.' template[opt] id-expression
2162 tok::TokenKind OpKind
= Tok
.getKind();
2163 SourceLocation OpLoc
= ConsumeToken(); // Eat the "." or "->" token.
2166 ParsedType ObjectType
;
2167 bool MayBePseudoDestructor
= false;
2168 Expr
* OrigLHS
= !LHS
.isInvalid() ? LHS
.get() : nullptr;
2170 PreferredType
.enterMemAccess(Actions
, Tok
.getLocation(), OrigLHS
);
2172 if (getLangOpts().CPlusPlus
&& !LHS
.isInvalid()) {
2173 Expr
*Base
= OrigLHS
;
2174 const Type
* BaseType
= Base
->getType().getTypePtrOrNull();
2175 if (BaseType
&& Tok
.is(tok::l_paren
) &&
2176 (BaseType
->isFunctionType() ||
2177 BaseType
->isSpecificPlaceholderType(BuiltinType::BoundMember
))) {
2178 Diag(OpLoc
, diag::err_function_is_not_record
)
2179 << OpKind
<< Base
->getSourceRange()
2180 << FixItHint::CreateRemoval(OpLoc
);
2181 return ParsePostfixExpressionSuffix(Base
);
2184 LHS
= Actions
.ActOnStartCXXMemberReference(getCurScope(), Base
, OpLoc
,
2186 MayBePseudoDestructor
);
2187 if (LHS
.isInvalid()) {
2188 // Clang will try to perform expression based completion as a
2189 // fallback, which is confusing in case of member references. So we
2190 // stop here without any completions.
2191 if (Tok
.is(tok::code_completion
)) {
2197 ParseOptionalCXXScopeSpecifier(
2198 SS
, ObjectType
, LHS
.get() && LHS
.get()->containsErrors(),
2199 /*EnteringContext=*/false, &MayBePseudoDestructor
);
2200 if (SS
.isNotEmpty())
2201 ObjectType
= nullptr;
2204 if (Tok
.is(tok::code_completion
)) {
2205 tok::TokenKind CorrectedOpKind
=
2206 OpKind
== tok::arrow
? tok::period
: tok::arrow
;
2207 ExprResult
CorrectedLHS(/*Invalid=*/true);
2208 if (getLangOpts().CPlusPlus
&& OrigLHS
) {
2209 // FIXME: Creating a TentativeAnalysisScope from outside Sema is a
2211 Sema::TentativeAnalysisScope
Trap(Actions
);
2212 CorrectedLHS
= Actions
.ActOnStartCXXMemberReference(
2213 getCurScope(), OrigLHS
, OpLoc
, CorrectedOpKind
, ObjectType
,
2214 MayBePseudoDestructor
);
2217 Expr
*Base
= LHS
.get();
2218 Expr
*CorrectedBase
= CorrectedLHS
.get();
2219 if (!CorrectedBase
&& !getLangOpts().CPlusPlus
)
2220 CorrectedBase
= Base
;
2222 // Code completion for a member access expression.
2224 Actions
.CodeCompleteMemberReferenceExpr(
2225 getCurScope(), Base
, CorrectedBase
, OpLoc
, OpKind
== tok::arrow
,
2226 Base
&& ExprStatementTokLoc
== Base
->getBeginLoc(),
2227 PreferredType
.get(Tok
.getLocation()));
2232 if (MayBePseudoDestructor
&& !LHS
.isInvalid()) {
2233 LHS
= ParseCXXPseudoDestructor(LHS
.get(), OpLoc
, OpKind
, SS
,
2238 // Either the action has told us that this cannot be a
2239 // pseudo-destructor expression (based on the type of base
2240 // expression), or we didn't see a '~' in the right place. We
2241 // can still parse a destructor name here, but in that case it
2242 // names a real destructor.
2243 // Allow explicit constructor calls in Microsoft mode.
2244 // FIXME: Add support for explicit call of template constructor.
2245 SourceLocation TemplateKWLoc
;
2247 if (getLangOpts().ObjC
&& OpKind
== tok::period
&&
2248 Tok
.is(tok::kw_class
)) {
2250 // After a '.' in a member access expression, treat the keyword
2251 // 'class' as if it were an identifier.
2253 // This hack allows property access to the 'class' method because it is
2254 // such a common method name. For other C++ keywords that are
2255 // Objective-C method names, one must use the message send syntax.
2256 IdentifierInfo
*Id
= Tok
.getIdentifierInfo();
2257 SourceLocation Loc
= ConsumeToken();
2258 Name
.setIdentifier(Id
, Loc
);
2259 } else if (ParseUnqualifiedId(
2260 SS
, ObjectType
, LHS
.get() && LHS
.get()->containsErrors(),
2261 /*EnteringContext=*/false,
2262 /*AllowDestructorName=*/true,
2263 /*AllowConstructorName=*/
2264 getLangOpts().MicrosoftExt
&& SS
.isNotEmpty(),
2265 /*AllowDeductionGuide=*/false, &TemplateKWLoc
, Name
)) {
2266 (void)Actions
.CorrectDelayedTyposInExpr(LHS
);
2270 if (!LHS
.isInvalid())
2271 LHS
= Actions
.ActOnMemberAccessExpr(getCurScope(), LHS
.get(), OpLoc
,
2272 OpKind
, SS
, TemplateKWLoc
, Name
,
2273 CurParsedObjCImpl
? CurParsedObjCImpl
->Dcl
2275 if (!LHS
.isInvalid()) {
2276 if (Tok
.is(tok::less
))
2277 checkPotentialAngleBracket(LHS
);
2278 } else if (OrigLHS
&& Name
.isValid()) {
2279 // Preserve the LHS if the RHS is an invalid member.
2280 LHS
= Actions
.CreateRecoveryExpr(OrigLHS
->getBeginLoc(),
2281 Name
.getEndLoc(), {OrigLHS
});
2285 case tok::plusplus
: // postfix-expression: postfix-expression '++'
2286 case tok::minusminus
: // postfix-expression: postfix-expression '--'
2287 if (!LHS
.isInvalid()) {
2288 Expr
*Arg
= LHS
.get();
2289 LHS
= Actions
.ActOnPostfixUnaryOp(getCurScope(), Tok
.getLocation(),
2290 Tok
.getKind(), Arg
);
2291 if (LHS
.isInvalid())
2292 LHS
= Actions
.CreateRecoveryExpr(Arg
->getBeginLoc(),
2293 Tok
.getLocation(), Arg
);
2301 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
2302 /// vec_step and we are at the start of an expression or a parenthesized
2303 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
2304 /// expression (isCastExpr == false) or the type (isCastExpr == true).
2307 /// unary-expression: [C99 6.5.3]
2308 /// 'sizeof' unary-expression
2309 /// 'sizeof' '(' type-name ')'
2310 /// [GNU] '__alignof' unary-expression
2311 /// [GNU] '__alignof' '(' type-name ')'
2312 /// [C11] '_Alignof' '(' type-name ')'
2313 /// [C++0x] 'alignof' '(' type-id ')'
2315 /// [GNU] typeof-specifier:
2316 /// typeof ( expressions )
2317 /// typeof ( type-name )
2318 /// [GNU/C++] typeof unary-expression
2319 /// [C23] typeof-specifier:
2320 /// typeof '(' typeof-specifier-argument ')'
2321 /// typeof_unqual '(' typeof-specifier-argument ')'
2323 /// typeof-specifier-argument:
2327 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
2328 /// vec_step ( expressions )
2329 /// vec_step ( type-name )
2332 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token
&OpTok
,
2335 SourceRange
&CastRange
) {
2337 assert(OpTok
.isOneOf(tok::kw_typeof
, tok::kw_typeof_unqual
, tok::kw_sizeof
,
2338 tok::kw___alignof
, tok::kw_alignof
, tok::kw__Alignof
,
2340 tok::kw___builtin_omp_required_simd_align
,
2341 tok::kw___builtin_vectorelements
) &&
2342 "Not a typeof/sizeof/alignof/vec_step expression!");
2346 // If the operand doesn't start with an '(', it must be an expression.
2347 if (Tok
.isNot(tok::l_paren
)) {
2348 // If construct allows a form without parenthesis, user may forget to put
2349 // pathenthesis around type name.
2350 if (OpTok
.isOneOf(tok::kw_sizeof
, tok::kw___alignof
, tok::kw_alignof
,
2351 tok::kw__Alignof
)) {
2352 if (isTypeIdUnambiguously()) {
2353 DeclSpec
DS(AttrFactory
);
2354 ParseSpecifierQualifierList(DS
);
2355 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
2356 DeclaratorContext::TypeName
);
2357 ParseDeclarator(DeclaratorInfo
);
2359 SourceLocation LParenLoc
= PP
.getLocForEndOfToken(OpTok
.getLocation());
2360 SourceLocation RParenLoc
= PP
.getLocForEndOfToken(PrevTokLocation
);
2361 if (LParenLoc
.isInvalid() || RParenLoc
.isInvalid()) {
2362 Diag(OpTok
.getLocation(),
2363 diag::err_expected_parentheses_around_typename
)
2366 Diag(LParenLoc
, diag::err_expected_parentheses_around_typename
)
2367 << OpTok
.getName() << FixItHint::CreateInsertion(LParenLoc
, "(")
2368 << FixItHint::CreateInsertion(RParenLoc
, ")");
2376 if (OpTok
.isOneOf(tok::kw_typeof
, tok::kw_typeof_unqual
) &&
2377 !getLangOpts().CPlusPlus
) {
2378 Diag(Tok
, diag::err_expected_after
) << OpTok
.getIdentifierInfo()
2383 Operand
= ParseCastExpression(UnaryExprOnly
);
2385 // If it starts with a '(', we know that it is either a parenthesized
2386 // type-name, or it is a unary-expression that starts with a compound
2387 // literal, or starts with a primary-expression that is a parenthesized
2389 ParenParseOption ExprType
= CastExpr
;
2390 SourceLocation LParenLoc
= Tok
.getLocation(), RParenLoc
;
2392 Operand
= ParseParenExpression(ExprType
, true/*stopIfCastExpr*/,
2393 false, CastTy
, RParenLoc
);
2394 CastRange
= SourceRange(LParenLoc
, RParenLoc
);
2396 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
2398 if (ExprType
== CastExpr
) {
2403 if (getLangOpts().CPlusPlus
||
2404 !OpTok
.isOneOf(tok::kw_typeof
, tok::kw_typeof_unqual
)) {
2405 // GNU typeof in C requires the expression to be parenthesized. Not so for
2406 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
2407 // the start of a unary-expression, but doesn't include any postfix
2408 // pieces. Parse these now if present.
2409 if (!Operand
.isInvalid())
2410 Operand
= ParsePostfixExpressionSuffix(Operand
.get());
2414 // If we get here, the operand to the typeof/sizeof/alignof was an expression.
2419 /// Parse a __builtin_sycl_unique_stable_name expression. Accepts a type-id as
2421 ExprResult
Parser::ParseSYCLUniqueStableNameExpression() {
2422 assert(Tok
.is(tok::kw___builtin_sycl_unique_stable_name
) &&
2423 "Not __builtin_sycl_unique_stable_name");
2425 SourceLocation OpLoc
= ConsumeToken();
2426 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2428 // __builtin_sycl_unique_stable_name expressions are always parenthesized.
2429 if (T
.expectAndConsume(diag::err_expected_lparen_after
,
2430 "__builtin_sycl_unique_stable_name"))
2433 TypeResult Ty
= ParseTypeName();
2435 if (Ty
.isInvalid()) {
2440 if (T
.consumeClose())
2443 return Actions
.ActOnSYCLUniqueStableNameExpr(OpLoc
, T
.getOpenLocation(),
2444 T
.getCloseLocation(), Ty
.get());
2447 /// Parse a sizeof or alignof expression.
2450 /// unary-expression: [C99 6.5.3]
2451 /// 'sizeof' unary-expression
2452 /// 'sizeof' '(' type-name ')'
2453 /// [C++11] 'sizeof' '...' '(' identifier ')'
2454 /// [GNU] '__alignof' unary-expression
2455 /// [GNU] '__alignof' '(' type-name ')'
2456 /// [C11] '_Alignof' '(' type-name ')'
2457 /// [C++11] 'alignof' '(' type-id ')'
2459 ExprResult
Parser::ParseUnaryExprOrTypeTraitExpression() {
2460 assert(Tok
.isOneOf(tok::kw_sizeof
, tok::kw___alignof
, tok::kw_alignof
,
2461 tok::kw__Alignof
, tok::kw_vec_step
,
2462 tok::kw___builtin_omp_required_simd_align
,
2463 tok::kw___builtin_vectorelements
) &&
2464 "Not a sizeof/alignof/vec_step expression!");
2468 // [C++11] 'sizeof' '...' '(' identifier ')'
2469 if (Tok
.is(tok::ellipsis
) && OpTok
.is(tok::kw_sizeof
)) {
2470 SourceLocation EllipsisLoc
= ConsumeToken();
2471 SourceLocation LParenLoc
, RParenLoc
;
2472 IdentifierInfo
*Name
= nullptr;
2473 SourceLocation NameLoc
;
2474 if (Tok
.is(tok::l_paren
)) {
2475 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2477 LParenLoc
= T
.getOpenLocation();
2478 if (Tok
.is(tok::identifier
)) {
2479 Name
= Tok
.getIdentifierInfo();
2480 NameLoc
= ConsumeToken();
2482 RParenLoc
= T
.getCloseLocation();
2483 if (RParenLoc
.isInvalid())
2484 RParenLoc
= PP
.getLocForEndOfToken(NameLoc
);
2486 Diag(Tok
, diag::err_expected_parameter_pack
);
2487 SkipUntil(tok::r_paren
, StopAtSemi
);
2489 } else if (Tok
.is(tok::identifier
)) {
2490 Name
= Tok
.getIdentifierInfo();
2491 NameLoc
= ConsumeToken();
2492 LParenLoc
= PP
.getLocForEndOfToken(EllipsisLoc
);
2493 RParenLoc
= PP
.getLocForEndOfToken(NameLoc
);
2494 Diag(LParenLoc
, diag::err_paren_sizeof_parameter_pack
)
2496 << FixItHint::CreateInsertion(LParenLoc
, "(")
2497 << FixItHint::CreateInsertion(RParenLoc
, ")");
2499 Diag(Tok
, diag::err_sizeof_parameter_pack
);
2505 EnterExpressionEvaluationContext
Unevaluated(
2506 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
,
2507 Sema::ReuseLambdaContextDecl
);
2509 return Actions
.ActOnSizeofParameterPackExpr(getCurScope(),
2510 OpTok
.getLocation(),
2515 if (getLangOpts().CPlusPlus
&&
2516 OpTok
.isOneOf(tok::kw_alignof
, tok::kw__Alignof
))
2517 Diag(OpTok
, diag::warn_cxx98_compat_alignof
);
2518 else if (getLangOpts().C23
&& OpTok
.is(tok::kw_alignof
))
2519 Diag(OpTok
, diag::warn_c23_compat_keyword
) << OpTok
.getName();
2521 EnterExpressionEvaluationContext
Unevaluated(
2522 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
,
2523 Sema::ReuseLambdaContextDecl
);
2527 SourceRange CastRange
;
2528 ExprResult Operand
= ParseExprAfterUnaryExprOrTypeTrait(OpTok
,
2533 UnaryExprOrTypeTrait ExprKind
= UETT_SizeOf
;
2534 if (OpTok
.isOneOf(tok::kw_alignof
, tok::kw__Alignof
))
2535 ExprKind
= UETT_AlignOf
;
2536 else if (OpTok
.is(tok::kw___alignof
))
2537 ExprKind
= UETT_PreferredAlignOf
;
2538 else if (OpTok
.is(tok::kw_vec_step
))
2539 ExprKind
= UETT_VecStep
;
2540 else if (OpTok
.is(tok::kw___builtin_omp_required_simd_align
))
2541 ExprKind
= UETT_OpenMPRequiredSimdAlign
;
2542 else if (OpTok
.is(tok::kw___builtin_vectorelements
))
2543 ExprKind
= UETT_VectorElements
;
2546 return Actions
.ActOnUnaryExprOrTypeTraitExpr(OpTok
.getLocation(),
2549 CastTy
.getAsOpaquePtr(),
2552 if (OpTok
.isOneOf(tok::kw_alignof
, tok::kw__Alignof
))
2553 Diag(OpTok
, diag::ext_alignof_expr
) << OpTok
.getIdentifierInfo();
2555 // If we get here, the operand to the sizeof/alignof was an expression.
2556 if (!Operand
.isInvalid())
2557 Operand
= Actions
.ActOnUnaryExprOrTypeTraitExpr(OpTok
.getLocation(),
2565 /// ParseBuiltinPrimaryExpression
2568 /// primary-expression: [C99 6.5.1]
2569 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2570 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2571 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2573 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2574 /// [GNU] '__builtin_FILE' '(' ')'
2575 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
2576 /// [GNU] '__builtin_FUNCTION' '(' ')'
2577 /// [MS] '__builtin_FUNCSIG' '(' ')'
2578 /// [GNU] '__builtin_LINE' '(' ')'
2579 /// [CLANG] '__builtin_COLUMN' '(' ')'
2580 /// [GNU] '__builtin_source_location' '(' ')'
2581 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
2583 /// [GNU] offsetof-member-designator:
2584 /// [GNU] identifier
2585 /// [GNU] offsetof-member-designator '.' identifier
2586 /// [GNU] offsetof-member-designator '[' expression ']'
2588 ExprResult
Parser::ParseBuiltinPrimaryExpression() {
2590 const IdentifierInfo
*BuiltinII
= Tok
.getIdentifierInfo();
2592 tok::TokenKind T
= Tok
.getKind();
2593 SourceLocation StartLoc
= ConsumeToken(); // Eat the builtin identifier.
2595 // All of these start with an open paren.
2596 if (Tok
.isNot(tok::l_paren
))
2597 return ExprError(Diag(Tok
, diag::err_expected_after
) << BuiltinII
2600 BalancedDelimiterTracker
PT(*this, tok::l_paren
);
2606 default: llvm_unreachable("Not a builtin primary expression!");
2607 case tok::kw___builtin_va_arg
: {
2608 ExprResult
Expr(ParseAssignmentExpression());
2610 if (ExpectAndConsume(tok::comma
)) {
2611 SkipUntil(tok::r_paren
, StopAtSemi
);
2615 TypeResult Ty
= ParseTypeName();
2617 if (Tok
.isNot(tok::r_paren
)) {
2618 Diag(Tok
, diag::err_expected
) << tok::r_paren
;
2622 if (Expr
.isInvalid() || Ty
.isInvalid())
2625 Res
= Actions
.ActOnVAArg(StartLoc
, Expr
.get(), Ty
.get(), ConsumeParen());
2628 case tok::kw___builtin_offsetof
: {
2629 SourceLocation TypeLoc
= Tok
.getLocation();
2630 auto OOK
= Sema::OffsetOfKind::OOK_Builtin
;
2631 if (Tok
.getLocation().isMacroID()) {
2632 StringRef MacroName
= Lexer::getImmediateMacroNameForDiagnostics(
2633 Tok
.getLocation(), PP
.getSourceManager(), getLangOpts());
2634 if (MacroName
== "offsetof")
2635 OOK
= Sema::OffsetOfKind::OOK_Macro
;
2639 OffsetOfStateRAIIObject
InOffsetof(*this, OOK
);
2640 Ty
= ParseTypeName();
2641 if (Ty
.isInvalid()) {
2642 SkipUntil(tok::r_paren
, StopAtSemi
);
2647 if (ExpectAndConsume(tok::comma
)) {
2648 SkipUntil(tok::r_paren
, StopAtSemi
);
2652 // We must have at least one identifier here.
2653 if (Tok
.isNot(tok::identifier
)) {
2654 Diag(Tok
, diag::err_expected
) << tok::identifier
;
2655 SkipUntil(tok::r_paren
, StopAtSemi
);
2659 // Keep track of the various subcomponents we see.
2660 SmallVector
<Sema::OffsetOfComponent
, 4> Comps
;
2662 Comps
.push_back(Sema::OffsetOfComponent());
2663 Comps
.back().isBrackets
= false;
2664 Comps
.back().U
.IdentInfo
= Tok
.getIdentifierInfo();
2665 Comps
.back().LocStart
= Comps
.back().LocEnd
= ConsumeToken();
2667 // FIXME: This loop leaks the index expressions on error.
2669 if (Tok
.is(tok::period
)) {
2670 // offsetof-member-designator: offsetof-member-designator '.' identifier
2671 Comps
.push_back(Sema::OffsetOfComponent());
2672 Comps
.back().isBrackets
= false;
2673 Comps
.back().LocStart
= ConsumeToken();
2675 if (Tok
.isNot(tok::identifier
)) {
2676 Diag(Tok
, diag::err_expected
) << tok::identifier
;
2677 SkipUntil(tok::r_paren
, StopAtSemi
);
2680 Comps
.back().U
.IdentInfo
= Tok
.getIdentifierInfo();
2681 Comps
.back().LocEnd
= ConsumeToken();
2682 } else if (Tok
.is(tok::l_square
)) {
2683 if (CheckProhibitedCXX11Attribute())
2686 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2687 Comps
.push_back(Sema::OffsetOfComponent());
2688 Comps
.back().isBrackets
= true;
2689 BalancedDelimiterTracker
ST(*this, tok::l_square
);
2691 Comps
.back().LocStart
= ST
.getOpenLocation();
2692 Res
= ParseExpression();
2693 if (Res
.isInvalid()) {
2694 SkipUntil(tok::r_paren
, StopAtSemi
);
2697 Comps
.back().U
.E
= Res
.get();
2700 Comps
.back().LocEnd
= ST
.getCloseLocation();
2702 if (Tok
.isNot(tok::r_paren
)) {
2705 } else if (Ty
.isInvalid()) {
2709 Res
= Actions
.ActOnBuiltinOffsetOf(getCurScope(), StartLoc
, TypeLoc
,
2711 PT
.getCloseLocation());
2718 case tok::kw___builtin_choose_expr
: {
2719 ExprResult
Cond(ParseAssignmentExpression());
2720 if (Cond
.isInvalid()) {
2721 SkipUntil(tok::r_paren
, StopAtSemi
);
2724 if (ExpectAndConsume(tok::comma
)) {
2725 SkipUntil(tok::r_paren
, StopAtSemi
);
2729 ExprResult
Expr1(ParseAssignmentExpression());
2730 if (Expr1
.isInvalid()) {
2731 SkipUntil(tok::r_paren
, StopAtSemi
);
2734 if (ExpectAndConsume(tok::comma
)) {
2735 SkipUntil(tok::r_paren
, StopAtSemi
);
2739 ExprResult
Expr2(ParseAssignmentExpression());
2740 if (Expr2
.isInvalid()) {
2741 SkipUntil(tok::r_paren
, StopAtSemi
);
2744 if (Tok
.isNot(tok::r_paren
)) {
2745 Diag(Tok
, diag::err_expected
) << tok::r_paren
;
2748 Res
= Actions
.ActOnChooseExpr(StartLoc
, Cond
.get(), Expr1
.get(),
2749 Expr2
.get(), ConsumeParen());
2752 case tok::kw___builtin_astype
: {
2753 // The first argument is an expression to be converted, followed by a comma.
2754 ExprResult
Expr(ParseAssignmentExpression());
2755 if (Expr
.isInvalid()) {
2756 SkipUntil(tok::r_paren
, StopAtSemi
);
2760 if (ExpectAndConsume(tok::comma
)) {
2761 SkipUntil(tok::r_paren
, StopAtSemi
);
2765 // Second argument is the type to bitcast to.
2766 TypeResult DestTy
= ParseTypeName();
2767 if (DestTy
.isInvalid())
2770 // Attempt to consume the r-paren.
2771 if (Tok
.isNot(tok::r_paren
)) {
2772 Diag(Tok
, diag::err_expected
) << tok::r_paren
;
2773 SkipUntil(tok::r_paren
, StopAtSemi
);
2777 Res
= Actions
.ActOnAsTypeExpr(Expr
.get(), DestTy
.get(), StartLoc
,
2781 case tok::kw___builtin_convertvector
: {
2782 // The first argument is an expression to be converted, followed by a comma.
2783 ExprResult
Expr(ParseAssignmentExpression());
2784 if (Expr
.isInvalid()) {
2785 SkipUntil(tok::r_paren
, StopAtSemi
);
2789 if (ExpectAndConsume(tok::comma
)) {
2790 SkipUntil(tok::r_paren
, StopAtSemi
);
2794 // Second argument is the type to bitcast to.
2795 TypeResult DestTy
= ParseTypeName();
2796 if (DestTy
.isInvalid())
2799 // Attempt to consume the r-paren.
2800 if (Tok
.isNot(tok::r_paren
)) {
2801 Diag(Tok
, diag::err_expected
) << tok::r_paren
;
2802 SkipUntil(tok::r_paren
, StopAtSemi
);
2806 Res
= Actions
.ActOnConvertVectorExpr(Expr
.get(), DestTy
.get(), StartLoc
,
2810 case tok::kw___builtin_COLUMN
:
2811 case tok::kw___builtin_FILE
:
2812 case tok::kw___builtin_FILE_NAME
:
2813 case tok::kw___builtin_FUNCTION
:
2814 case tok::kw___builtin_FUNCSIG
:
2815 case tok::kw___builtin_LINE
:
2816 case tok::kw___builtin_source_location
: {
2817 // Attempt to consume the r-paren.
2818 if (Tok
.isNot(tok::r_paren
)) {
2819 Diag(Tok
, diag::err_expected
) << tok::r_paren
;
2820 SkipUntil(tok::r_paren
, StopAtSemi
);
2823 SourceLocExpr::IdentKind Kind
= [&] {
2825 case tok::kw___builtin_FILE
:
2826 return SourceLocExpr::File
;
2827 case tok::kw___builtin_FILE_NAME
:
2828 return SourceLocExpr::FileName
;
2829 case tok::kw___builtin_FUNCTION
:
2830 return SourceLocExpr::Function
;
2831 case tok::kw___builtin_FUNCSIG
:
2832 return SourceLocExpr::FuncSig
;
2833 case tok::kw___builtin_LINE
:
2834 return SourceLocExpr::Line
;
2835 case tok::kw___builtin_COLUMN
:
2836 return SourceLocExpr::Column
;
2837 case tok::kw___builtin_source_location
:
2838 return SourceLocExpr::SourceLocStruct
;
2840 llvm_unreachable("invalid keyword");
2843 Res
= Actions
.ActOnSourceLocExpr(Kind
, StartLoc
, ConsumeParen());
2848 if (Res
.isInvalid())
2851 // These can be followed by postfix-expr pieces because they are
2852 // primary-expressions.
2853 return ParsePostfixExpressionSuffix(Res
.get());
2856 bool Parser::tryParseOpenMPArrayShapingCastPart() {
2857 assert(Tok
.is(tok::l_square
) && "Expected open bracket");
2858 bool ErrorFound
= true;
2859 TentativeParsingAction
TPA(*this);
2861 if (Tok
.isNot(tok::l_square
))
2865 // Skip inner expression.
2866 while (!SkipUntil(tok::r_square
, tok::annot_pragma_openmp_end
,
2867 StopAtSemi
| StopBeforeMatch
))
2869 if (Tok
.isNot(tok::r_square
))
2873 // Found ')' - done.
2874 if (Tok
.is(tok::r_paren
)) {
2878 } while (Tok
.isNot(tok::annot_pragma_openmp_end
));
2883 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2884 /// based on what is allowed by ExprType. The actual thing parsed is returned
2885 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2886 /// not the parsed cast-expression.
2889 /// primary-expression: [C99 6.5.1]
2890 /// '(' expression ')'
2891 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2892 /// postfix-expression: [C99 6.5.2]
2893 /// '(' type-name ')' '{' initializer-list '}'
2894 /// '(' type-name ')' '{' initializer-list ',' '}'
2895 /// cast-expression: [C99 6.5.4]
2896 /// '(' type-name ')' cast-expression
2897 /// [ARC] bridged-cast-expression
2898 /// [ARC] bridged-cast-expression:
2899 /// (__bridge type-name) cast-expression
2900 /// (__bridge_transfer type-name) cast-expression
2901 /// (__bridge_retained type-name) cast-expression
2902 /// fold-expression: [C++1z]
2903 /// '(' cast-expression fold-operator '...' ')'
2904 /// '(' '...' fold-operator cast-expression ')'
2905 /// '(' cast-expression fold-operator '...'
2906 /// fold-operator cast-expression ')'
2907 /// [OPENMP] Array shaping operation
2908 /// '(' '[' expression ']' { '[' expression ']' } cast-expression
2911 Parser::ParseParenExpression(ParenParseOption
&ExprType
, bool stopIfCastExpr
,
2912 bool isTypeCast
, ParsedType
&CastTy
,
2913 SourceLocation
&RParenLoc
) {
2914 assert(Tok
.is(tok::l_paren
) && "Not a paren expr!");
2915 ColonProtectionRAIIObject
ColonProtection(*this, false);
2916 BalancedDelimiterTracker
T(*this, tok::l_paren
);
2917 if (T
.consumeOpen())
2919 SourceLocation OpenLoc
= T
.getOpenLocation();
2921 PreferredType
.enterParenExpr(Tok
.getLocation(), OpenLoc
);
2923 ExprResult
Result(true);
2924 bool isAmbiguousTypeId
;
2927 if (Tok
.is(tok::code_completion
)) {
2929 Actions
.CodeCompleteExpression(
2930 getCurScope(), PreferredType
.get(Tok
.getLocation()),
2931 /*IsParenthesized=*/ExprType
>= CompoundLiteral
);
2935 // Diagnose use of bridge casts in non-arc mode.
2936 bool BridgeCast
= (getLangOpts().ObjC
&&
2937 Tok
.isOneOf(tok::kw___bridge
,
2938 tok::kw___bridge_transfer
,
2939 tok::kw___bridge_retained
,
2940 tok::kw___bridge_retain
));
2941 if (BridgeCast
&& !getLangOpts().ObjCAutoRefCount
) {
2942 if (!TryConsumeToken(tok::kw___bridge
)) {
2943 StringRef BridgeCastName
= Tok
.getName();
2944 SourceLocation BridgeKeywordLoc
= ConsumeToken();
2945 if (!PP
.getSourceManager().isInSystemHeader(BridgeKeywordLoc
))
2946 Diag(BridgeKeywordLoc
, diag::warn_arc_bridge_cast_nonarc
)
2948 << FixItHint::CreateReplacement(BridgeKeywordLoc
, "");
2953 // None of these cases should fall through with an invalid Result
2954 // unless they've already reported an error.
2955 if (ExprType
>= CompoundStmt
&& Tok
.is(tok::l_brace
)) {
2956 Diag(Tok
, OpenLoc
.isMacroID() ? diag::ext_gnu_statement_expr_macro
2957 : diag::ext_gnu_statement_expr
);
2959 checkCompoundToken(OpenLoc
, tok::l_paren
, CompoundToken::StmtExprBegin
);
2961 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2962 Result
= ExprError(Diag(OpenLoc
, diag::err_stmtexpr_file_scope
));
2964 // Find the nearest non-record decl context. Variables declared in a
2965 // statement expression behave as if they were declared in the enclosing
2966 // function, block, or other code construct.
2967 DeclContext
*CodeDC
= Actions
.CurContext
;
2968 while (CodeDC
->isRecord() || isa
<EnumDecl
>(CodeDC
)) {
2969 CodeDC
= CodeDC
->getParent();
2970 assert(CodeDC
&& !CodeDC
->isFileContext() &&
2971 "statement expr not in code context");
2973 Sema::ContextRAII
SavedContext(Actions
, CodeDC
, /*NewThisContext=*/false);
2975 Actions
.ActOnStartStmtExpr();
2977 StmtResult
Stmt(ParseCompoundStatement(true));
2978 ExprType
= CompoundStmt
;
2980 // If the substmt parsed correctly, build the AST node.
2981 if (!Stmt
.isInvalid()) {
2982 Result
= Actions
.ActOnStmtExpr(getCurScope(), OpenLoc
, Stmt
.get(),
2985 Actions
.ActOnStmtExprError();
2988 } else if (ExprType
>= CompoundLiteral
&& BridgeCast
) {
2989 tok::TokenKind tokenKind
= Tok
.getKind();
2990 SourceLocation BridgeKeywordLoc
= ConsumeToken();
2992 // Parse an Objective-C ARC ownership cast expression.
2993 ObjCBridgeCastKind Kind
;
2994 if (tokenKind
== tok::kw___bridge
)
2996 else if (tokenKind
== tok::kw___bridge_transfer
)
2997 Kind
= OBC_BridgeTransfer
;
2998 else if (tokenKind
== tok::kw___bridge_retained
)
2999 Kind
= OBC_BridgeRetained
;
3001 // As a hopefully temporary workaround, allow __bridge_retain as
3002 // a synonym for __bridge_retained, but only in system headers.
3003 assert(tokenKind
== tok::kw___bridge_retain
);
3004 Kind
= OBC_BridgeRetained
;
3005 if (!PP
.getSourceManager().isInSystemHeader(BridgeKeywordLoc
))
3006 Diag(BridgeKeywordLoc
, diag::err_arc_bridge_retain
)
3007 << FixItHint::CreateReplacement(BridgeKeywordLoc
,
3008 "__bridge_retained");
3011 TypeResult Ty
= ParseTypeName();
3013 ColonProtection
.restore();
3014 RParenLoc
= T
.getCloseLocation();
3016 PreferredType
.enterTypeCast(Tok
.getLocation(), Ty
.get().get());
3017 ExprResult SubExpr
= ParseCastExpression(AnyCastExpr
);
3019 if (Ty
.isInvalid() || SubExpr
.isInvalid())
3022 return Actions
.ActOnObjCBridgedCast(getCurScope(), OpenLoc
, Kind
,
3023 BridgeKeywordLoc
, Ty
.get(),
3024 RParenLoc
, SubExpr
.get());
3025 } else if (ExprType
>= CompoundLiteral
&&
3026 isTypeIdInParens(isAmbiguousTypeId
)) {
3028 // Otherwise, this is a compound literal expression or cast expression.
3030 // In C++, if the type-id is ambiguous we disambiguate based on context.
3031 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
3032 // in which case we should treat it as type-id.
3033 // if stopIfCastExpr is false, we need to determine the context past the
3034 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
3035 if (isAmbiguousTypeId
&& !stopIfCastExpr
) {
3036 ExprResult res
= ParseCXXAmbiguousParenExpression(ExprType
, CastTy
, T
,
3038 RParenLoc
= T
.getCloseLocation();
3042 // Parse the type declarator.
3043 DeclSpec
DS(AttrFactory
);
3044 ParseSpecifierQualifierList(DS
);
3045 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
3046 DeclaratorContext::TypeName
);
3047 ParseDeclarator(DeclaratorInfo
);
3049 // If our type is followed by an identifier and either ':' or ']', then
3050 // this is probably an Objective-C message send where the leading '[' is
3051 // missing. Recover as if that were the case.
3052 if (!DeclaratorInfo
.isInvalidType() && Tok
.is(tok::identifier
) &&
3053 !InMessageExpression
&& getLangOpts().ObjC
&&
3054 (NextToken().is(tok::colon
) || NextToken().is(tok::r_square
))) {
3057 InMessageExpressionRAIIObject
InMessage(*this, false);
3058 Ty
= Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
3060 Result
= ParseObjCMessageExpressionBody(SourceLocation(),
3066 ColonProtection
.restore();
3067 RParenLoc
= T
.getCloseLocation();
3068 if (Tok
.is(tok::l_brace
)) {
3069 ExprType
= CompoundLiteral
;
3072 InMessageExpressionRAIIObject
InMessage(*this, false);
3073 Ty
= Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
3075 return ParseCompoundLiteralExpression(Ty
.get(), OpenLoc
, RParenLoc
);
3078 if (Tok
.is(tok::l_paren
)) {
3079 // This could be OpenCL vector Literals
3080 if (getLangOpts().OpenCL
)
3084 InMessageExpressionRAIIObject
InMessage(*this, false);
3085 Ty
= Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
3091 QualType QT
= Ty
.get().get().getCanonicalType();
3092 if (QT
->isVectorType())
3094 // We parsed '(' vector-type-name ')' followed by '('
3096 // Parse the cast-expression that follows it next.
3097 // isVectorLiteral = true will make sure we don't parse any
3098 // Postfix expression yet
3099 Result
= ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr
,
3100 /*isAddressOfOperand=*/false,
3101 /*isTypeCast=*/IsTypeCast
,
3102 /*isVectorLiteral=*/true);
3104 if (!Result
.isInvalid()) {
3105 Result
= Actions
.ActOnCastExpr(getCurScope(), OpenLoc
,
3106 DeclaratorInfo
, CastTy
,
3107 RParenLoc
, Result
.get());
3110 // After we performed the cast we can check for postfix-expr pieces.
3111 if (!Result
.isInvalid()) {
3112 Result
= ParsePostfixExpressionSuffix(Result
);
3120 if (ExprType
== CastExpr
) {
3121 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
3123 if (DeclaratorInfo
.isInvalidType())
3126 // Note that this doesn't parse the subsequent cast-expression, it just
3127 // returns the parsed type to the callee.
3128 if (stopIfCastExpr
) {
3131 InMessageExpressionRAIIObject
InMessage(*this, false);
3132 Ty
= Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
3135 return ExprResult();
3138 // Reject the cast of super idiom in ObjC.
3139 if (Tok
.is(tok::identifier
) && getLangOpts().ObjC
&&
3140 Tok
.getIdentifierInfo() == Ident_super
&&
3141 getCurScope()->isInObjcMethodScope() &&
3142 GetLookAheadToken(1).isNot(tok::period
)) {
3143 Diag(Tok
.getLocation(), diag::err_illegal_super_cast
)
3144 << SourceRange(OpenLoc
, RParenLoc
);
3148 PreferredType
.enterTypeCast(Tok
.getLocation(), CastTy
.get());
3149 // Parse the cast-expression that follows it next.
3150 // TODO: For cast expression with CastTy.
3151 Result
= ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr
,
3152 /*isAddressOfOperand=*/false,
3153 /*isTypeCast=*/IsTypeCast
);
3154 if (!Result
.isInvalid()) {
3155 Result
= Actions
.ActOnCastExpr(getCurScope(), OpenLoc
,
3156 DeclaratorInfo
, CastTy
,
3157 RParenLoc
, Result
.get());
3162 Diag(Tok
, diag::err_expected_lbrace_in_compound_literal
);
3165 } else if (ExprType
>= FoldExpr
&& Tok
.is(tok::ellipsis
) &&
3166 isFoldOperator(NextToken().getKind())) {
3167 ExprType
= FoldExpr
;
3168 return ParseFoldExpression(ExprResult(), T
);
3169 } else if (isTypeCast
) {
3170 // Parse the expression-list.
3171 InMessageExpressionRAIIObject
InMessage(*this, false);
3172 ExprVector ArgExprs
;
3174 if (!ParseSimpleExpressionList(ArgExprs
)) {
3175 // FIXME: If we ever support comma expressions as operands to
3176 // fold-expressions, we'll need to allow multiple ArgExprs here.
3177 if (ExprType
>= FoldExpr
&& ArgExprs
.size() == 1 &&
3178 isFoldOperator(Tok
.getKind()) && NextToken().is(tok::ellipsis
)) {
3179 ExprType
= FoldExpr
;
3180 return ParseFoldExpression(ArgExprs
[0], T
);
3183 ExprType
= SimpleExpr
;
3184 Result
= Actions
.ActOnParenListExpr(OpenLoc
, Tok
.getLocation(),
3187 } else if (getLangOpts().OpenMP
>= 50 && OpenMPDirectiveParsing
&&
3188 ExprType
== CastExpr
&& Tok
.is(tok::l_square
) &&
3189 tryParseOpenMPArrayShapingCastPart()) {
3190 bool ErrorFound
= false;
3191 SmallVector
<Expr
*, 4> OMPDimensions
;
3192 SmallVector
<SourceRange
, 4> OMPBracketsRanges
;
3194 BalancedDelimiterTracker
TS(*this, tok::l_square
);
3196 ExprResult NumElements
=
3197 Actions
.CorrectDelayedTyposInExpr(ParseExpression());
3198 if (!NumElements
.isUsable()) {
3200 while (!SkipUntil(tok::r_square
, tok::r_paren
,
3201 StopAtSemi
| StopBeforeMatch
))
3205 OMPDimensions
.push_back(NumElements
.get());
3206 OMPBracketsRanges
.push_back(TS
.getRange());
3207 } while (Tok
.isNot(tok::r_paren
));
3210 RParenLoc
= T
.getCloseLocation();
3211 Result
= Actions
.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3213 Result
= ExprError();
3214 } else if (!Result
.isInvalid()) {
3215 Result
= Actions
.ActOnOMPArrayShapingExpr(
3216 Result
.get(), OpenLoc
, RParenLoc
, OMPDimensions
, OMPBracketsRanges
);
3220 InMessageExpressionRAIIObject
InMessage(*this, false);
3222 Result
= ParseExpression(MaybeTypeCast
);
3223 if (!getLangOpts().CPlusPlus
&& Result
.isUsable()) {
3224 // Correct typos in non-C++ code earlier so that implicit-cast-like
3225 // expressions are parsed correctly.
3226 Result
= Actions
.CorrectDelayedTyposInExpr(Result
);
3229 if (ExprType
>= FoldExpr
&& isFoldOperator(Tok
.getKind()) &&
3230 NextToken().is(tok::ellipsis
)) {
3231 ExprType
= FoldExpr
;
3232 return ParseFoldExpression(Result
, T
);
3234 ExprType
= SimpleExpr
;
3236 // Don't build a paren expression unless we actually match a ')'.
3237 if (!Result
.isInvalid() && Tok
.is(tok::r_paren
))
3239 Actions
.ActOnParenExpr(OpenLoc
, Tok
.getLocation(), Result
.get());
3243 if (Result
.isInvalid()) {
3244 SkipUntil(tok::r_paren
, StopAtSemi
);
3249 RParenLoc
= T
.getCloseLocation();
3253 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
3254 /// and we are at the left brace.
3257 /// postfix-expression: [C99 6.5.2]
3258 /// '(' type-name ')' '{' initializer-list '}'
3259 /// '(' type-name ')' '{' initializer-list ',' '}'
3262 Parser::ParseCompoundLiteralExpression(ParsedType Ty
,
3263 SourceLocation LParenLoc
,
3264 SourceLocation RParenLoc
) {
3265 assert(Tok
.is(tok::l_brace
) && "Not a compound literal!");
3266 if (!getLangOpts().C99
) // Compound literals don't exist in C90.
3267 Diag(LParenLoc
, diag::ext_c99_compound_literal
);
3268 PreferredType
.enterTypeCast(Tok
.getLocation(), Ty
.get());
3269 ExprResult Result
= ParseInitializer();
3270 if (!Result
.isInvalid() && Ty
)
3271 return Actions
.ActOnCompoundLiteral(LParenLoc
, Ty
, RParenLoc
, Result
.get());
3275 /// ParseStringLiteralExpression - This handles the various token types that
3276 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
3277 /// translation phase #6].
3280 /// primary-expression: [C99 6.5.1]
3283 ExprResult
Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral
) {
3284 return ParseStringLiteralExpression(AllowUserDefinedLiteral
,
3285 /*Unevaluated=*/false);
3288 ExprResult
Parser::ParseUnevaluatedStringLiteralExpression() {
3289 return ParseStringLiteralExpression(/*AllowUserDefinedLiteral=*/false,
3290 /*Unevaluated=*/true);
3293 ExprResult
Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral
,
3295 assert(tokenIsLikeStringLiteral(Tok
, getLangOpts()) &&
3296 "Not a string-literal-like token!");
3298 // String concatenation.
3299 // Note: some keywords like __FUNCTION__ are not considered to be strings
3300 // for concatenation purposes, unless Microsoft extensions are enabled.
3301 SmallVector
<Token
, 4> StringToks
;
3304 StringToks
.push_back(Tok
);
3306 } while (tokenIsLikeStringLiteral(Tok
, getLangOpts()));
3309 assert(!AllowUserDefinedLiteral
&& "UDL are always evaluated");
3310 return Actions
.ActOnUnevaluatedStringLiteral(StringToks
);
3313 // Pass the set of string tokens, ready for concatenation, to the actions.
3314 return Actions
.ActOnStringLiteral(StringToks
,
3315 AllowUserDefinedLiteral
? getCurScope()
3319 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
3323 /// generic-selection:
3324 /// _Generic ( assignment-expression , generic-assoc-list )
3325 /// generic-assoc-list:
3326 /// generic-association
3327 /// generic-assoc-list , generic-association
3328 /// generic-association:
3329 /// type-name : assignment-expression
3330 /// default : assignment-expression
3333 /// As an extension, Clang also accepts:
3335 /// generic-selection:
3336 /// _Generic ( type-name, generic-assoc-list )
3338 ExprResult
Parser::ParseGenericSelectionExpression() {
3339 assert(Tok
.is(tok::kw__Generic
) && "_Generic keyword expected");
3340 if (!getLangOpts().C11
)
3341 Diag(Tok
, diag::ext_c11_feature
) << Tok
.getName();
3343 SourceLocation KeyLoc
= ConsumeToken();
3344 BalancedDelimiterTracker
T(*this, tok::l_paren
);
3345 if (T
.expectAndConsume())
3348 // We either have a controlling expression or we have a controlling type, and
3349 // we need to figure out which it is.
3350 TypeResult ControllingType
;
3351 ExprResult ControllingExpr
;
3352 if (isTypeIdForGenericSelection()) {
3353 ControllingType
= ParseTypeName();
3354 if (ControllingType
.isInvalid()) {
3355 SkipUntil(tok::r_paren
, StopAtSemi
);
3358 const auto *LIT
= cast
<LocInfoType
>(ControllingType
.get().get());
3359 SourceLocation Loc
= LIT
->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
3360 Diag(Loc
, diag::ext_generic_with_type_arg
);
3362 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
3364 EnterExpressionEvaluationContext
Unevaluated(
3365 Actions
, Sema::ExpressionEvaluationContext::Unevaluated
);
3367 Actions
.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3368 if (ControllingExpr
.isInvalid()) {
3369 SkipUntil(tok::r_paren
, StopAtSemi
);
3374 if (ExpectAndConsume(tok::comma
)) {
3375 SkipUntil(tok::r_paren
, StopAtSemi
);
3379 SourceLocation DefaultLoc
;
3380 SmallVector
<ParsedType
, 12> Types
;
3384 if (Tok
.is(tok::kw_default
)) {
3385 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
3386 // generic association."
3387 if (!DefaultLoc
.isInvalid()) {
3388 Diag(Tok
, diag::err_duplicate_default_assoc
);
3389 Diag(DefaultLoc
, diag::note_previous_default_assoc
);
3390 SkipUntil(tok::r_paren
, StopAtSemi
);
3393 DefaultLoc
= ConsumeToken();
3396 ColonProtectionRAIIObject
X(*this);
3397 TypeResult TR
= ParseTypeName(nullptr, DeclaratorContext::Association
);
3398 if (TR
.isInvalid()) {
3399 SkipUntil(tok::r_paren
, StopAtSemi
);
3404 Types
.push_back(Ty
);
3406 if (ExpectAndConsume(tok::colon
)) {
3407 SkipUntil(tok::r_paren
, StopAtSemi
);
3411 // FIXME: These expressions should be parsed in a potentially potentially
3412 // evaluated context.
3414 Actions
.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
3415 if (ER
.isInvalid()) {
3416 SkipUntil(tok::r_paren
, StopAtSemi
);
3419 Exprs
.push_back(ER
.get());
3420 } while (TryConsumeToken(tok::comma
));
3423 if (T
.getCloseLocation().isInvalid())
3426 void *ExprOrTy
= ControllingExpr
.isUsable()
3427 ? ControllingExpr
.get()
3428 : ControllingType
.get().getAsOpaquePtr();
3430 return Actions
.ActOnGenericSelectionExpr(
3431 KeyLoc
, DefaultLoc
, T
.getCloseLocation(), ControllingExpr
.isUsable(),
3432 ExprOrTy
, Types
, Exprs
);
3435 /// Parse A C++1z fold-expression after the opening paren and optional
3436 /// left-hand-side expression.
3439 /// fold-expression:
3440 /// ( cast-expression fold-operator ... )
3441 /// ( ... fold-operator cast-expression )
3442 /// ( cast-expression fold-operator ... fold-operator cast-expression )
3443 ExprResult
Parser::ParseFoldExpression(ExprResult LHS
,
3444 BalancedDelimiterTracker
&T
) {
3445 if (LHS
.isInvalid()) {
3450 tok::TokenKind Kind
= tok::unknown
;
3451 SourceLocation FirstOpLoc
;
3452 if (LHS
.isUsable()) {
3453 Kind
= Tok
.getKind();
3454 assert(isFoldOperator(Kind
) && "missing fold-operator");
3455 FirstOpLoc
= ConsumeToken();
3458 assert(Tok
.is(tok::ellipsis
) && "not a fold-expression");
3459 SourceLocation EllipsisLoc
= ConsumeToken();
3462 if (Tok
.isNot(tok::r_paren
)) {
3463 if (!isFoldOperator(Tok
.getKind()))
3464 return Diag(Tok
.getLocation(), diag::err_expected_fold_operator
);
3466 if (Kind
!= tok::unknown
&& Tok
.getKind() != Kind
)
3467 Diag(Tok
.getLocation(), diag::err_fold_operator_mismatch
)
3468 << SourceRange(FirstOpLoc
);
3469 Kind
= Tok
.getKind();
3472 RHS
= ParseExpression();
3473 if (RHS
.isInvalid()) {
3479 Diag(EllipsisLoc
, getLangOpts().CPlusPlus17
3480 ? diag::warn_cxx14_compat_fold_expression
3481 : diag::ext_fold_expression
);
3484 return Actions
.ActOnCXXFoldExpr(getCurScope(), T
.getOpenLocation(), LHS
.get(),
3485 Kind
, EllipsisLoc
, RHS
.get(),
3486 T
.getCloseLocation());
3489 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
3492 /// argument-expression-list:
3493 /// assignment-expression
3494 /// argument-expression-list , assignment-expression
3496 /// [C++] expression-list:
3497 /// [C++] assignment-expression
3498 /// [C++] expression-list , assignment-expression
3500 /// [C++0x] expression-list:
3501 /// [C++0x] initializer-list
3503 /// [C++0x] initializer-list
3504 /// [C++0x] initializer-clause ...[opt]
3505 /// [C++0x] initializer-list , initializer-clause ...[opt]
3507 /// [C++0x] initializer-clause:
3508 /// [C++0x] assignment-expression
3509 /// [C++0x] braced-init-list
3511 bool Parser::ParseExpressionList(SmallVectorImpl
<Expr
*> &Exprs
,
3512 llvm::function_ref
<void()> ExpressionStarts
,
3513 bool FailImmediatelyOnInvalidExpr
,
3514 bool EarlyTypoCorrection
) {
3515 bool SawError
= false;
3517 if (ExpressionStarts
)
3521 if (getLangOpts().CPlusPlus11
&& Tok
.is(tok::l_brace
)) {
3522 Diag(Tok
, diag::warn_cxx98_compat_generalized_initializer_lists
);
3523 Expr
= ParseBraceInitializer();
3525 Expr
= ParseAssignmentExpression();
3527 if (EarlyTypoCorrection
)
3528 Expr
= Actions
.CorrectDelayedTyposInExpr(Expr
);
3530 if (Tok
.is(tok::ellipsis
))
3531 Expr
= Actions
.ActOnPackExpansion(Expr
.get(), ConsumeToken());
3532 else if (Tok
.is(tok::code_completion
)) {
3533 // There's nothing to suggest in here as we parsed a full expression.
3534 // Instead fail and propagate the error since caller might have something
3535 // the suggest, e.g. signature help in function call. Note that this is
3536 // performed before pushing the \p Expr, so that signature help can report
3537 // current argument correctly.
3542 if (Expr
.isInvalid()) {
3544 if (FailImmediatelyOnInvalidExpr
)
3546 SkipUntil(tok::comma
, tok::r_paren
, StopBeforeMatch
);
3548 Exprs
.push_back(Expr
.get());
3551 if (Tok
.isNot(tok::comma
))
3553 // Move to the next argument, remember where the comma was.
3556 checkPotentialAngleBracketDelimiter(Comma
);
3559 // Ensure typos get diagnosed when errors were encountered while parsing the
3561 for (auto &E
: Exprs
) {
3562 ExprResult Expr
= Actions
.CorrectDelayedTyposInExpr(E
);
3563 if (Expr
.isUsable()) E
= Expr
.get();
3569 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
3570 /// used for misc language extensions.
3573 /// simple-expression-list:
3574 /// assignment-expression
3575 /// simple-expression-list , assignment-expression
3577 bool Parser::ParseSimpleExpressionList(SmallVectorImpl
<Expr
*> &Exprs
) {
3579 ExprResult Expr
= ParseAssignmentExpression();
3580 if (Expr
.isInvalid())
3583 Exprs
.push_back(Expr
.get());
3585 // We might be parsing the LHS of a fold-expression. If we reached the fold
3587 if (Tok
.isNot(tok::comma
) || NextToken().is(tok::ellipsis
))
3590 // Move to the next argument, remember where the comma was.
3593 checkPotentialAngleBracketDelimiter(Comma
);
3597 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
3600 /// [clang] block-id:
3601 /// [clang] specifier-qualifier-list block-declarator
3603 void Parser::ParseBlockId(SourceLocation CaretLoc
) {
3604 if (Tok
.is(tok::code_completion
)) {
3606 Actions
.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type
);
3610 // Parse the specifier-qualifier-list piece.
3611 DeclSpec
DS(AttrFactory
);
3612 ParseSpecifierQualifierList(DS
);
3614 // Parse the block-declarator.
3615 Declarator
DeclaratorInfo(DS
, ParsedAttributesView::none(),
3616 DeclaratorContext::BlockLiteral
);
3617 DeclaratorInfo
.setFunctionDefinitionKind(FunctionDefinitionKind::Definition
);
3618 ParseDeclarator(DeclaratorInfo
);
3620 MaybeParseGNUAttributes(DeclaratorInfo
);
3622 // Inform sema that we are starting a block.
3623 Actions
.ActOnBlockArguments(CaretLoc
, DeclaratorInfo
, getCurScope());
3626 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
3627 /// like ^(int x){ return x+1; }
3631 /// [clang] '^' block-args[opt] compound-statement
3632 /// [clang] '^' block-id compound-statement
3633 /// [clang] block-args:
3634 /// [clang] '(' parameter-list ')'
3636 ExprResult
Parser::ParseBlockLiteralExpression() {
3637 assert(Tok
.is(tok::caret
) && "block literal starts with ^");
3638 SourceLocation CaretLoc
= ConsumeToken();
3640 PrettyStackTraceLoc
CrashInfo(PP
.getSourceManager(), CaretLoc
,
3641 "block literal parsing");
3643 // Enter a scope to hold everything within the block. This includes the
3644 // argument decls, decls within the compound expression, etc. This also
3645 // allows determining whether a variable reference inside the block is
3646 // within or outside of the block.
3647 ParseScope
BlockScope(this, Scope::BlockScope
| Scope::FnScope
|
3648 Scope::CompoundStmtScope
| Scope::DeclScope
);
3650 // Inform sema that we are starting a block.
3651 Actions
.ActOnBlockStart(CaretLoc
, getCurScope());
3653 // Parse the return type if present.
3654 DeclSpec
DS(AttrFactory
);
3655 Declarator
ParamInfo(DS
, ParsedAttributesView::none(),
3656 DeclaratorContext::BlockLiteral
);
3657 ParamInfo
.setFunctionDefinitionKind(FunctionDefinitionKind::Definition
);
3658 // FIXME: Since the return type isn't actually parsed, it can't be used to
3659 // fill ParamInfo with an initial valid range, so do it manually.
3660 ParamInfo
.SetSourceRange(SourceRange(Tok
.getLocation(), Tok
.getLocation()));
3662 // If this block has arguments, parse them. There is no ambiguity here with
3663 // the expression case, because the expression case requires a parameter list.
3664 if (Tok
.is(tok::l_paren
)) {
3665 ParseParenDeclarator(ParamInfo
);
3666 // Parse the pieces after the identifier as if we had "int(...)".
3667 // SetIdentifier sets the source range end, but in this case we're past
3669 SourceLocation Tmp
= ParamInfo
.getSourceRange().getEnd();
3670 ParamInfo
.SetIdentifier(nullptr, CaretLoc
);
3671 ParamInfo
.SetRangeEnd(Tmp
);
3672 if (ParamInfo
.isInvalidType()) {
3673 // If there was an error parsing the arguments, they may have
3674 // tried to use ^(x+y) which requires an argument list. Just
3675 // skip the whole block literal.
3676 Actions
.ActOnBlockError(CaretLoc
, getCurScope());
3680 MaybeParseGNUAttributes(ParamInfo
);
3682 // Inform sema that we are starting a block.
3683 Actions
.ActOnBlockArguments(CaretLoc
, ParamInfo
, getCurScope());
3684 } else if (!Tok
.is(tok::l_brace
)) {
3685 ParseBlockId(CaretLoc
);
3687 // Otherwise, pretend we saw (void).
3688 SourceLocation NoLoc
;
3689 ParamInfo
.AddTypeInfo(
3690 DeclaratorChunk::getFunction(/*HasProto=*/true,
3691 /*IsAmbiguous=*/false,
3692 /*RParenLoc=*/NoLoc
,
3693 /*ArgInfo=*/nullptr,
3695 /*EllipsisLoc=*/NoLoc
,
3696 /*RParenLoc=*/NoLoc
,
3697 /*RefQualifierIsLvalueRef=*/true,
3698 /*RefQualifierLoc=*/NoLoc
,
3699 /*MutableLoc=*/NoLoc
, EST_None
,
3700 /*ESpecRange=*/SourceRange(),
3701 /*Exceptions=*/nullptr,
3702 /*ExceptionRanges=*/nullptr,
3703 /*NumExceptions=*/0,
3704 /*NoexceptExpr=*/nullptr,
3705 /*ExceptionSpecTokens=*/nullptr,
3706 /*DeclsInPrototype=*/std::nullopt
,
3707 CaretLoc
, CaretLoc
, ParamInfo
),
3710 MaybeParseGNUAttributes(ParamInfo
);
3712 // Inform sema that we are starting a block.
3713 Actions
.ActOnBlockArguments(CaretLoc
, ParamInfo
, getCurScope());
3717 ExprResult
Result(true);
3718 if (!Tok
.is(tok::l_brace
)) {
3719 // Saw something like: ^expr
3720 Diag(Tok
, diag::err_expected_expression
);
3721 Actions
.ActOnBlockError(CaretLoc
, getCurScope());
3725 StmtResult
Stmt(ParseCompoundStatementBody());
3727 if (!Stmt
.isInvalid())
3728 Result
= Actions
.ActOnBlockStmtExpr(CaretLoc
, Stmt
.get(), getCurScope());
3730 Actions
.ActOnBlockError(CaretLoc
, getCurScope());
3734 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3738 ExprResult
Parser::ParseObjCBoolLiteral() {
3739 tok::TokenKind Kind
= Tok
.getKind();
3740 return Actions
.ActOnObjCBoolLiteral(ConsumeToken(), Kind
);
3743 /// Validate availability spec list, emitting diagnostics if necessary. Returns
3744 /// true if invalid.
3745 static bool CheckAvailabilitySpecList(Parser
&P
,
3746 ArrayRef
<AvailabilitySpec
> AvailSpecs
) {
3747 llvm::SmallSet
<StringRef
, 4> Platforms
;
3748 bool HasOtherPlatformSpec
= false;
3750 for (const auto &Spec
: AvailSpecs
) {
3751 if (Spec
.isOtherPlatformSpec()) {
3752 if (HasOtherPlatformSpec
) {
3753 P
.Diag(Spec
.getBeginLoc(), diag::err_availability_query_repeated_star
);
3757 HasOtherPlatformSpec
= true;
3761 bool Inserted
= Platforms
.insert(Spec
.getPlatform()).second
;
3763 // Rule out multiple version specs referring to the same platform.
3764 // For example, we emit an error for:
3765 // @available(macos 10.10, macos 10.11, *)
3766 StringRef Platform
= Spec
.getPlatform();
3767 P
.Diag(Spec
.getBeginLoc(), diag::err_availability_query_repeated_platform
)
3768 << Spec
.getEndLoc() << Platform
;
3773 if (!HasOtherPlatformSpec
) {
3774 SourceLocation InsertWildcardLoc
= AvailSpecs
.back().getEndLoc();
3775 P
.Diag(InsertWildcardLoc
, diag::err_availability_query_wildcard_required
)
3776 << FixItHint::CreateInsertion(InsertWildcardLoc
, ", *");
3783 /// Parse availability query specification.
3785 /// availability-spec:
3787 /// identifier version-tuple
3788 std::optional
<AvailabilitySpec
> Parser::ParseAvailabilitySpec() {
3789 if (Tok
.is(tok::star
)) {
3790 return AvailabilitySpec(ConsumeToken());
3792 // Parse the platform name.
3793 if (Tok
.is(tok::code_completion
)) {
3795 Actions
.CodeCompleteAvailabilityPlatformName();
3796 return std::nullopt
;
3798 if (Tok
.isNot(tok::identifier
)) {
3799 Diag(Tok
, diag::err_avail_query_expected_platform_name
);
3800 return std::nullopt
;
3803 IdentifierLoc
*PlatformIdentifier
= ParseIdentifierLoc();
3804 SourceRange VersionRange
;
3805 VersionTuple Version
= ParseVersionTuple(VersionRange
);
3807 if (Version
.empty())
3808 return std::nullopt
;
3810 StringRef GivenPlatform
= PlatformIdentifier
->Ident
->getName();
3811 StringRef Platform
=
3812 AvailabilityAttr::canonicalizePlatformName(GivenPlatform
);
3814 if (AvailabilityAttr::getPrettyPlatformName(Platform
).empty()) {
3815 Diag(PlatformIdentifier
->Loc
,
3816 diag::err_avail_query_unrecognized_platform_name
)
3818 return std::nullopt
;
3821 return AvailabilitySpec(Version
, Platform
, PlatformIdentifier
->Loc
,
3822 VersionRange
.getEnd());
3826 ExprResult
Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc
) {
3827 assert(Tok
.is(tok::kw___builtin_available
) ||
3828 Tok
.isObjCAtKeyword(tok::objc_available
));
3830 // Eat the available or __builtin_available.
3833 BalancedDelimiterTracker
Parens(*this, tok::l_paren
);
3834 if (Parens
.expectAndConsume())
3837 SmallVector
<AvailabilitySpec
, 4> AvailSpecs
;
3838 bool HasError
= false;
3840 std::optional
<AvailabilitySpec
> Spec
= ParseAvailabilitySpec();
3844 AvailSpecs
.push_back(*Spec
);
3846 if (!TryConsumeToken(tok::comma
))
3851 SkipUntil(tok::r_paren
, StopAtSemi
);
3855 CheckAvailabilitySpecList(*this, AvailSpecs
);
3857 if (Parens
.consumeClose())
3860 return Actions
.ActOnObjCAvailabilityCheckExpr(AvailSpecs
, BeginLoc
,
3861 Parens
.getCloseLocation());