1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Provides the Expression parsing implementation.
13 /// Expressions in C99 basically consist of a bunch of binary operators with
14 /// unary operators and other random stuff at the leaves.
16 /// In the C99 grammar, these unary operators bind tightest and are represented
17 /// as the 'cast-expression' production. Everything else is either a binary
18 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
19 /// handled by ParseCastExpression, the higher level pieces are handled by
20 /// ParseBinaryExpression.
22 //===----------------------------------------------------------------------===//
24 #include "clang/Parse/Parser.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/Basic/PrettyStackTrace.h"
27 #include "clang/Parse/RAIIObjectsForParser.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/ParsedTemplate.h"
30 #include "clang/Sema/Scope.h"
31 #include "clang/Sema/TypoCorrection.h"
32 #include "llvm/ADT/SmallVector.h"
33 using namespace clang;
35 /// \brief Simple precedence-based parser for binary/ternary operators.
37 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
38 /// production. C99 specifies that the LHS of an assignment operator should be
39 /// parsed as a unary-expression, but consistency dictates that it be a
40 /// conditional-expession. In practice, the important thing here is that the
41 /// LHS of an assignment has to be an l-value, which productions between
42 /// unary-expression and conditional-expression don't produce. Because we want
43 /// consistency, we parse the LHS as a conditional-expression, then check for
44 /// l-value-ness in semantic analysis stages.
47 /// pm-expression: [C++ 5.5]
49 /// pm-expression '.*' cast-expression
50 /// pm-expression '->*' cast-expression
52 /// multiplicative-expression: [C99 6.5.5]
53 /// Note: in C++, apply pm-expression instead of cast-expression
55 /// multiplicative-expression '*' cast-expression
56 /// multiplicative-expression '/' cast-expression
57 /// multiplicative-expression '%' cast-expression
59 /// additive-expression: [C99 6.5.6]
60 /// multiplicative-expression
61 /// additive-expression '+' multiplicative-expression
62 /// additive-expression '-' multiplicative-expression
64 /// shift-expression: [C99 6.5.7]
65 /// additive-expression
66 /// shift-expression '<<' additive-expression
67 /// shift-expression '>>' additive-expression
69 /// compare-expression: [C++20 expr.spaceship]
71 /// compare-expression '<=>' shift-expression
73 /// relational-expression: [C99 6.5.8]
74 /// compare-expression
75 /// relational-expression '<' compare-expression
76 /// relational-expression '>' compare-expression
77 /// relational-expression '<=' compare-expression
78 /// relational-expression '>=' compare-expression
80 /// equality-expression: [C99 6.5.9]
81 /// relational-expression
82 /// equality-expression '==' relational-expression
83 /// equality-expression '!=' relational-expression
85 /// AND-expression: [C99 6.5.10]
86 /// equality-expression
87 /// AND-expression '&' equality-expression
89 /// exclusive-OR-expression: [C99 6.5.11]
91 /// exclusive-OR-expression '^' AND-expression
93 /// inclusive-OR-expression: [C99 6.5.12]
94 /// exclusive-OR-expression
95 /// inclusive-OR-expression '|' exclusive-OR-expression
97 /// logical-AND-expression: [C99 6.5.13]
98 /// inclusive-OR-expression
99 /// logical-AND-expression '&&' inclusive-OR-expression
101 /// logical-OR-expression: [C99 6.5.14]
102 /// logical-AND-expression
103 /// logical-OR-expression '||' logical-AND-expression
105 /// conditional-expression: [C99 6.5.15]
106 /// logical-OR-expression
107 /// logical-OR-expression '?' expression ':' conditional-expression
108 /// [GNU] logical-OR-expression '?' ':' conditional-expression
109 /// [C++] the third operand is an assignment-expression
111 /// assignment-expression: [C99 6.5.16]
112 /// conditional-expression
113 /// unary-expression assignment-operator assignment-expression
114 /// [C++] throw-expression [C++ 15]
116 /// assignment-operator: one of
117 /// = *= /= %= += -= <<= >>= &= ^= |=
119 /// expression: [C99 6.5.17]
120 /// assignment-expression ...[opt]
121 /// expression ',' assignment-expression ...[opt]
123 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
124 ExprResult LHS(ParseAssignmentExpression(isTypeCast));
125 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
128 /// This routine is called when the '@' is seen and consumed.
129 /// Current token is an Identifier and is not a 'try'. This
130 /// routine is necessary to disambiguate \@try-statement from,
131 /// for example, \@encode-expression.
134 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
135 ExprResult LHS(ParseObjCAtExpression(AtLoc));
136 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
139 /// This routine is called when a leading '__extension__' is seen and
140 /// consumed. This is necessary because the token gets consumed in the
141 /// process of disambiguating between an expression and a declaration.
143 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
144 ExprResult LHS(true);
146 // Silence extension warnings in the sub-expression
147 ExtensionRAIIObject O(Diags);
149 LHS = ParseCastExpression(false);
152 if (!LHS.isInvalid())
153 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
156 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
159 /// \brief Parse an expr that doesn't include (top-level) commas.
160 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
161 if (Tok.is(tok::code_completion)) {
162 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
167 if (Tok.is(tok::kw_throw))
168 return ParseThrowExpression();
169 if (Tok.is(tok::kw_co_yield))
170 return ParseCoyieldExpression();
172 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
173 /*isAddressOfOperand=*/false,
175 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
178 /// \brief Parse an assignment expression where part of an Objective-C message
179 /// send has already been parsed.
181 /// In this case \p LBracLoc indicates the location of the '[' of the message
182 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
183 /// the receiver of the message.
185 /// Since this handles full assignment-expression's, it handles postfix
186 /// expressions and other binary operators for these expressions as well.
188 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
189 SourceLocation SuperLoc,
190 ParsedType ReceiverType,
191 Expr *ReceiverExpr) {
193 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
194 ReceiverType, ReceiverExpr);
195 R = ParsePostfixExpressionSuffix(R);
196 return ParseRHSOfBinaryExpression(R, prec::Assignment);
200 Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) {
201 assert(Actions.ExprEvalContexts.back().Context ==
202 Sema::ExpressionEvaluationContext::ConstantEvaluated &&
203 "Call this function only if your ExpressionEvaluationContext is "
204 "already ConstantEvaluated");
205 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
206 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
207 return Actions.ActOnConstantExpression(Res);
210 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
211 // C++03 [basic.def.odr]p2:
212 // An expression is potentially evaluated unless it appears where an
213 // integral constant expression is required (see 5.19) [...].
214 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
215 EnterExpressionEvaluationContext ConstantEvaluated(
216 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
217 return ParseConstantExpressionInExprEvalContext(isTypeCast);
220 /// \brief Parse a constraint-expression.
223 /// constraint-expression: [Concepts TS temp.constr.decl p1]
224 /// logical-or-expression
226 ExprResult Parser::ParseConstraintExpression() {
227 // FIXME: this may erroneously consume a function-body as the braced
228 // initializer list of a compound literal
230 // FIXME: this may erroneously consume a parenthesized rvalue reference
231 // declarator as a parenthesized address-of-label expression
232 ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
233 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
238 bool Parser::isNotExpressionStart() {
239 tok::TokenKind K = Tok.getKind();
240 if (K == tok::l_brace || K == tok::r_brace ||
241 K == tok::kw_for || K == tok::kw_while ||
242 K == tok::kw_if || K == tok::kw_else ||
243 K == tok::kw_goto || K == tok::kw_try)
245 // If this is a decl-specifier, we can't be at the start of an expression.
246 return isKnownToBeDeclarationSpecifier();
249 /// We've parsed something that could plausibly be intended to be a template
250 /// name (\p LHS) followed by a '<' token, and the following code can't possibly
251 /// be an expression. Determine if this is likely to be a template-id and if so,
253 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
254 TentativeParsingAction TPA(*this);
255 // FIXME: We could look at the token sequence in a lot more detail here.
256 if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
257 StopAtSemi | StopBeforeMatch)) {
260 SourceLocation Greater;
261 ParseGreaterThanInTemplateList(Greater, true, false);
262 Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
267 // There's no matching '>' token, this probably isn't supposed to be
268 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
273 bool Parser::isFoldOperator(prec::Level Level) const {
274 return Level > prec::Unknown && Level != prec::Conditional &&
275 Level != prec::Spaceship;
278 bool Parser::isFoldOperator(tok::TokenKind Kind) const {
279 return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
282 /// \brief Parse a binary expression that starts with \p LHS and has a
283 /// precedence of at least \p MinPrec.
285 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
286 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
287 GreaterThanIsOperator,
288 getLangOpts().CPlusPlus11);
289 SourceLocation ColonLoc;
292 // If this token has a lower precedence than we are allowed to parse (e.g.
293 // because we are called recursively, or because the token is not a binop),
295 if (NextTokPrec < MinPrec)
298 // Consume the operator, saving the operator token for error reporting.
302 if (OpToken.is(tok::caretcaret)) {
303 return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
305 // Bail out when encountering a comma followed by a token which can't
306 // possibly be the start of an expression. For instance:
307 // int f() { return 1, }
308 // We can't do this before consuming the comma, because
309 // isNotExpressionStart() looks at the token stream.
310 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
316 // If a '<' token is followed by a type that can be a template argument and
317 // cannot be an expression, then this is ill-formed, but might be intended
318 // to be a template-id.
319 if (OpToken.is(tok::less) && Actions.mightBeIntendedToBeTemplateName(LHS) &&
320 (isKnownToBeDeclarationSpecifier() ||
321 Tok.isOneOf(tok::greater, tok::greatergreater,
322 tok::greatergreatergreater)) &&
323 diagnoseUnknownTemplateId(LHS, OpToken.getLocation()))
326 // If the next token is an ellipsis, then this is a fold-expression. Leave
327 // it alone so we can handle it in the paren expression.
328 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
329 // FIXME: We can't check this via lookahead before we consume the token
330 // because that tickles a lexer bug.
336 // Special case handling for the ternary operator.
337 ExprResult TernaryMiddle(true);
338 if (NextTokPrec == prec::Conditional) {
339 if (Tok.isNot(tok::colon)) {
340 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
341 ColonProtectionRAIIObject X(*this);
343 // Handle this production specially:
344 // logical-OR-expression '?' expression ':' conditional-expression
345 // In particular, the RHS of the '?' is 'expression', not
346 // 'logical-OR-expression' as we might expect.
347 TernaryMiddle = ParseExpression();
348 if (TernaryMiddle.isInvalid()) {
349 Actions.CorrectDelayedTyposInExpr(LHS);
351 TernaryMiddle = nullptr;
354 // Special case handling of "X ? Y : Z" where Y is empty:
355 // logical-OR-expression '?' ':' conditional-expression [GNU]
356 TernaryMiddle = nullptr;
357 Diag(Tok, diag::ext_gnu_conditional_expr);
360 if (!TryConsumeToken(tok::colon, ColonLoc)) {
361 // Otherwise, we're missing a ':'. Assume that this was a typo that
362 // the user forgot. If we're not in a macro expansion, we can suggest
363 // a fixit hint. If there were two spaces before the current token,
364 // suggest inserting the colon in between them, otherwise insert ": ".
365 SourceLocation FILoc = Tok.getLocation();
366 const char *FIText = ": ";
367 const SourceManager &SM = PP.getSourceManager();
368 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
369 assert(FILoc.isFileID());
370 bool IsInvalid = false;
371 const char *SourcePtr =
372 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
373 if (!IsInvalid && *SourcePtr == ' ') {
375 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
376 if (!IsInvalid && *SourcePtr == ' ') {
377 FILoc = FILoc.getLocWithOffset(-1);
383 Diag(Tok, diag::err_expected)
384 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
385 Diag(OpToken, diag::note_matching) << tok::question;
386 ColonLoc = Tok.getLocation();
390 // Code completion for the right-hand side of an assignment expression
391 // goes through a special hook that takes the left-hand side into account.
392 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
393 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
398 // Parse another leaf here for the RHS of the operator.
399 // ParseCastExpression works here because all RHS expressions in C have it
400 // as a prefix, at least. However, in C++, an assignment-expression could
401 // be a throw-expression, which is not a valid cast-expression.
402 // Therefore we need some special-casing here.
403 // Also note that the third operand of the conditional operator is
404 // an assignment-expression in C++, and in C++11, we can have a
405 // braced-init-list on the RHS of an assignment. For better diagnostics,
406 // parse as if we were allowed braced-init-lists everywhere, and check that
407 // they only appear on the RHS of assignments later.
409 bool RHSIsInitList = false;
410 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
411 RHS = ParseBraceInitializer();
412 RHSIsInitList = true;
413 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
414 RHS = ParseAssignmentExpression();
416 RHS = ParseCastExpression(false);
418 if (RHS.isInvalid()) {
419 // FIXME: Errors generated by the delayed typo correction should be
420 // printed before errors from parsing the RHS, not after.
421 Actions.CorrectDelayedTyposInExpr(LHS);
422 if (TernaryMiddle.isUsable())
423 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
427 // Remember the precedence of this operator and get the precedence of the
428 // operator immediately to the right of the RHS.
429 prec::Level ThisPrec = NextTokPrec;
430 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
431 getLangOpts().CPlusPlus11);
433 // Assignment and conditional expressions are right-associative.
434 bool isRightAssoc = ThisPrec == prec::Conditional ||
435 ThisPrec == prec::Assignment;
437 // Get the precedence of the operator to the right of the RHS. If it binds
438 // more tightly with RHS than we do, evaluate it completely first.
439 if (ThisPrec < NextTokPrec ||
440 (ThisPrec == NextTokPrec && isRightAssoc)) {
441 if (!RHS.isInvalid() && RHSIsInitList) {
442 Diag(Tok, diag::err_init_list_bin_op)
443 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
446 // If this is left-associative, only parse things on the RHS that bind
447 // more tightly than the current operator. If it is left-associative, it
448 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
449 // A=(B=(C=D)), where each paren is a level of recursion here.
450 // The function takes ownership of the RHS.
451 RHS = ParseRHSOfBinaryExpression(RHS,
452 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
453 RHSIsInitList = false;
455 if (RHS.isInvalid()) {
456 // FIXME: Errors generated by the delayed typo correction should be
457 // printed before errors from ParseRHSOfBinaryExpression, not after.
458 Actions.CorrectDelayedTyposInExpr(LHS);
459 if (TernaryMiddle.isUsable())
460 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
464 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
465 getLangOpts().CPlusPlus11);
468 if (!RHS.isInvalid() && RHSIsInitList) {
469 if (ThisPrec == prec::Assignment) {
470 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
471 << Actions.getExprRange(RHS.get());
473 Diag(OpToken, diag::err_init_list_bin_op)
474 << /*RHS*/1 << PP.getSpelling(OpToken)
475 << Actions.getExprRange(RHS.get());
480 ExprResult OrigLHS = LHS;
481 if (!LHS.isInvalid()) {
482 // Combine the LHS and RHS into the LHS (e.g. build AST).
483 if (TernaryMiddle.isInvalid()) {
484 // If we're using '>>' as an operator within a template
485 // argument list (in C++98), suggest the addition of
486 // parentheses so that the code remains well-formed in C++0x.
487 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
488 SuggestParentheses(OpToken.getLocation(),
489 diag::warn_cxx11_right_shift_in_template_arg,
490 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
491 Actions.getExprRange(RHS.get()).getEnd()));
493 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
494 OpToken.getKind(), LHS.get(), RHS.get());
497 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
498 LHS.get(), TernaryMiddle.get(),
501 // In this case, ActOnBinOp or ActOnConditionalOp performed the
502 // CorrectDelayedTyposInExpr check.
503 if (!getLangOpts().CPlusPlus)
507 // Ensure potential typos aren't left undiagnosed.
508 if (LHS.isInvalid()) {
509 Actions.CorrectDelayedTyposInExpr(OrigLHS);
510 Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
511 Actions.CorrectDelayedTyposInExpr(RHS);
516 /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
517 /// parse a unary-expression.
519 /// \p isAddressOfOperand exists because an id-expression that is the
520 /// operand of address-of gets special treatment due to member pointers.
522 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
523 bool isAddressOfOperand,
524 TypeCastState isTypeCast,
525 bool isVectorLiteral) {
527 ExprResult Res = ParseCastExpression(isUnaryExpression,
533 Diag(Tok, diag::err_expected_expression);
538 class CastExpressionIdValidator : public CorrectionCandidateCallback {
540 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
541 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
542 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
545 bool ValidateCandidate(const TypoCorrection &candidate) override {
546 NamedDecl *ND = candidate.getCorrectionDecl();
548 return candidate.isKeyword();
550 if (isa<TypeDecl>(ND))
551 return WantTypeSpecifiers;
553 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
556 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
559 for (auto *C : candidate) {
560 NamedDecl *ND = C->getUnderlyingDecl();
561 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
573 /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
574 /// a unary-expression.
576 /// \p isAddressOfOperand exists because an id-expression that is the operand
577 /// of address-of gets special treatment due to member pointers. NotCastExpr
578 /// is set to true if the token is not the start of a cast-expression, and no
579 /// diagnostic is emitted in this case and no tokens are consumed.
582 /// cast-expression: [C99 6.5.4]
584 /// '(' type-name ')' cast-expression
586 /// unary-expression: [C99 6.5.3]
587 /// postfix-expression
588 /// '++' unary-expression
589 /// '--' unary-expression
590 /// [Coro] 'co_await' cast-expression
591 /// unary-operator cast-expression
592 /// 'sizeof' unary-expression
593 /// 'sizeof' '(' type-name ')'
594 /// [C++11] 'sizeof' '...' '(' identifier ')'
595 /// [GNU] '__alignof' unary-expression
596 /// [GNU] '__alignof' '(' type-name ')'
597 /// [C11] '_Alignof' '(' type-name ')'
598 /// [C++11] 'alignof' '(' type-id ')'
599 /// [GNU] '&&' identifier
600 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
601 /// [C++] new-expression
602 /// [C++] delete-expression
604 /// unary-operator: one of
605 /// '&' '*' '+' '-' '~' '!'
606 /// [GNU] '__extension__' '__real' '__imag'
608 /// primary-expression: [C99 6.5.1]
610 /// [C++] id-expression
613 /// [C++] boolean-literal [C++ 2.13.5]
614 /// [C++11] 'nullptr' [C++11 2.14.7]
615 /// [C++11] user-defined-literal
616 /// '(' expression ')'
617 /// [C11] generic-selection
618 /// '__func__' [C99 6.4.2.2]
619 /// [GNU] '__FUNCTION__'
620 /// [MS] '__FUNCDNAME__'
621 /// [MS] 'L__FUNCTION__'
622 /// [GNU] '__PRETTY_FUNCTION__'
623 /// [GNU] '(' compound-statement ')'
624 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
625 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
626 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
628 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
630 /// [OBJC] '[' objc-message-expr ']'
631 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
632 /// [OBJC] '\@protocol' '(' identifier ')'
633 /// [OBJC] '\@encode' '(' type-name ')'
634 /// [OBJC] objc-string-literal
635 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
636 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
637 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
638 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
639 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
640 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
641 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
642 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
643 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
644 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
645 /// [C++] 'this' [C++ 9.3.2]
646 /// [G++] unary-type-trait '(' type-id ')'
647 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
648 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
649 /// [clang] '^' block-literal
651 /// constant: [C99 6.4.4]
653 /// floating-constant
654 /// enumeration-constant -> identifier
655 /// character-constant
657 /// id-expression: [C++ 5.1]
661 /// unqualified-id: [C++ 5.1]
663 /// operator-function-id
664 /// conversion-function-id
668 /// new-expression: [C++ 5.3.4]
669 /// '::'[opt] 'new' new-placement[opt] new-type-id
670 /// new-initializer[opt]
671 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
672 /// new-initializer[opt]
674 /// delete-expression: [C++ 5.3.5]
675 /// '::'[opt] 'delete' cast-expression
676 /// '::'[opt] 'delete' '[' ']' cast-expression
678 /// [GNU/Embarcadero] unary-type-trait:
679 /// '__is_arithmetic'
680 /// '__is_floating_point'
682 /// '__is_lvalue_expr'
683 /// '__is_rvalue_expr'
684 /// '__is_complete_type'
689 /// '__is_lvalue_reference'
690 /// '__is_rvalue_reference'
691 /// '__is_fundamental'
696 /// '__is_member_object_pointer'
697 /// '__is_member_function_pointer'
698 /// '__is_member_pointer'
702 /// '__is_standard_layout'
706 /// [GNU] unary-type-trait:
707 /// '__has_nothrow_assign'
708 /// '__has_nothrow_copy'
709 /// '__has_nothrow_constructor'
710 /// '__has_trivial_assign' [TODO]
711 /// '__has_trivial_copy' [TODO]
712 /// '__has_trivial_constructor'
713 /// '__has_trivial_destructor'
714 /// '__has_virtual_destructor'
715 /// '__is_abstract' [TODO]
717 /// '__is_empty' [TODO]
721 /// '__is_polymorphic'
722 /// '__is_sealed' [MS]
725 /// '__has_unique_object_representations'
727 /// [Clang] unary-type-trait:
729 /// '__trivially_copyable'
731 /// binary-type-trait:
732 /// [GNU] '__is_base_of'
733 /// [MS] '__is_convertible_to'
734 /// '__is_convertible'
737 /// [Embarcadero] array-type-trait:
741 /// [Embarcadero] expression-trait:
742 /// '__is_lvalue_expr'
743 /// '__is_rvalue_expr'
746 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
747 bool isAddressOfOperand,
749 TypeCastState isTypeCast,
750 bool isVectorLiteral) {
752 tok::TokenKind SavedKind = Tok.getKind();
755 // This handles all of cast-expression, unary-expression, postfix-expression,
756 // and primary-expression. We handle them together like this for efficiency
757 // and to simplify handling of an expression starting with a '(' token: which
758 // may be one of a parenthesized expression, cast-expression, compound literal
759 // expression, or statement expression.
761 // If the parsed tokens consist of a primary-expression, the cases below
762 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
763 // to handle the postfix expression suffixes. Cases that cannot be followed
764 // by postfix exprs should return without invoking
765 // ParsePostfixExpressionSuffix.
768 // If this expression is limited to being a unary-expression, the parent can
769 // not start a cast expression.
770 ParenParseOption ParenExprType =
771 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
774 SourceLocation RParenLoc;
775 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
776 isTypeCast == IsTypeCast, CastTy, RParenLoc);
781 switch (ParenExprType) {
782 case SimpleExpr: break; // Nothing else to do.
783 case CompoundStmt: break; // Nothing else to do.
784 case CompoundLiteral:
785 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
786 // postfix-expression exist, parse them now.
789 // We have parsed the cast-expression and no postfix-expr pieces are
797 // primary-expression
798 case tok::numeric_constant:
799 // constant: integer-constant
800 // constant: floating-constant
802 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
808 Res = ParseCXXBoolLiteral();
811 case tok::kw___objc_yes:
812 case tok::kw___objc_no:
813 return ParseObjCBoolLiteral();
815 case tok::kw_nullptr:
816 Diag(Tok, diag::warn_cxx98_compat_nullptr);
817 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
819 case tok::annot_primary_expr:
820 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
821 Res = getExprAnnotation(Tok);
822 ConsumeAnnotationToken();
825 case tok::kw___super:
826 case tok::kw_decltype:
827 // Annotate the token and tail recurse.
828 if (TryAnnotateTypeOrScopeToken())
830 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
831 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
833 case tok::identifier: { // primary-expression: identifier
834 // unqualified-id: identifier
835 // constant: enumeration-constant
836 // Turn a potentially qualified name into a annot_typename or
837 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
838 if (getLangOpts().CPlusPlus) {
839 // Avoid the unnecessary parse-time lookup in the common case
840 // where the syntax forbids a type.
841 const Token &Next = NextToken();
843 // If this identifier was reverted from a token ID, and the next token
844 // is a parenthesis, this is likely to be a use of a type trait. Check
846 if (Next.is(tok::l_paren) &&
847 Tok.is(tok::identifier) &&
848 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
849 IdentifierInfo *II = Tok.getIdentifierInfo();
850 // Build up the mapping of revertible type traits, for future use.
851 if (RevertibleTypeTraits.empty()) {
852 #define RTT_JOIN(X,Y) X##Y
853 #define REVERTIBLE_TYPE_TRAIT(Name) \
854 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
855 = RTT_JOIN(tok::kw_,Name)
857 REVERTIBLE_TYPE_TRAIT(__is_abstract);
858 REVERTIBLE_TYPE_TRAIT(__is_aggregate);
859 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
860 REVERTIBLE_TYPE_TRAIT(__is_array);
861 REVERTIBLE_TYPE_TRAIT(__is_assignable);
862 REVERTIBLE_TYPE_TRAIT(__is_base_of);
863 REVERTIBLE_TYPE_TRAIT(__is_class);
864 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
865 REVERTIBLE_TYPE_TRAIT(__is_compound);
866 REVERTIBLE_TYPE_TRAIT(__is_const);
867 REVERTIBLE_TYPE_TRAIT(__is_constructible);
868 REVERTIBLE_TYPE_TRAIT(__is_convertible);
869 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
870 REVERTIBLE_TYPE_TRAIT(__is_destructible);
871 REVERTIBLE_TYPE_TRAIT(__is_empty);
872 REVERTIBLE_TYPE_TRAIT(__is_enum);
873 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
874 REVERTIBLE_TYPE_TRAIT(__is_final);
875 REVERTIBLE_TYPE_TRAIT(__is_function);
876 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
877 REVERTIBLE_TYPE_TRAIT(__is_integral);
878 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
879 REVERTIBLE_TYPE_TRAIT(__is_literal);
880 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
881 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
882 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
883 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
884 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
885 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
886 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
887 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
888 REVERTIBLE_TYPE_TRAIT(__is_object);
889 REVERTIBLE_TYPE_TRAIT(__is_pod);
890 REVERTIBLE_TYPE_TRAIT(__is_pointer);
891 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
892 REVERTIBLE_TYPE_TRAIT(__is_reference);
893 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
894 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
895 REVERTIBLE_TYPE_TRAIT(__is_same);
896 REVERTIBLE_TYPE_TRAIT(__is_scalar);
897 REVERTIBLE_TYPE_TRAIT(__is_sealed);
898 REVERTIBLE_TYPE_TRAIT(__is_signed);
899 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
900 REVERTIBLE_TYPE_TRAIT(__is_trivial);
901 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
902 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
903 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
904 REVERTIBLE_TYPE_TRAIT(__is_union);
905 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
906 REVERTIBLE_TYPE_TRAIT(__is_void);
907 REVERTIBLE_TYPE_TRAIT(__is_volatile);
908 #undef REVERTIBLE_TYPE_TRAIT
912 // If we find that this is in fact the name of a type trait,
913 // update the token kind in place and parse again to treat it as
914 // the appropriate kind of type trait.
915 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
916 = RevertibleTypeTraits.find(II);
917 if (Known != RevertibleTypeTraits.end()) {
918 Tok.setKind(Known->second);
919 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
920 NotCastExpr, isTypeCast);
924 if ((!ColonIsSacred && Next.is(tok::colon)) ||
925 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
927 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
928 if (TryAnnotateTypeOrScopeToken())
930 if (!Tok.is(tok::identifier))
931 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
935 // Consume the identifier so that we can see if it is followed by a '(' or
937 IdentifierInfo &II = *Tok.getIdentifierInfo();
938 SourceLocation ILoc = ConsumeToken();
940 // Support 'Class.property' and 'super.property' notation.
941 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
942 (Actions.getTypeName(II, ILoc, getCurScope()) ||
943 // Allow the base to be 'super' if in an objc-method.
944 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
947 if (Tok.is(tok::code_completion) && &II != Ident_super) {
948 Actions.CodeCompleteObjCClassPropertyRefExpr(
949 getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
953 // Allow either an identifier or the keyword 'class' (in C++).
954 if (Tok.isNot(tok::identifier) &&
955 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
956 Diag(Tok, diag::err_expected_property_name);
959 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
960 SourceLocation PropertyLoc = ConsumeToken();
962 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
967 // In an Objective-C method, if we have "super" followed by an identifier,
968 // the token sequence is ill-formed. However, if there's a ':' or ']' after
969 // that identifier, this is probably a message send with a missing open
970 // bracket. Treat it as such.
971 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
972 getCurScope()->isInObjcMethodScope() &&
973 ((Tok.is(tok::identifier) &&
974 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
975 Tok.is(tok::code_completion))) {
976 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
981 // If we have an Objective-C class name followed by an identifier
982 // and either ':' or ']', this is an Objective-C class message
983 // send that's missing the opening '['. Recovery
984 // appropriately. Also take this path if we're performing code
985 // completion after an Objective-C class name.
986 if (getLangOpts().ObjC1 &&
987 ((Tok.is(tok::identifier) && !InMessageExpression) ||
988 Tok.is(tok::code_completion))) {
989 const Token& Next = NextToken();
990 if (Tok.is(tok::code_completion) ||
991 Next.is(tok::colon) || Next.is(tok::r_square))
992 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
993 if (Typ.get()->isObjCObjectOrInterfaceType()) {
994 // Fake up a Declarator to use with ActOnTypeName.
995 DeclSpec DS(AttrFactory);
996 DS.SetRangeStart(ILoc);
997 DS.SetRangeEnd(ILoc);
998 const char *PrevSpec = nullptr;
1000 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1001 Actions.getASTContext().getPrintingPolicy());
1003 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1004 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1009 Res = ParseObjCMessageExpressionBody(SourceLocation(),
1016 // Make sure to pass down the right value for isAddressOfOperand.
1017 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
1018 isAddressOfOperand = false;
1020 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1021 // need to know whether or not this identifier is a function designator or
1024 CXXScopeSpec ScopeSpec;
1025 SourceLocation TemplateKWLoc;
1027 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
1028 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
1029 Validator->IsAddressOfOperand = isAddressOfOperand;
1030 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1031 Validator->WantExpressionKeywords = false;
1032 Validator->WantRemainingKeywords = false;
1034 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
1036 Name.setIdentifier(&II, ILoc);
1037 Res = Actions.ActOnIdExpression(
1038 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1039 isAddressOfOperand, std::move(Validator),
1040 /*IsInlineAsmIdentifier=*/false,
1041 Tok.is(tok::r_paren) ? nullptr : &Replacement);
1042 if (!Res.isInvalid() && !Res.get()) {
1043 UnconsumeToken(Replacement);
1044 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1045 NotCastExpr, isTypeCast);
1049 case tok::char_constant: // constant: character-constant
1050 case tok::wide_char_constant:
1051 case tok::utf8_char_constant:
1052 case tok::utf16_char_constant:
1053 case tok::utf32_char_constant:
1054 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1057 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
1058 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
1059 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
1060 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
1061 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
1062 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1063 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1066 case tok::string_literal: // primary-expression: string-literal
1067 case tok::wide_string_literal:
1068 case tok::utf8_string_literal:
1069 case tok::utf16_string_literal:
1070 case tok::utf32_string_literal:
1071 Res = ParseStringLiteralExpression(true);
1073 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1074 Res = ParseGenericSelectionExpression();
1076 case tok::kw___builtin_available:
1077 return ParseAvailabilityCheckExpr(Tok.getLocation());
1078 case tok::kw___builtin_va_arg:
1079 case tok::kw___builtin_offsetof:
1080 case tok::kw___builtin_choose_expr:
1081 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1082 case tok::kw___builtin_convertvector:
1083 return ParseBuiltinPrimaryExpression();
1084 case tok::kw___null:
1085 return Actions.ActOnGNUNullExpr(ConsumeToken());
1087 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1088 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1089 // C++ [expr.unary] has:
1090 // unary-expression:
1091 // ++ cast-expression
1092 // -- cast-expression
1093 Token SavedTok = Tok;
1095 // One special case is implicitly handled here: if the preceding tokens are
1096 // an ambiguous cast expression, such as "(T())++", then we recurse to
1097 // determine whether the '++' is prefix or postfix.
1098 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1099 /*isAddressOfOperand*/false, NotCastExpr,
1102 // If we return with NotCastExpr = true, we must not consume any tokens,
1103 // so put the token back where we found it.
1104 assert(Res.isInvalid());
1105 UnconsumeToken(SavedTok);
1108 if (!Res.isInvalid())
1109 Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1110 SavedKind, Res.get());
1113 case tok::amp: { // unary-expression: '&' cast-expression
1114 // Special treatment because of member pointers
1115 SourceLocation SavedLoc = ConsumeToken();
1116 Res = ParseCastExpression(false, true);
1117 if (!Res.isInvalid())
1118 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1122 case tok::star: // unary-expression: '*' cast-expression
1123 case tok::plus: // unary-expression: '+' cast-expression
1124 case tok::minus: // unary-expression: '-' cast-expression
1125 case tok::tilde: // unary-expression: '~' cast-expression
1126 case tok::exclaim: // unary-expression: '!' cast-expression
1127 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1128 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1129 SourceLocation SavedLoc = ConsumeToken();
1130 Res = ParseCastExpression(false);
1131 if (!Res.isInvalid())
1132 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1136 case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1137 SourceLocation CoawaitLoc = ConsumeToken();
1138 Res = ParseCastExpression(false);
1139 if (!Res.isInvalid())
1140 Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1144 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1145 // __extension__ silences extension warnings in the subexpression.
1146 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1147 SourceLocation SavedLoc = ConsumeToken();
1148 Res = ParseCastExpression(false);
1149 if (!Res.isInvalid())
1150 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1153 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1154 if (!getLangOpts().C11)
1155 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1157 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1158 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1159 // unary-expression: '__alignof' '(' type-name ')'
1160 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1161 // unary-expression: 'sizeof' '(' type-name ')'
1162 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1163 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1164 case tok::kw___builtin_omp_required_simd_align:
1165 return ParseUnaryExprOrTypeTraitExpression();
1166 case tok::ampamp: { // unary-expression: '&&' identifier
1167 SourceLocation AmpAmpLoc = ConsumeToken();
1168 if (Tok.isNot(tok::identifier))
1169 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1171 if (getCurScope()->getFnParent() == nullptr)
1172 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1174 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1175 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1177 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1181 case tok::kw_const_cast:
1182 case tok::kw_dynamic_cast:
1183 case tok::kw_reinterpret_cast:
1184 case tok::kw_static_cast:
1185 Res = ParseCXXCasts();
1187 case tok::kw_typeid:
1188 Res = ParseCXXTypeid();
1190 case tok::kw___uuidof:
1191 Res = ParseCXXUuidof();
1194 Res = ParseCXXThis();
1197 case tok::annot_typename:
1198 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1199 ParsedType Type = getTypeAnnotation(Tok);
1201 // Fake up a Declarator to use with ActOnTypeName.
1202 DeclSpec DS(AttrFactory);
1203 DS.SetRangeStart(Tok.getLocation());
1204 DS.SetRangeEnd(Tok.getLastLoc());
1206 const char *PrevSpec = nullptr;
1208 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1209 PrevSpec, DiagID, Type,
1210 Actions.getASTContext().getPrintingPolicy());
1212 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1213 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1217 ConsumeAnnotationToken();
1218 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1224 case tok::annot_decltype:
1226 case tok::kw_wchar_t:
1227 case tok::kw_char16_t:
1228 case tok::kw_char32_t:
1233 case tok::kw___int64:
1234 case tok::kw___int128:
1235 case tok::kw_signed:
1236 case tok::kw_unsigned:
1239 case tok::kw_double:
1240 case tok::kw__Float16:
1241 case tok::kw___float128:
1243 case tok::kw_typename:
1244 case tok::kw_typeof:
1245 case tok::kw___vector:
1246 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1247 #include "clang/Basic/OpenCLImageTypes.def"
1249 if (!getLangOpts().CPlusPlus) {
1250 Diag(Tok, diag::err_expected_expression);
1254 if (SavedKind == tok::kw_typename) {
1255 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1256 // typename-specifier braced-init-list
1257 if (TryAnnotateTypeOrScopeToken())
1260 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1261 // We are trying to parse a simple-type-specifier but might not get such
1262 // a token after error recovery.
1266 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1267 // simple-type-specifier braced-init-list
1269 DeclSpec DS(AttrFactory);
1271 ParseCXXSimpleTypeSpecifier(DS);
1272 if (Tok.isNot(tok::l_paren) &&
1273 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1274 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1275 << DS.getSourceRange());
1277 if (Tok.is(tok::l_brace))
1278 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1280 Res = ParseCXXTypeConstructExpression(DS);
1284 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1285 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1286 // (We can end up in this situation after tentative parsing.)
1287 if (TryAnnotateTypeOrScopeToken())
1289 if (!Tok.is(tok::annot_cxxscope))
1290 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1291 NotCastExpr, isTypeCast);
1293 Token Next = NextToken();
1294 if (Next.is(tok::annot_template_id)) {
1295 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1296 if (TemplateId->Kind == TNK_Type_template) {
1297 // We have a qualified template-id that we know refers to a
1298 // type, translate it into a type and continue parsing as a
1301 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1302 /*EnteringContext=*/false);
1303 AnnotateTemplateIdTokenAsType();
1304 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1305 NotCastExpr, isTypeCast);
1309 // Parse as an id-expression.
1310 Res = ParseCXXIdExpression(isAddressOfOperand);
1314 case tok::annot_template_id: { // [C++] template-id
1315 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1316 if (TemplateId->Kind == TNK_Type_template) {
1317 // We have a template-id that we know refers to a type,
1318 // translate it into a type and continue parsing as a cast
1320 AnnotateTemplateIdTokenAsType();
1321 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1322 NotCastExpr, isTypeCast);
1325 // Fall through to treat the template-id as an id-expression.
1329 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1330 Res = ParseCXXIdExpression(isAddressOfOperand);
1333 case tok::coloncolon: {
1334 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1335 // annotates the token, tail recurse.
1336 if (TryAnnotateTypeOrScopeToken())
1338 if (!Tok.is(tok::coloncolon))
1339 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1341 // ::new -> [C++] new-expression
1342 // ::delete -> [C++] delete-expression
1343 SourceLocation CCLoc = ConsumeToken();
1344 if (Tok.is(tok::kw_new))
1345 return ParseCXXNewExpression(true, CCLoc);
1346 if (Tok.is(tok::kw_delete))
1347 return ParseCXXDeleteExpression(true, CCLoc);
1349 // This is not a type name or scope specifier, it is an invalid expression.
1350 Diag(CCLoc, diag::err_expected_expression);
1354 case tok::kw_new: // [C++] new-expression
1355 return ParseCXXNewExpression(false, Tok.getLocation());
1357 case tok::kw_delete: // [C++] delete-expression
1358 return ParseCXXDeleteExpression(false, Tok.getLocation());
1360 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1361 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1362 SourceLocation KeyLoc = ConsumeToken();
1363 BalancedDelimiterTracker T(*this, tok::l_paren);
1365 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1367 // C++11 [expr.unary.noexcept]p1:
1368 // The noexcept operator determines whether the evaluation of its operand,
1369 // which is an unevaluated operand, can throw an exception.
1370 EnterExpressionEvaluationContext Unevaluated(
1371 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1372 ExprResult Result = ParseExpression();
1376 if (!Result.isInvalid())
1377 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1378 Result.get(), T.getCloseLocation());
1382 #define TYPE_TRAIT(N,Spelling,K) \
1383 case tok::kw_##Spelling:
1384 #include "clang/Basic/TokenKinds.def"
1385 return ParseTypeTrait();
1387 case tok::kw___array_rank:
1388 case tok::kw___array_extent:
1389 return ParseArrayTypeTrait();
1391 case tok::kw___is_lvalue_expr:
1392 case tok::kw___is_rvalue_expr:
1393 return ParseExpressionTrait();
1396 SourceLocation AtLoc = ConsumeToken();
1397 return ParseObjCAtExpression(AtLoc);
1400 Res = ParseBlockLiteralExpression();
1402 case tok::code_completion: {
1403 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1408 if (getLangOpts().CPlusPlus11) {
1409 if (getLangOpts().ObjC1) {
1410 // C++11 lambda expressions and Objective-C message sends both start with a
1411 // square bracket. There are three possibilities here:
1412 // we have a valid lambda expression, we have an invalid lambda
1413 // expression, or we have something that doesn't appear to be a lambda.
1414 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1415 Res = TryParseLambdaExpression();
1416 if (!Res.isInvalid() && !Res.get())
1417 Res = ParseObjCMessageExpression();
1420 Res = ParseLambdaExpression();
1423 if (getLangOpts().ObjC1) {
1424 Res = ParseObjCMessageExpression();
1433 // Check to see whether Res is a function designator only. If it is and we
1434 // are compiling for OpenCL, we need to return an error as this implies
1435 // that the address of the function is being taken, which is illegal in CL.
1437 // These can be followed by postfix-expr pieces.
1438 Res = ParsePostfixExpressionSuffix(Res);
1439 if (getLangOpts().OpenCL)
1440 if (Expr *PostfixExpr = Res.get()) {
1441 QualType Ty = PostfixExpr->getType();
1442 if (!Ty.isNull() && Ty->isFunctionType()) {
1443 Diag(PostfixExpr->getExprLoc(),
1444 diag::err_opencl_taking_function_address_parser);
1452 /// \brief Once the leading part of a postfix-expression is parsed, this
1453 /// method parses any suffixes that apply.
1456 /// postfix-expression: [C99 6.5.2]
1457 /// primary-expression
1458 /// postfix-expression '[' expression ']'
1459 /// postfix-expression '[' braced-init-list ']'
1460 /// postfix-expression '(' argument-expression-list[opt] ')'
1461 /// postfix-expression '.' identifier
1462 /// postfix-expression '->' identifier
1463 /// postfix-expression '++'
1464 /// postfix-expression '--'
1465 /// '(' type-name ')' '{' initializer-list '}'
1466 /// '(' type-name ')' '{' initializer-list ',' '}'
1468 /// argument-expression-list: [C99 6.5.2]
1469 /// argument-expression ...[opt]
1470 /// argument-expression-list ',' assignment-expression ...[opt]
1473 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1474 // Now that the primary-expression piece of the postfix-expression has been
1475 // parsed, see if there are any postfix-expression pieces here.
1478 switch (Tok.getKind()) {
1479 case tok::code_completion:
1480 if (InMessageExpression)
1483 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1487 case tok::identifier:
1488 // If we see identifier: after an expression, and we're not already in a
1489 // message send, then this is probably a message send with a missing
1490 // opening bracket '['.
1491 if (getLangOpts().ObjC1 && !InMessageExpression &&
1492 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1493 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1494 nullptr, LHS.get());
1497 // Fall through; this isn't a message send.
1500 default: // Not a postfix-expression suffix.
1502 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1503 // If we have a array postfix expression that starts on a new line and
1504 // Objective-C is enabled, it is highly likely that the user forgot a
1505 // semicolon after the base expression and that the array postfix-expr is
1506 // actually another message send. In this case, do some look-ahead to see
1507 // if the contents of the square brackets are obviously not a valid
1508 // expression and recover by pretending there is no suffix.
1509 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1510 isSimpleObjCMessageExpression())
1513 // Reject array indices starting with a lambda-expression. '[[' is
1514 // reserved for attributes.
1515 if (CheckProhibitedCXX11Attribute()) {
1516 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1520 BalancedDelimiterTracker T(*this, tok::l_square);
1522 Loc = T.getOpenLocation();
1523 ExprResult Idx, Length;
1524 SourceLocation ColonLoc;
1525 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1526 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1527 Idx = ParseBraceInitializer();
1528 } else if (getLangOpts().OpenMP) {
1529 ColonProtectionRAIIObject RAII(*this);
1530 // Parse [: or [ expr or [ expr :
1531 if (!Tok.is(tok::colon)) {
1533 Idx = ParseExpression();
1535 if (Tok.is(tok::colon)) {
1537 ColonLoc = ConsumeToken();
1538 if (Tok.isNot(tok::r_square))
1539 Length = ParseExpression();
1542 Idx = ParseExpression();
1544 SourceLocation RLoc = Tok.getLocation();
1546 ExprResult OrigLHS = LHS;
1547 if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1548 Tok.is(tok::r_square)) {
1549 if (ColonLoc.isValid()) {
1550 LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1551 ColonLoc, Length.get(), RLoc);
1553 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1559 if (LHS.isInvalid()) {
1560 (void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
1561 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1562 (void)Actions.CorrectDelayedTyposInExpr(Length);
1572 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1573 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1574 // '(' argument-expression-list[opt] ')'
1575 tok::TokenKind OpKind = Tok.getKind();
1576 InMessageExpressionRAIIObject InMessage(*this, false);
1578 Expr *ExecConfig = nullptr;
1580 BalancedDelimiterTracker PT(*this, tok::l_paren);
1582 if (OpKind == tok::lesslessless) {
1583 ExprVector ExecConfigExprs;
1584 CommaLocsTy ExecConfigCommaLocs;
1585 SourceLocation OpenLoc = ConsumeToken();
1587 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1588 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1592 SourceLocation CloseLoc;
1593 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1594 } else if (LHS.isInvalid()) {
1595 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1597 // There was an error closing the brackets
1598 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1599 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1600 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1604 if (!LHS.isInvalid()) {
1605 if (ExpectAndConsume(tok::l_paren))
1608 Loc = PrevTokLocation;
1611 if (!LHS.isInvalid()) {
1612 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1616 if (ECResult.isInvalid())
1619 ExecConfig = ECResult.get();
1623 Loc = PT.getOpenLocation();
1626 ExprVector ArgExprs;
1627 CommaLocsTy CommaLocs;
1629 if (Tok.is(tok::code_completion)) {
1630 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1635 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1636 if (Tok.isNot(tok::r_paren)) {
1637 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1638 Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1640 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1642 } else if (LHS.isInvalid()) {
1643 for (auto &E : ArgExprs)
1644 Actions.CorrectDelayedTyposInExpr(E);
1650 if (LHS.isInvalid()) {
1651 SkipUntil(tok::r_paren, StopAtSemi);
1652 } else if (Tok.isNot(tok::r_paren)) {
1653 bool HadDelayedTypo = false;
1654 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1655 HadDelayedTypo = true;
1656 for (auto &E : ArgExprs)
1657 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1658 HadDelayedTypo = true;
1659 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1660 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1661 // the unmatched l_paren.
1663 SkipUntil(tok::r_paren, StopAtSemi);
1668 assert((ArgExprs.size() == 0 ||
1669 ArgExprs.size()-1 == CommaLocs.size())&&
1670 "Unexpected number of commas!");
1671 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1672 ArgExprs, Tok.getLocation(),
1681 // postfix-expression: p-e '->' template[opt] id-expression
1682 // postfix-expression: p-e '.' template[opt] id-expression
1683 tok::TokenKind OpKind = Tok.getKind();
1684 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1687 ParsedType ObjectType;
1688 bool MayBePseudoDestructor = false;
1689 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1690 Expr *Base = LHS.get();
1691 const Type* BaseType = Base->getType().getTypePtrOrNull();
1692 if (BaseType && Tok.is(tok::l_paren) &&
1693 (BaseType->isFunctionType() ||
1694 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1695 Diag(OpLoc, diag::err_function_is_not_record)
1696 << OpKind << Base->getSourceRange()
1697 << FixItHint::CreateRemoval(OpLoc);
1698 return ParsePostfixExpressionSuffix(Base);
1701 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1702 OpLoc, OpKind, ObjectType,
1703 MayBePseudoDestructor);
1704 if (LHS.isInvalid())
1707 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1708 /*EnteringContext=*/false,
1709 &MayBePseudoDestructor);
1710 if (SS.isNotEmpty())
1711 ObjectType = nullptr;
1714 if (Tok.is(tok::code_completion)) {
1715 // Code completion for a member access expression.
1716 if (Expr *Base = LHS.get())
1717 Actions.CodeCompleteMemberReferenceExpr(
1718 getCurScope(), Base, OpLoc, OpKind == tok::arrow,
1719 ExprStatementTokLoc == Base->getLocStart());
1725 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1726 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1731 // Either the action has told us that this cannot be a
1732 // pseudo-destructor expression (based on the type of base
1733 // expression), or we didn't see a '~' in the right place. We
1734 // can still parse a destructor name here, but in that case it
1735 // names a real destructor.
1736 // Allow explicit constructor calls in Microsoft mode.
1737 // FIXME: Add support for explicit call of template constructor.
1738 SourceLocation TemplateKWLoc;
1740 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1741 Tok.is(tok::kw_class)) {
1743 // After a '.' in a member access expression, treat the keyword
1744 // 'class' as if it were an identifier.
1746 // This hack allows property access to the 'class' method because it is
1747 // such a common method name. For other C++ keywords that are
1748 // Objective-C method names, one must use the message send syntax.
1749 IdentifierInfo *Id = Tok.getIdentifierInfo();
1750 SourceLocation Loc = ConsumeToken();
1751 Name.setIdentifier(Id, Loc);
1752 } else if (ParseUnqualifiedId(SS,
1753 /*EnteringContext=*/false,
1754 /*AllowDestructorName=*/true,
1755 /*AllowConstructorName=*/
1756 getLangOpts().MicrosoftExt,
1757 /*AllowDeductionGuide=*/false,
1758 ObjectType, TemplateKWLoc, Name)) {
1759 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1763 if (!LHS.isInvalid())
1764 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1765 OpKind, SS, TemplateKWLoc, Name,
1766 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1770 case tok::plusplus: // postfix-expression: postfix-expression '++'
1771 case tok::minusminus: // postfix-expression: postfix-expression '--'
1772 if (!LHS.isInvalid()) {
1773 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1774 Tok.getKind(), LHS.get());
1782 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1783 /// vec_step and we are at the start of an expression or a parenthesized
1784 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1785 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1788 /// unary-expression: [C99 6.5.3]
1789 /// 'sizeof' unary-expression
1790 /// 'sizeof' '(' type-name ')'
1791 /// [GNU] '__alignof' unary-expression
1792 /// [GNU] '__alignof' '(' type-name ')'
1793 /// [C11] '_Alignof' '(' type-name ')'
1794 /// [C++0x] 'alignof' '(' type-id ')'
1796 /// [GNU] typeof-specifier:
1797 /// typeof ( expressions )
1798 /// typeof ( type-name )
1799 /// [GNU/C++] typeof unary-expression
1801 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1802 /// vec_step ( expressions )
1803 /// vec_step ( type-name )
1806 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1809 SourceRange &CastRange) {
1811 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1812 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1813 tok::kw___builtin_omp_required_simd_align) &&
1814 "Not a typeof/sizeof/alignof/vec_step expression!");
1818 // If the operand doesn't start with an '(', it must be an expression.
1819 if (Tok.isNot(tok::l_paren)) {
1820 // If construct allows a form without parenthesis, user may forget to put
1821 // pathenthesis around type name.
1822 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1823 tok::kw__Alignof)) {
1824 if (isTypeIdUnambiguously()) {
1825 DeclSpec DS(AttrFactory);
1826 ParseSpecifierQualifierList(DS);
1827 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1828 ParseDeclarator(DeclaratorInfo);
1830 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1831 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1832 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1834 << FixItHint::CreateInsertion(LParenLoc, "(")
1835 << FixItHint::CreateInsertion(RParenLoc, ")");
1842 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1843 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1848 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1850 // If it starts with a '(', we know that it is either a parenthesized
1851 // type-name, or it is a unary-expression that starts with a compound
1852 // literal, or starts with a primary-expression that is a parenthesized
1854 ParenParseOption ExprType = CastExpr;
1855 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1857 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1858 false, CastTy, RParenLoc);
1859 CastRange = SourceRange(LParenLoc, RParenLoc);
1861 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1863 if (ExprType == CastExpr) {
1868 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1869 // GNU typeof in C requires the expression to be parenthesized. Not so for
1870 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1871 // the start of a unary-expression, but doesn't include any postfix
1872 // pieces. Parse these now if present.
1873 if (!Operand.isInvalid())
1874 Operand = ParsePostfixExpressionSuffix(Operand.get());
1878 // If we get here, the operand to the typeof/sizeof/alignof was an expression.
1884 /// \brief Parse a sizeof or alignof expression.
1887 /// unary-expression: [C99 6.5.3]
1888 /// 'sizeof' unary-expression
1889 /// 'sizeof' '(' type-name ')'
1890 /// [C++11] 'sizeof' '...' '(' identifier ')'
1891 /// [GNU] '__alignof' unary-expression
1892 /// [GNU] '__alignof' '(' type-name ')'
1893 /// [C11] '_Alignof' '(' type-name ')'
1894 /// [C++11] 'alignof' '(' type-id ')'
1896 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1897 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1898 tok::kw__Alignof, tok::kw_vec_step,
1899 tok::kw___builtin_omp_required_simd_align) &&
1900 "Not a sizeof/alignof/vec_step expression!");
1904 // [C++11] 'sizeof' '...' '(' identifier ')'
1905 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1906 SourceLocation EllipsisLoc = ConsumeToken();
1907 SourceLocation LParenLoc, RParenLoc;
1908 IdentifierInfo *Name = nullptr;
1909 SourceLocation NameLoc;
1910 if (Tok.is(tok::l_paren)) {
1911 BalancedDelimiterTracker T(*this, tok::l_paren);
1913 LParenLoc = T.getOpenLocation();
1914 if (Tok.is(tok::identifier)) {
1915 Name = Tok.getIdentifierInfo();
1916 NameLoc = ConsumeToken();
1918 RParenLoc = T.getCloseLocation();
1919 if (RParenLoc.isInvalid())
1920 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1922 Diag(Tok, diag::err_expected_parameter_pack);
1923 SkipUntil(tok::r_paren, StopAtSemi);
1925 } else if (Tok.is(tok::identifier)) {
1926 Name = Tok.getIdentifierInfo();
1927 NameLoc = ConsumeToken();
1928 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1929 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1930 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1932 << FixItHint::CreateInsertion(LParenLoc, "(")
1933 << FixItHint::CreateInsertion(RParenLoc, ")");
1935 Diag(Tok, diag::err_sizeof_parameter_pack);
1941 EnterExpressionEvaluationContext Unevaluated(
1942 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1943 Sema::ReuseLambdaContextDecl);
1945 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1946 OpTok.getLocation(),
1951 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1952 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1954 EnterExpressionEvaluationContext Unevaluated(
1955 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1956 Sema::ReuseLambdaContextDecl);
1960 SourceRange CastRange;
1961 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1966 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1967 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1968 ExprKind = UETT_AlignOf;
1969 else if (OpTok.is(tok::kw_vec_step))
1970 ExprKind = UETT_VecStep;
1971 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
1972 ExprKind = UETT_OpenMPRequiredSimdAlign;
1975 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1978 CastTy.getAsOpaquePtr(),
1981 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1982 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1984 // If we get here, the operand to the sizeof/alignof was an expression.
1985 if (!Operand.isInvalid())
1986 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1994 /// ParseBuiltinPrimaryExpression
1997 /// primary-expression: [C99 6.5.1]
1998 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1999 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2000 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2002 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2003 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
2005 /// [GNU] offsetof-member-designator:
2006 /// [GNU] identifier
2007 /// [GNU] offsetof-member-designator '.' identifier
2008 /// [GNU] offsetof-member-designator '[' expression ']'
2010 ExprResult Parser::ParseBuiltinPrimaryExpression() {
2012 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2014 tok::TokenKind T = Tok.getKind();
2015 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
2017 // All of these start with an open paren.
2018 if (Tok.isNot(tok::l_paren))
2019 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2022 BalancedDelimiterTracker PT(*this, tok::l_paren);
2028 default: llvm_unreachable("Not a builtin primary expression!");
2029 case tok::kw___builtin_va_arg: {
2030 ExprResult Expr(ParseAssignmentExpression());
2032 if (ExpectAndConsume(tok::comma)) {
2033 SkipUntil(tok::r_paren, StopAtSemi);
2037 TypeResult Ty = ParseTypeName();
2039 if (Tok.isNot(tok::r_paren)) {
2040 Diag(Tok, diag::err_expected) << tok::r_paren;
2044 if (Expr.isInvalid() || Ty.isInvalid())
2047 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2050 case tok::kw___builtin_offsetof: {
2051 SourceLocation TypeLoc = Tok.getLocation();
2052 TypeResult Ty = ParseTypeName();
2053 if (Ty.isInvalid()) {
2054 SkipUntil(tok::r_paren, StopAtSemi);
2058 if (ExpectAndConsume(tok::comma)) {
2059 SkipUntil(tok::r_paren, StopAtSemi);
2063 // We must have at least one identifier here.
2064 if (Tok.isNot(tok::identifier)) {
2065 Diag(Tok, diag::err_expected) << tok::identifier;
2066 SkipUntil(tok::r_paren, StopAtSemi);
2070 // Keep track of the various subcomponents we see.
2071 SmallVector<Sema::OffsetOfComponent, 4> Comps;
2073 Comps.push_back(Sema::OffsetOfComponent());
2074 Comps.back().isBrackets = false;
2075 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2076 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2078 // FIXME: This loop leaks the index expressions on error.
2080 if (Tok.is(tok::period)) {
2081 // offsetof-member-designator: offsetof-member-designator '.' identifier
2082 Comps.push_back(Sema::OffsetOfComponent());
2083 Comps.back().isBrackets = false;
2084 Comps.back().LocStart = ConsumeToken();
2086 if (Tok.isNot(tok::identifier)) {
2087 Diag(Tok, diag::err_expected) << tok::identifier;
2088 SkipUntil(tok::r_paren, StopAtSemi);
2091 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2092 Comps.back().LocEnd = ConsumeToken();
2094 } else if (Tok.is(tok::l_square)) {
2095 if (CheckProhibitedCXX11Attribute())
2098 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2099 Comps.push_back(Sema::OffsetOfComponent());
2100 Comps.back().isBrackets = true;
2101 BalancedDelimiterTracker ST(*this, tok::l_square);
2103 Comps.back().LocStart = ST.getOpenLocation();
2104 Res = ParseExpression();
2105 if (Res.isInvalid()) {
2106 SkipUntil(tok::r_paren, StopAtSemi);
2109 Comps.back().U.E = Res.get();
2112 Comps.back().LocEnd = ST.getCloseLocation();
2114 if (Tok.isNot(tok::r_paren)) {
2117 } else if (Ty.isInvalid()) {
2121 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2123 PT.getCloseLocation());
2130 case tok::kw___builtin_choose_expr: {
2131 ExprResult Cond(ParseAssignmentExpression());
2132 if (Cond.isInvalid()) {
2133 SkipUntil(tok::r_paren, StopAtSemi);
2136 if (ExpectAndConsume(tok::comma)) {
2137 SkipUntil(tok::r_paren, StopAtSemi);
2141 ExprResult Expr1(ParseAssignmentExpression());
2142 if (Expr1.isInvalid()) {
2143 SkipUntil(tok::r_paren, StopAtSemi);
2146 if (ExpectAndConsume(tok::comma)) {
2147 SkipUntil(tok::r_paren, StopAtSemi);
2151 ExprResult Expr2(ParseAssignmentExpression());
2152 if (Expr2.isInvalid()) {
2153 SkipUntil(tok::r_paren, StopAtSemi);
2156 if (Tok.isNot(tok::r_paren)) {
2157 Diag(Tok, diag::err_expected) << tok::r_paren;
2160 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2161 Expr2.get(), ConsumeParen());
2164 case tok::kw___builtin_astype: {
2165 // The first argument is an expression to be converted, followed by a comma.
2166 ExprResult Expr(ParseAssignmentExpression());
2167 if (Expr.isInvalid()) {
2168 SkipUntil(tok::r_paren, StopAtSemi);
2172 if (ExpectAndConsume(tok::comma)) {
2173 SkipUntil(tok::r_paren, StopAtSemi);
2177 // Second argument is the type to bitcast to.
2178 TypeResult DestTy = ParseTypeName();
2179 if (DestTy.isInvalid())
2182 // Attempt to consume the r-paren.
2183 if (Tok.isNot(tok::r_paren)) {
2184 Diag(Tok, diag::err_expected) << tok::r_paren;
2185 SkipUntil(tok::r_paren, StopAtSemi);
2189 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2193 case tok::kw___builtin_convertvector: {
2194 // The first argument is an expression to be converted, followed by a comma.
2195 ExprResult Expr(ParseAssignmentExpression());
2196 if (Expr.isInvalid()) {
2197 SkipUntil(tok::r_paren, StopAtSemi);
2201 if (ExpectAndConsume(tok::comma)) {
2202 SkipUntil(tok::r_paren, StopAtSemi);
2206 // Second argument is the type to bitcast to.
2207 TypeResult DestTy = ParseTypeName();
2208 if (DestTy.isInvalid())
2211 // Attempt to consume the r-paren.
2212 if (Tok.isNot(tok::r_paren)) {
2213 Diag(Tok, diag::err_expected) << tok::r_paren;
2214 SkipUntil(tok::r_paren, StopAtSemi);
2218 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2224 if (Res.isInvalid())
2227 // These can be followed by postfix-expr pieces because they are
2228 // primary-expressions.
2229 return ParsePostfixExpressionSuffix(Res.get());
2232 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2233 /// based on what is allowed by ExprType. The actual thing parsed is returned
2234 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2235 /// not the parsed cast-expression.
2238 /// primary-expression: [C99 6.5.1]
2239 /// '(' expression ')'
2240 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2241 /// postfix-expression: [C99 6.5.2]
2242 /// '(' type-name ')' '{' initializer-list '}'
2243 /// '(' type-name ')' '{' initializer-list ',' '}'
2244 /// cast-expression: [C99 6.5.4]
2245 /// '(' type-name ')' cast-expression
2246 /// [ARC] bridged-cast-expression
2247 /// [ARC] bridged-cast-expression:
2248 /// (__bridge type-name) cast-expression
2249 /// (__bridge_transfer type-name) cast-expression
2250 /// (__bridge_retained type-name) cast-expression
2251 /// fold-expression: [C++1z]
2252 /// '(' cast-expression fold-operator '...' ')'
2253 /// '(' '...' fold-operator cast-expression ')'
2254 /// '(' cast-expression fold-operator '...'
2255 /// fold-operator cast-expression ')'
2258 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2259 bool isTypeCast, ParsedType &CastTy,
2260 SourceLocation &RParenLoc) {
2261 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2262 ColonProtectionRAIIObject ColonProtection(*this, false);
2263 BalancedDelimiterTracker T(*this, tok::l_paren);
2264 if (T.consumeOpen())
2266 SourceLocation OpenLoc = T.getOpenLocation();
2268 ExprResult Result(true);
2269 bool isAmbiguousTypeId;
2272 if (Tok.is(tok::code_completion)) {
2273 Actions.CodeCompleteOrdinaryName(getCurScope(),
2274 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2275 : Sema::PCC_Expression);
2280 // Diagnose use of bridge casts in non-arc mode.
2281 bool BridgeCast = (getLangOpts().ObjC2 &&
2282 Tok.isOneOf(tok::kw___bridge,
2283 tok::kw___bridge_transfer,
2284 tok::kw___bridge_retained,
2285 tok::kw___bridge_retain));
2286 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2287 if (!TryConsumeToken(tok::kw___bridge)) {
2288 StringRef BridgeCastName = Tok.getName();
2289 SourceLocation BridgeKeywordLoc = ConsumeToken();
2290 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2291 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2293 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2298 // None of these cases should fall through with an invalid Result
2299 // unless they've already reported an error.
2300 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2301 Diag(Tok, diag::ext_gnu_statement_expr);
2303 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2304 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2306 // Find the nearest non-record decl context. Variables declared in a
2307 // statement expression behave as if they were declared in the enclosing
2308 // function, block, or other code construct.
2309 DeclContext *CodeDC = Actions.CurContext;
2310 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2311 CodeDC = CodeDC->getParent();
2312 assert(CodeDC && !CodeDC->isFileContext() &&
2313 "statement expr not in code context");
2315 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2317 Actions.ActOnStartStmtExpr();
2319 StmtResult Stmt(ParseCompoundStatement(true));
2320 ExprType = CompoundStmt;
2322 // If the substmt parsed correctly, build the AST node.
2323 if (!Stmt.isInvalid()) {
2324 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2326 Actions.ActOnStmtExprError();
2329 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2330 tok::TokenKind tokenKind = Tok.getKind();
2331 SourceLocation BridgeKeywordLoc = ConsumeToken();
2333 // Parse an Objective-C ARC ownership cast expression.
2334 ObjCBridgeCastKind Kind;
2335 if (tokenKind == tok::kw___bridge)
2337 else if (tokenKind == tok::kw___bridge_transfer)
2338 Kind = OBC_BridgeTransfer;
2339 else if (tokenKind == tok::kw___bridge_retained)
2340 Kind = OBC_BridgeRetained;
2342 // As a hopefully temporary workaround, allow __bridge_retain as
2343 // a synonym for __bridge_retained, but only in system headers.
2344 assert(tokenKind == tok::kw___bridge_retain);
2345 Kind = OBC_BridgeRetained;
2346 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2347 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2348 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2349 "__bridge_retained");
2352 TypeResult Ty = ParseTypeName();
2354 ColonProtection.restore();
2355 RParenLoc = T.getCloseLocation();
2356 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2358 if (Ty.isInvalid() || SubExpr.isInvalid())
2361 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2362 BridgeKeywordLoc, Ty.get(),
2363 RParenLoc, SubExpr.get());
2364 } else if (ExprType >= CompoundLiteral &&
2365 isTypeIdInParens(isAmbiguousTypeId)) {
2367 // Otherwise, this is a compound literal expression or cast expression.
2369 // In C++, if the type-id is ambiguous we disambiguate based on context.
2370 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2371 // in which case we should treat it as type-id.
2372 // if stopIfCastExpr is false, we need to determine the context past the
2373 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2374 if (isAmbiguousTypeId && !stopIfCastExpr) {
2375 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2377 RParenLoc = T.getCloseLocation();
2381 // Parse the type declarator.
2382 DeclSpec DS(AttrFactory);
2383 ParseSpecifierQualifierList(DS);
2384 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2385 ParseDeclarator(DeclaratorInfo);
2387 // If our type is followed by an identifier and either ':' or ']', then
2388 // this is probably an Objective-C message send where the leading '[' is
2389 // missing. Recover as if that were the case.
2390 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2391 !InMessageExpression && getLangOpts().ObjC1 &&
2392 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2395 InMessageExpressionRAIIObject InMessage(*this, false);
2396 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2398 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2404 ColonProtection.restore();
2405 RParenLoc = T.getCloseLocation();
2406 if (Tok.is(tok::l_brace)) {
2407 ExprType = CompoundLiteral;
2410 InMessageExpressionRAIIObject InMessage(*this, false);
2411 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2413 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2416 if (Tok.is(tok::l_paren)) {
2417 // This could be OpenCL vector Literals
2418 if (getLangOpts().OpenCL)
2422 InMessageExpressionRAIIObject InMessage(*this, false);
2423 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2429 QualType QT = Ty.get().get().getCanonicalType();
2430 if (QT->isVectorType())
2432 // We parsed '(' vector-type-name ')' followed by '('
2434 // Parse the cast-expression that follows it next.
2435 // isVectorLiteral = true will make sure we don't parse any
2436 // Postfix expression yet
2437 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2438 /*isAddressOfOperand=*/false,
2439 /*isTypeCast=*/IsTypeCast,
2440 /*isVectorLiteral=*/true);
2442 if (!Result.isInvalid()) {
2443 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2444 DeclaratorInfo, CastTy,
2445 RParenLoc, Result.get());
2448 // After we performed the cast we can check for postfix-expr pieces.
2449 if (!Result.isInvalid()) {
2450 Result = ParsePostfixExpressionSuffix(Result);
2458 if (ExprType == CastExpr) {
2459 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2461 if (DeclaratorInfo.isInvalidType())
2464 // Note that this doesn't parse the subsequent cast-expression, it just
2465 // returns the parsed type to the callee.
2466 if (stopIfCastExpr) {
2469 InMessageExpressionRAIIObject InMessage(*this, false);
2470 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2473 return ExprResult();
2476 // Reject the cast of super idiom in ObjC.
2477 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2478 Tok.getIdentifierInfo() == Ident_super &&
2479 getCurScope()->isInObjcMethodScope() &&
2480 GetLookAheadToken(1).isNot(tok::period)) {
2481 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2482 << SourceRange(OpenLoc, RParenLoc);
2486 // Parse the cast-expression that follows it next.
2487 // TODO: For cast expression with CastTy.
2488 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2489 /*isAddressOfOperand=*/false,
2490 /*isTypeCast=*/IsTypeCast);
2491 if (!Result.isInvalid()) {
2492 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2493 DeclaratorInfo, CastTy,
2494 RParenLoc, Result.get());
2499 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2502 } else if (Tok.is(tok::ellipsis) &&
2503 isFoldOperator(NextToken().getKind())) {
2504 return ParseFoldExpression(ExprResult(), T);
2505 } else if (isTypeCast) {
2506 // Parse the expression-list.
2507 InMessageExpressionRAIIObject InMessage(*this, false);
2509 ExprVector ArgExprs;
2510 CommaLocsTy CommaLocs;
2512 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2513 // FIXME: If we ever support comma expressions as operands to
2514 // fold-expressions, we'll need to allow multiple ArgExprs here.
2515 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2516 NextToken().is(tok::ellipsis))
2517 return ParseFoldExpression(ArgExprs[0], T);
2519 ExprType = SimpleExpr;
2520 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2524 InMessageExpressionRAIIObject InMessage(*this, false);
2526 Result = ParseExpression(MaybeTypeCast);
2527 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2528 // Correct typos in non-C++ code earlier so that implicit-cast-like
2529 // expressions are parsed correctly.
2530 Result = Actions.CorrectDelayedTyposInExpr(Result);
2532 ExprType = SimpleExpr;
2534 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2535 return ParseFoldExpression(Result, T);
2537 // Don't build a paren expression unless we actually match a ')'.
2538 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2540 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2544 if (Result.isInvalid()) {
2545 SkipUntil(tok::r_paren, StopAtSemi);
2550 RParenLoc = T.getCloseLocation();
2554 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2555 /// and we are at the left brace.
2558 /// postfix-expression: [C99 6.5.2]
2559 /// '(' type-name ')' '{' initializer-list '}'
2560 /// '(' type-name ')' '{' initializer-list ',' '}'
2563 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2564 SourceLocation LParenLoc,
2565 SourceLocation RParenLoc) {
2566 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2567 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2568 Diag(LParenLoc, diag::ext_c99_compound_literal);
2569 ExprResult Result = ParseInitializer();
2570 if (!Result.isInvalid() && Ty)
2571 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2575 /// ParseStringLiteralExpression - This handles the various token types that
2576 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2577 /// translation phase #6].
2580 /// primary-expression: [C99 6.5.1]
2583 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2584 assert(isTokenStringLiteral() && "Not a string literal!");
2586 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2587 // considered to be strings for concatenation purposes.
2588 SmallVector<Token, 4> StringToks;
2591 StringToks.push_back(Tok);
2592 ConsumeStringToken();
2593 } while (isTokenStringLiteral());
2595 // Pass the set of string tokens, ready for concatenation, to the actions.
2596 return Actions.ActOnStringLiteral(StringToks,
2597 AllowUserDefinedLiteral ? getCurScope()
2601 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2605 /// generic-selection:
2606 /// _Generic ( assignment-expression , generic-assoc-list )
2607 /// generic-assoc-list:
2608 /// generic-association
2609 /// generic-assoc-list , generic-association
2610 /// generic-association:
2611 /// type-name : assignment-expression
2612 /// default : assignment-expression
2614 ExprResult Parser::ParseGenericSelectionExpression() {
2615 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2616 SourceLocation KeyLoc = ConsumeToken();
2618 if (!getLangOpts().C11)
2619 Diag(KeyLoc, diag::ext_c11_generic_selection);
2621 BalancedDelimiterTracker T(*this, tok::l_paren);
2622 if (T.expectAndConsume())
2625 ExprResult ControllingExpr;
2627 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2629 EnterExpressionEvaluationContext Unevaluated(
2630 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
2632 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2633 if (ControllingExpr.isInvalid()) {
2634 SkipUntil(tok::r_paren, StopAtSemi);
2639 if (ExpectAndConsume(tok::comma)) {
2640 SkipUntil(tok::r_paren, StopAtSemi);
2644 SourceLocation DefaultLoc;
2649 if (Tok.is(tok::kw_default)) {
2650 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2651 // generic association."
2652 if (!DefaultLoc.isInvalid()) {
2653 Diag(Tok, diag::err_duplicate_default_assoc);
2654 Diag(DefaultLoc, diag::note_previous_default_assoc);
2655 SkipUntil(tok::r_paren, StopAtSemi);
2658 DefaultLoc = ConsumeToken();
2661 ColonProtectionRAIIObject X(*this);
2662 TypeResult TR = ParseTypeName();
2663 if (TR.isInvalid()) {
2664 SkipUntil(tok::r_paren, StopAtSemi);
2669 Types.push_back(Ty);
2671 if (ExpectAndConsume(tok::colon)) {
2672 SkipUntil(tok::r_paren, StopAtSemi);
2676 // FIXME: These expressions should be parsed in a potentially potentially
2677 // evaluated context.
2679 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2680 if (ER.isInvalid()) {
2681 SkipUntil(tok::r_paren, StopAtSemi);
2684 Exprs.push_back(ER.get());
2685 } while (TryConsumeToken(tok::comma));
2688 if (T.getCloseLocation().isInvalid())
2691 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2692 T.getCloseLocation(),
2693 ControllingExpr.get(),
2697 /// \brief Parse A C++1z fold-expression after the opening paren and optional
2698 /// left-hand-side expression.
2701 /// fold-expression:
2702 /// ( cast-expression fold-operator ... )
2703 /// ( ... fold-operator cast-expression )
2704 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2705 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2706 BalancedDelimiterTracker &T) {
2707 if (LHS.isInvalid()) {
2712 tok::TokenKind Kind = tok::unknown;
2713 SourceLocation FirstOpLoc;
2714 if (LHS.isUsable()) {
2715 Kind = Tok.getKind();
2716 assert(isFoldOperator(Kind) && "missing fold-operator");
2717 FirstOpLoc = ConsumeToken();
2720 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2721 SourceLocation EllipsisLoc = ConsumeToken();
2724 if (Tok.isNot(tok::r_paren)) {
2725 if (!isFoldOperator(Tok.getKind()))
2726 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2728 if (Kind != tok::unknown && Tok.getKind() != Kind)
2729 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2730 << SourceRange(FirstOpLoc);
2731 Kind = Tok.getKind();
2734 RHS = ParseExpression();
2735 if (RHS.isInvalid()) {
2741 Diag(EllipsisLoc, getLangOpts().CPlusPlus17
2742 ? diag::warn_cxx14_compat_fold_expression
2743 : diag::ext_fold_expression);
2746 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2747 EllipsisLoc, RHS.get(), T.getCloseLocation());
2750 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2753 /// argument-expression-list:
2754 /// assignment-expression
2755 /// argument-expression-list , assignment-expression
2757 /// [C++] expression-list:
2758 /// [C++] assignment-expression
2759 /// [C++] expression-list , assignment-expression
2761 /// [C++0x] expression-list:
2762 /// [C++0x] initializer-list
2764 /// [C++0x] initializer-list
2765 /// [C++0x] initializer-clause ...[opt]
2766 /// [C++0x] initializer-list , initializer-clause ...[opt]
2768 /// [C++0x] initializer-clause:
2769 /// [C++0x] assignment-expression
2770 /// [C++0x] braced-init-list
2772 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2773 SmallVectorImpl<SourceLocation> &CommaLocs,
2774 llvm::function_ref<void()> Completer) {
2775 bool SawError = false;
2777 if (Tok.is(tok::code_completion)) {
2781 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2787 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2788 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2789 Expr = ParseBraceInitializer();
2791 Expr = ParseAssignmentExpression();
2793 if (Tok.is(tok::ellipsis))
2794 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2795 if (Expr.isInvalid()) {
2796 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2799 Exprs.push_back(Expr.get());
2802 if (Tok.isNot(tok::comma))
2804 // Move to the next argument, remember where the comma was.
2805 CommaLocs.push_back(ConsumeToken());
2808 // Ensure typos get diagnosed when errors were encountered while parsing the
2810 for (auto &E : Exprs) {
2811 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2812 if (Expr.isUsable()) E = Expr.get();
2818 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2819 /// used for misc language extensions.
2822 /// simple-expression-list:
2823 /// assignment-expression
2824 /// simple-expression-list , assignment-expression
2827 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2828 SmallVectorImpl<SourceLocation> &CommaLocs) {
2830 ExprResult Expr = ParseAssignmentExpression();
2831 if (Expr.isInvalid())
2834 Exprs.push_back(Expr.get());
2836 if (Tok.isNot(tok::comma))
2839 // Move to the next argument, remember where the comma was.
2840 CommaLocs.push_back(ConsumeToken());
2844 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2847 /// [clang] block-id:
2848 /// [clang] specifier-qualifier-list block-declarator
2850 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2851 if (Tok.is(tok::code_completion)) {
2852 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2853 return cutOffParsing();
2856 // Parse the specifier-qualifier-list piece.
2857 DeclSpec DS(AttrFactory);
2858 ParseSpecifierQualifierList(DS);
2860 // Parse the block-declarator.
2861 Declarator DeclaratorInfo(DS, DeclaratorContext::BlockLiteralContext);
2862 DeclaratorInfo.setFunctionDefinitionKind(FDK_Definition);
2863 ParseDeclarator(DeclaratorInfo);
2865 MaybeParseGNUAttributes(DeclaratorInfo);
2867 // Inform sema that we are starting a block.
2868 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2871 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2872 /// like ^(int x){ return x+1; }
2876 /// [clang] '^' block-args[opt] compound-statement
2877 /// [clang] '^' block-id compound-statement
2878 /// [clang] block-args:
2879 /// [clang] '(' parameter-list ')'
2881 ExprResult Parser::ParseBlockLiteralExpression() {
2882 assert(Tok.is(tok::caret) && "block literal starts with ^");
2883 SourceLocation CaretLoc = ConsumeToken();
2885 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2886 "block literal parsing");
2888 // Enter a scope to hold everything within the block. This includes the
2889 // argument decls, decls within the compound expression, etc. This also
2890 // allows determining whether a variable reference inside the block is
2891 // within or outside of the block.
2892 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2893 Scope::CompoundStmtScope | Scope::DeclScope);
2895 // Inform sema that we are starting a block.
2896 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2898 // Parse the return type if present.
2899 DeclSpec DS(AttrFactory);
2900 Declarator ParamInfo(DS, DeclaratorContext::BlockLiteralContext);
2901 ParamInfo.setFunctionDefinitionKind(FDK_Definition);
2902 // FIXME: Since the return type isn't actually parsed, it can't be used to
2903 // fill ParamInfo with an initial valid range, so do it manually.
2904 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2906 // If this block has arguments, parse them. There is no ambiguity here with
2907 // the expression case, because the expression case requires a parameter list.
2908 if (Tok.is(tok::l_paren)) {
2909 ParseParenDeclarator(ParamInfo);
2910 // Parse the pieces after the identifier as if we had "int(...)".
2911 // SetIdentifier sets the source range end, but in this case we're past
2913 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2914 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2915 ParamInfo.SetRangeEnd(Tmp);
2916 if (ParamInfo.isInvalidType()) {
2917 // If there was an error parsing the arguments, they may have
2918 // tried to use ^(x+y) which requires an argument list. Just
2919 // skip the whole block literal.
2920 Actions.ActOnBlockError(CaretLoc, getCurScope());
2924 MaybeParseGNUAttributes(ParamInfo);
2926 // Inform sema that we are starting a block.
2927 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2928 } else if (!Tok.is(tok::l_brace)) {
2929 ParseBlockId(CaretLoc);
2931 // Otherwise, pretend we saw (void).
2932 ParsedAttributes attrs(AttrFactory);
2933 SourceLocation NoLoc;
2934 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2935 /*IsAmbiguous=*/false,
2936 /*RParenLoc=*/NoLoc,
2937 /*ArgInfo=*/nullptr,
2939 /*EllipsisLoc=*/NoLoc,
2940 /*RParenLoc=*/NoLoc,
2942 /*RefQualifierIsLvalueRef=*/true,
2943 /*RefQualifierLoc=*/NoLoc,
2944 /*ConstQualifierLoc=*/NoLoc,
2945 /*VolatileQualifierLoc=*/NoLoc,
2946 /*RestrictQualifierLoc=*/NoLoc,
2947 /*MutableLoc=*/NoLoc,
2949 /*ESpecRange=*/SourceRange(),
2950 /*Exceptions=*/nullptr,
2951 /*ExceptionRanges=*/nullptr,
2952 /*NumExceptions=*/0,
2953 /*NoexceptExpr=*/nullptr,
2954 /*ExceptionSpecTokens=*/nullptr,
2955 /*DeclsInPrototype=*/None,
2960 MaybeParseGNUAttributes(ParamInfo);
2962 // Inform sema that we are starting a block.
2963 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2967 ExprResult Result(true);
2968 if (!Tok.is(tok::l_brace)) {
2969 // Saw something like: ^expr
2970 Diag(Tok, diag::err_expected_expression);
2971 Actions.ActOnBlockError(CaretLoc, getCurScope());
2975 StmtResult Stmt(ParseCompoundStatementBody());
2977 if (!Stmt.isInvalid())
2978 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2980 Actions.ActOnBlockError(CaretLoc, getCurScope());
2984 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2988 ExprResult Parser::ParseObjCBoolLiteral() {
2989 tok::TokenKind Kind = Tok.getKind();
2990 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
2993 /// Validate availability spec list, emitting diagnostics if necessary. Returns
2994 /// true if invalid.
2995 static bool CheckAvailabilitySpecList(Parser &P,
2996 ArrayRef<AvailabilitySpec> AvailSpecs) {
2997 llvm::SmallSet<StringRef, 4> Platforms;
2998 bool HasOtherPlatformSpec = false;
3000 for (const auto &Spec : AvailSpecs) {
3001 if (Spec.isOtherPlatformSpec()) {
3002 if (HasOtherPlatformSpec) {
3003 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3007 HasOtherPlatformSpec = true;
3011 bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3013 // Rule out multiple version specs referring to the same platform.
3014 // For example, we emit an error for:
3015 // @available(macos 10.10, macos 10.11, *)
3016 StringRef Platform = Spec.getPlatform();
3017 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3018 << Spec.getEndLoc() << Platform;
3023 if (!HasOtherPlatformSpec) {
3024 SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3025 P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3026 << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3033 /// Parse availability query specification.
3035 /// availability-spec:
3037 /// identifier version-tuple
3038 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3039 if (Tok.is(tok::star)) {
3040 return AvailabilitySpec(ConsumeToken());
3042 // Parse the platform name.
3043 if (Tok.is(tok::code_completion)) {
3044 Actions.CodeCompleteAvailabilityPlatformName();
3048 if (Tok.isNot(tok::identifier)) {
3049 Diag(Tok, diag::err_avail_query_expected_platform_name);
3053 IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3054 SourceRange VersionRange;
3055 VersionTuple Version = ParseVersionTuple(VersionRange);
3057 if (Version.empty())
3060 StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3061 StringRef Platform =
3062 AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3064 if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3065 Diag(PlatformIdentifier->Loc,
3066 diag::err_avail_query_unrecognized_platform_name)
3071 return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3072 VersionRange.getEnd());
3076 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3077 assert(Tok.is(tok::kw___builtin_available) ||
3078 Tok.isObjCAtKeyword(tok::objc_available));
3080 // Eat the available or __builtin_available.
3083 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3084 if (Parens.expectAndConsume())
3087 SmallVector<AvailabilitySpec, 4> AvailSpecs;
3088 bool HasError = false;
3090 Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3094 AvailSpecs.push_back(*Spec);
3096 if (!TryConsumeToken(tok::comma))
3101 SkipUntil(tok::r_paren, StopAtSemi);
3105 CheckAvailabilitySpecList(*this, AvailSpecs);
3107 if (Parens.consumeClose())
3110 return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3111 Parens.getCloseLocation());