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 /// 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 /// 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 /// 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 /// 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 ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
221 EnterExpressionEvaluationContext ConstantEvaluated(
222 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
223 ExprResult LHS(ParseCastExpression(false, false, NotTypeCast));
224 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
225 return Actions.ActOnCaseExpr(CaseLoc, Res);
228 /// Parse a constraint-expression.
231 /// constraint-expression: [Concepts TS temp.constr.decl p1]
232 /// logical-or-expression
234 ExprResult Parser::ParseConstraintExpression() {
235 // FIXME: this may erroneously consume a function-body as the braced
236 // initializer list of a compound literal
238 // FIXME: this may erroneously consume a parenthesized rvalue reference
239 // declarator as a parenthesized address-of-label expression
240 ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
241 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
246 bool Parser::isNotExpressionStart() {
247 tok::TokenKind K = Tok.getKind();
248 if (K == tok::l_brace || K == tok::r_brace ||
249 K == tok::kw_for || K == tok::kw_while ||
250 K == tok::kw_if || K == tok::kw_else ||
251 K == tok::kw_goto || K == tok::kw_try)
253 // If this is a decl-specifier, we can't be at the start of an expression.
254 return isKnownToBeDeclarationSpecifier();
257 bool Parser::isFoldOperator(prec::Level Level) const {
258 return Level > prec::Unknown && Level != prec::Conditional &&
259 Level != prec::Spaceship;
262 bool Parser::isFoldOperator(tok::TokenKind Kind) const {
263 return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
266 /// Parse a binary expression that starts with \p LHS and has a
267 /// precedence of at least \p MinPrec.
269 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
270 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
271 GreaterThanIsOperator,
272 getLangOpts().CPlusPlus11);
273 SourceLocation ColonLoc;
276 // If this token has a lower precedence than we are allowed to parse (e.g.
277 // because we are called recursively, or because the token is not a binop),
279 if (NextTokPrec < MinPrec)
282 // Consume the operator, saving the operator token for error reporting.
286 if (OpToken.is(tok::caretcaret)) {
287 return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
290 // If we're potentially in a template-id, we may now be able to determine
291 // whether we're actually in one or not.
292 if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
293 tok::greatergreatergreater) &&
294 checkPotentialAngleBracketDelimiter(OpToken))
297 // Bail out when encountering a comma followed by a token which can't
298 // possibly be the start of an expression. For instance:
299 // int f() { return 1, }
300 // We can't do this before consuming the comma, because
301 // isNotExpressionStart() looks at the token stream.
302 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
308 // If the next token is an ellipsis, then this is a fold-expression. Leave
309 // it alone so we can handle it in the paren expression.
310 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
311 // FIXME: We can't check this via lookahead before we consume the token
312 // because that tickles a lexer bug.
318 // Special case handling for the ternary operator.
319 ExprResult TernaryMiddle(true);
320 if (NextTokPrec == prec::Conditional) {
321 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
322 // Parse a braced-init-list here for error recovery purposes.
323 SourceLocation BraceLoc = Tok.getLocation();
324 TernaryMiddle = ParseBraceInitializer();
325 if (!TernaryMiddle.isInvalid()) {
326 Diag(BraceLoc, diag::err_init_list_bin_op)
327 << /*RHS*/ 1 << PP.getSpelling(OpToken)
328 << Actions.getExprRange(TernaryMiddle.get());
329 TernaryMiddle = ExprError();
331 } else if (Tok.isNot(tok::colon)) {
332 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
333 ColonProtectionRAIIObject X(*this);
335 // Handle this production specially:
336 // logical-OR-expression '?' expression ':' conditional-expression
337 // In particular, the RHS of the '?' is 'expression', not
338 // 'logical-OR-expression' as we might expect.
339 TernaryMiddle = ParseExpression();
341 // Special case handling of "X ? Y : Z" where Y is empty:
342 // logical-OR-expression '?' ':' conditional-expression [GNU]
343 TernaryMiddle = nullptr;
344 Diag(Tok, diag::ext_gnu_conditional_expr);
347 if (TernaryMiddle.isInvalid()) {
348 Actions.CorrectDelayedTyposInExpr(LHS);
350 TernaryMiddle = nullptr;
353 if (!TryConsumeToken(tok::colon, ColonLoc)) {
354 // Otherwise, we're missing a ':'. Assume that this was a typo that
355 // the user forgot. If we're not in a macro expansion, we can suggest
356 // a fixit hint. If there were two spaces before the current token,
357 // suggest inserting the colon in between them, otherwise insert ": ".
358 SourceLocation FILoc = Tok.getLocation();
359 const char *FIText = ": ";
360 const SourceManager &SM = PP.getSourceManager();
361 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
362 assert(FILoc.isFileID());
363 bool IsInvalid = false;
364 const char *SourcePtr =
365 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
366 if (!IsInvalid && *SourcePtr == ' ') {
368 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
369 if (!IsInvalid && *SourcePtr == ' ') {
370 FILoc = FILoc.getLocWithOffset(-1);
376 Diag(Tok, diag::err_expected)
377 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
378 Diag(OpToken, diag::note_matching) << tok::question;
379 ColonLoc = Tok.getLocation();
383 // Code completion for the right-hand side of an assignment expression
384 // goes through a special hook that takes the left-hand side into account.
385 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
386 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
391 // Parse another leaf here for the RHS of the operator.
392 // ParseCastExpression works here because all RHS expressions in C have it
393 // as a prefix, at least. However, in C++, an assignment-expression could
394 // be a throw-expression, which is not a valid cast-expression.
395 // Therefore we need some special-casing here.
396 // Also note that the third operand of the conditional operator is
397 // an assignment-expression in C++, and in C++11, we can have a
398 // braced-init-list on the RHS of an assignment. For better diagnostics,
399 // parse as if we were allowed braced-init-lists everywhere, and check that
400 // they only appear on the RHS of assignments later.
402 bool RHSIsInitList = false;
403 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
404 RHS = ParseBraceInitializer();
405 RHSIsInitList = true;
406 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
407 RHS = ParseAssignmentExpression();
409 RHS = ParseCastExpression(false);
411 if (RHS.isInvalid()) {
412 // FIXME: Errors generated by the delayed typo correction should be
413 // printed before errors from parsing the RHS, not after.
414 Actions.CorrectDelayedTyposInExpr(LHS);
415 if (TernaryMiddle.isUsable())
416 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
420 // Remember the precedence of this operator and get the precedence of the
421 // operator immediately to the right of the RHS.
422 prec::Level ThisPrec = NextTokPrec;
423 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
424 getLangOpts().CPlusPlus11);
426 // Assignment and conditional expressions are right-associative.
427 bool isRightAssoc = ThisPrec == prec::Conditional ||
428 ThisPrec == prec::Assignment;
430 // Get the precedence of the operator to the right of the RHS. If it binds
431 // more tightly with RHS than we do, evaluate it completely first.
432 if (ThisPrec < NextTokPrec ||
433 (ThisPrec == NextTokPrec && isRightAssoc)) {
434 if (!RHS.isInvalid() && RHSIsInitList) {
435 Diag(Tok, diag::err_init_list_bin_op)
436 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
439 // If this is left-associative, only parse things on the RHS that bind
440 // more tightly than the current operator. If it is left-associative, it
441 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
442 // A=(B=(C=D)), where each paren is a level of recursion here.
443 // The function takes ownership of the RHS.
444 RHS = ParseRHSOfBinaryExpression(RHS,
445 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
446 RHSIsInitList = false;
448 if (RHS.isInvalid()) {
449 // FIXME: Errors generated by the delayed typo correction should be
450 // printed before errors from ParseRHSOfBinaryExpression, not after.
451 Actions.CorrectDelayedTyposInExpr(LHS);
452 if (TernaryMiddle.isUsable())
453 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
457 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
458 getLangOpts().CPlusPlus11);
461 if (!RHS.isInvalid() && RHSIsInitList) {
462 if (ThisPrec == prec::Assignment) {
463 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
464 << Actions.getExprRange(RHS.get());
465 } else if (ColonLoc.isValid()) {
466 Diag(ColonLoc, diag::err_init_list_bin_op)
468 << Actions.getExprRange(RHS.get());
471 Diag(OpToken, diag::err_init_list_bin_op)
472 << /*RHS*/1 << PP.getSpelling(OpToken)
473 << Actions.getExprRange(RHS.get());
478 ExprResult OrigLHS = LHS;
479 if (!LHS.isInvalid()) {
480 // Combine the LHS and RHS into the LHS (e.g. build AST).
481 if (TernaryMiddle.isInvalid()) {
482 // If we're using '>>' as an operator within a template
483 // argument list (in C++98), suggest the addition of
484 // parentheses so that the code remains well-formed in C++0x.
485 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
486 SuggestParentheses(OpToken.getLocation(),
487 diag::warn_cxx11_right_shift_in_template_arg,
488 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
489 Actions.getExprRange(RHS.get()).getEnd()));
491 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
492 OpToken.getKind(), LHS.get(), RHS.get());
495 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
496 LHS.get(), TernaryMiddle.get(),
499 // In this case, ActOnBinOp or ActOnConditionalOp performed the
500 // CorrectDelayedTyposInExpr check.
501 if (!getLangOpts().CPlusPlus)
505 // Ensure potential typos aren't left undiagnosed.
506 if (LHS.isInvalid()) {
507 Actions.CorrectDelayedTyposInExpr(OrigLHS);
508 Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
509 Actions.CorrectDelayedTyposInExpr(RHS);
514 /// Parse a cast-expression, or, if \p isUnaryExpression is true,
515 /// parse a unary-expression.
517 /// \p isAddressOfOperand exists because an id-expression that is the
518 /// operand of address-of gets special treatment due to member pointers.
520 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
521 bool isAddressOfOperand,
522 TypeCastState isTypeCast,
523 bool isVectorLiteral) {
525 ExprResult Res = ParseCastExpression(isUnaryExpression,
531 Diag(Tok, diag::err_expected_expression);
536 class CastExpressionIdValidator : public CorrectionCandidateCallback {
538 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
539 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
540 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
543 bool ValidateCandidate(const TypoCorrection &candidate) override {
544 NamedDecl *ND = candidate.getCorrectionDecl();
546 return candidate.isKeyword();
548 if (isa<TypeDecl>(ND))
549 return WantTypeSpecifiers;
551 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
554 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
557 for (auto *C : candidate) {
558 NamedDecl *ND = C->getUnderlyingDecl();
559 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
571 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
572 /// a unary-expression.
574 /// \p isAddressOfOperand exists because an id-expression that is the operand
575 /// of address-of gets special treatment due to member pointers. NotCastExpr
576 /// is set to true if the token is not the start of a cast-expression, and no
577 /// diagnostic is emitted in this case and no tokens are consumed.
580 /// cast-expression: [C99 6.5.4]
582 /// '(' type-name ')' cast-expression
584 /// unary-expression: [C99 6.5.3]
585 /// postfix-expression
586 /// '++' unary-expression
587 /// '--' unary-expression
588 /// [Coro] 'co_await' cast-expression
589 /// unary-operator cast-expression
590 /// 'sizeof' unary-expression
591 /// 'sizeof' '(' type-name ')'
592 /// [C++11] 'sizeof' '...' '(' identifier ')'
593 /// [GNU] '__alignof' unary-expression
594 /// [GNU] '__alignof' '(' type-name ')'
595 /// [C11] '_Alignof' '(' type-name ')'
596 /// [C++11] 'alignof' '(' type-id ')'
597 /// [GNU] '&&' identifier
598 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
599 /// [C++] new-expression
600 /// [C++] delete-expression
602 /// unary-operator: one of
603 /// '&' '*' '+' '-' '~' '!'
604 /// [GNU] '__extension__' '__real' '__imag'
606 /// primary-expression: [C99 6.5.1]
608 /// [C++] id-expression
611 /// [C++] boolean-literal [C++ 2.13.5]
612 /// [C++11] 'nullptr' [C++11 2.14.7]
613 /// [C++11] user-defined-literal
614 /// '(' expression ')'
615 /// [C11] generic-selection
616 /// '__func__' [C99 6.4.2.2]
617 /// [GNU] '__FUNCTION__'
618 /// [MS] '__FUNCDNAME__'
619 /// [MS] 'L__FUNCTION__'
620 /// [MS] '__FUNCSIG__'
621 /// [MS] 'L__FUNCSIG__'
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
793 // We only parsed a fold-expression. There might be postfix-expr pieces
794 // afterwards; parse them now.
801 // primary-expression
802 case tok::numeric_constant:
803 // constant: integer-constant
804 // constant: floating-constant
806 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
812 Res = ParseCXXBoolLiteral();
815 case tok::kw___objc_yes:
816 case tok::kw___objc_no:
817 return ParseObjCBoolLiteral();
819 case tok::kw_nullptr:
820 Diag(Tok, diag::warn_cxx98_compat_nullptr);
821 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
823 case tok::annot_primary_expr:
824 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
825 Res = getExprAnnotation(Tok);
826 ConsumeAnnotationToken();
827 if (!Res.isInvalid() && Tok.is(tok::less))
828 checkPotentialAngleBracket(Res);
831 case tok::kw___super:
832 case tok::kw_decltype:
833 // Annotate the token and tail recurse.
834 if (TryAnnotateTypeOrScopeToken())
836 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
837 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
839 case tok::identifier: { // primary-expression: identifier
840 // unqualified-id: identifier
841 // constant: enumeration-constant
842 // Turn a potentially qualified name into a annot_typename or
843 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
844 if (getLangOpts().CPlusPlus) {
845 // Avoid the unnecessary parse-time lookup in the common case
846 // where the syntax forbids a type.
847 const Token &Next = NextToken();
849 // If this identifier was reverted from a token ID, and the next token
850 // is a parenthesis, this is likely to be a use of a type trait. Check
852 if (Next.is(tok::l_paren) &&
853 Tok.is(tok::identifier) &&
854 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
855 IdentifierInfo *II = Tok.getIdentifierInfo();
856 // Build up the mapping of revertible type traits, for future use.
857 if (RevertibleTypeTraits.empty()) {
858 #define RTT_JOIN(X,Y) X##Y
859 #define REVERTIBLE_TYPE_TRAIT(Name) \
860 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
861 = RTT_JOIN(tok::kw_,Name)
863 REVERTIBLE_TYPE_TRAIT(__is_abstract);
864 REVERTIBLE_TYPE_TRAIT(__is_aggregate);
865 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
866 REVERTIBLE_TYPE_TRAIT(__is_array);
867 REVERTIBLE_TYPE_TRAIT(__is_assignable);
868 REVERTIBLE_TYPE_TRAIT(__is_base_of);
869 REVERTIBLE_TYPE_TRAIT(__is_class);
870 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
871 REVERTIBLE_TYPE_TRAIT(__is_compound);
872 REVERTIBLE_TYPE_TRAIT(__is_const);
873 REVERTIBLE_TYPE_TRAIT(__is_constructible);
874 REVERTIBLE_TYPE_TRAIT(__is_convertible);
875 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
876 REVERTIBLE_TYPE_TRAIT(__is_destructible);
877 REVERTIBLE_TYPE_TRAIT(__is_empty);
878 REVERTIBLE_TYPE_TRAIT(__is_enum);
879 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
880 REVERTIBLE_TYPE_TRAIT(__is_final);
881 REVERTIBLE_TYPE_TRAIT(__is_function);
882 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
883 REVERTIBLE_TYPE_TRAIT(__is_integral);
884 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
885 REVERTIBLE_TYPE_TRAIT(__is_literal);
886 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
887 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
888 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
889 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
890 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
891 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
892 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
893 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
894 REVERTIBLE_TYPE_TRAIT(__is_object);
895 REVERTIBLE_TYPE_TRAIT(__is_pod);
896 REVERTIBLE_TYPE_TRAIT(__is_pointer);
897 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
898 REVERTIBLE_TYPE_TRAIT(__is_reference);
899 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
900 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
901 REVERTIBLE_TYPE_TRAIT(__is_same);
902 REVERTIBLE_TYPE_TRAIT(__is_scalar);
903 REVERTIBLE_TYPE_TRAIT(__is_sealed);
904 REVERTIBLE_TYPE_TRAIT(__is_signed);
905 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
906 REVERTIBLE_TYPE_TRAIT(__is_trivial);
907 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
908 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
909 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
910 REVERTIBLE_TYPE_TRAIT(__is_union);
911 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
912 REVERTIBLE_TYPE_TRAIT(__is_void);
913 REVERTIBLE_TYPE_TRAIT(__is_volatile);
914 #undef REVERTIBLE_TYPE_TRAIT
918 // If we find that this is in fact the name of a type trait,
919 // update the token kind in place and parse again to treat it as
920 // the appropriate kind of type trait.
921 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
922 = RevertibleTypeTraits.find(II);
923 if (Known != RevertibleTypeTraits.end()) {
924 Tok.setKind(Known->second);
925 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
926 NotCastExpr, isTypeCast);
930 if ((!ColonIsSacred && Next.is(tok::colon)) ||
931 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
933 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
934 if (TryAnnotateTypeOrScopeToken())
936 if (!Tok.is(tok::identifier))
937 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
941 // Consume the identifier so that we can see if it is followed by a '(' or
943 IdentifierInfo &II = *Tok.getIdentifierInfo();
944 SourceLocation ILoc = ConsumeToken();
946 // Support 'Class.property' and 'super.property' notation.
947 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
948 (Actions.getTypeName(II, ILoc, getCurScope()) ||
949 // Allow the base to be 'super' if in an objc-method.
950 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
953 if (Tok.is(tok::code_completion) && &II != Ident_super) {
954 Actions.CodeCompleteObjCClassPropertyRefExpr(
955 getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
959 // Allow either an identifier or the keyword 'class' (in C++).
960 if (Tok.isNot(tok::identifier) &&
961 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
962 Diag(Tok, diag::err_expected_property_name);
965 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
966 SourceLocation PropertyLoc = ConsumeToken();
968 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
973 // In an Objective-C method, if we have "super" followed by an identifier,
974 // the token sequence is ill-formed. However, if there's a ':' or ']' after
975 // that identifier, this is probably a message send with a missing open
976 // bracket. Treat it as such.
977 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
978 getCurScope()->isInObjcMethodScope() &&
979 ((Tok.is(tok::identifier) &&
980 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
981 Tok.is(tok::code_completion))) {
982 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
987 // If we have an Objective-C class name followed by an identifier
988 // and either ':' or ']', this is an Objective-C class message
989 // send that's missing the opening '['. Recovery
990 // appropriately. Also take this path if we're performing code
991 // completion after an Objective-C class name.
992 if (getLangOpts().ObjC1 &&
993 ((Tok.is(tok::identifier) && !InMessageExpression) ||
994 Tok.is(tok::code_completion))) {
995 const Token& Next = NextToken();
996 if (Tok.is(tok::code_completion) ||
997 Next.is(tok::colon) || Next.is(tok::r_square))
998 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
999 if (Typ.get()->isObjCObjectOrInterfaceType()) {
1000 // Fake up a Declarator to use with ActOnTypeName.
1001 DeclSpec DS(AttrFactory);
1002 DS.SetRangeStart(ILoc);
1003 DS.SetRangeEnd(ILoc);
1004 const char *PrevSpec = nullptr;
1006 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1007 Actions.getASTContext().getPrintingPolicy());
1009 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1010 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1015 Res = ParseObjCMessageExpressionBody(SourceLocation(),
1022 // Make sure to pass down the right value for isAddressOfOperand.
1023 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
1024 isAddressOfOperand = false;
1026 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1027 // need to know whether or not this identifier is a function designator or
1030 CXXScopeSpec ScopeSpec;
1031 SourceLocation TemplateKWLoc;
1033 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
1034 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
1035 Validator->IsAddressOfOperand = isAddressOfOperand;
1036 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1037 Validator->WantExpressionKeywords = false;
1038 Validator->WantRemainingKeywords = false;
1040 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
1042 Name.setIdentifier(&II, ILoc);
1043 Res = Actions.ActOnIdExpression(
1044 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1045 isAddressOfOperand, std::move(Validator),
1046 /*IsInlineAsmIdentifier=*/false,
1047 Tok.is(tok::r_paren) ? nullptr : &Replacement);
1048 if (!Res.isInvalid() && Res.isUnset()) {
1049 UnconsumeToken(Replacement);
1050 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1051 NotCastExpr, isTypeCast);
1053 if (!Res.isInvalid() && Tok.is(tok::less))
1054 checkPotentialAngleBracket(Res);
1057 case tok::char_constant: // constant: character-constant
1058 case tok::wide_char_constant:
1059 case tok::utf8_char_constant:
1060 case tok::utf16_char_constant:
1061 case tok::utf32_char_constant:
1062 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1065 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
1066 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
1067 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
1068 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
1069 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
1070 case tok::kw_L__FUNCSIG__: // primary-expression: L__FUNCSIG__ [MS]
1071 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1072 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1075 case tok::string_literal: // primary-expression: string-literal
1076 case tok::wide_string_literal:
1077 case tok::utf8_string_literal:
1078 case tok::utf16_string_literal:
1079 case tok::utf32_string_literal:
1080 Res = ParseStringLiteralExpression(true);
1082 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1083 Res = ParseGenericSelectionExpression();
1085 case tok::kw___builtin_available:
1086 return ParseAvailabilityCheckExpr(Tok.getLocation());
1087 case tok::kw___builtin_va_arg:
1088 case tok::kw___builtin_offsetof:
1089 case tok::kw___builtin_choose_expr:
1090 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1091 case tok::kw___builtin_convertvector:
1092 return ParseBuiltinPrimaryExpression();
1093 case tok::kw___null:
1094 return Actions.ActOnGNUNullExpr(ConsumeToken());
1096 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1097 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1098 // C++ [expr.unary] has:
1099 // unary-expression:
1100 // ++ cast-expression
1101 // -- cast-expression
1102 Token SavedTok = Tok;
1104 // One special case is implicitly handled here: if the preceding tokens are
1105 // an ambiguous cast expression, such as "(T())++", then we recurse to
1106 // determine whether the '++' is prefix or postfix.
1107 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1108 /*isAddressOfOperand*/false, NotCastExpr,
1111 // If we return with NotCastExpr = true, we must not consume any tokens,
1112 // so put the token back where we found it.
1113 assert(Res.isInvalid());
1114 UnconsumeToken(SavedTok);
1117 if (!Res.isInvalid())
1118 Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1119 SavedKind, Res.get());
1122 case tok::amp: { // unary-expression: '&' cast-expression
1123 // Special treatment because of member pointers
1124 SourceLocation SavedLoc = ConsumeToken();
1125 Res = ParseCastExpression(false, true);
1126 if (!Res.isInvalid())
1127 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1131 case tok::star: // unary-expression: '*' cast-expression
1132 case tok::plus: // unary-expression: '+' cast-expression
1133 case tok::minus: // unary-expression: '-' cast-expression
1134 case tok::tilde: // unary-expression: '~' cast-expression
1135 case tok::exclaim: // unary-expression: '!' cast-expression
1136 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1137 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1138 SourceLocation SavedLoc = ConsumeToken();
1139 Res = ParseCastExpression(false);
1140 if (!Res.isInvalid())
1141 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1145 case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1146 SourceLocation CoawaitLoc = ConsumeToken();
1147 Res = ParseCastExpression(false);
1148 if (!Res.isInvalid())
1149 Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1153 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1154 // __extension__ silences extension warnings in the subexpression.
1155 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1156 SourceLocation SavedLoc = ConsumeToken();
1157 Res = ParseCastExpression(false);
1158 if (!Res.isInvalid())
1159 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1162 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1163 if (!getLangOpts().C11)
1164 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1166 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1167 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1168 // unary-expression: '__alignof' '(' type-name ')'
1169 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1170 // unary-expression: 'sizeof' '(' type-name ')'
1171 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1172 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1173 case tok::kw___builtin_omp_required_simd_align:
1174 return ParseUnaryExprOrTypeTraitExpression();
1175 case tok::ampamp: { // unary-expression: '&&' identifier
1176 SourceLocation AmpAmpLoc = ConsumeToken();
1177 if (Tok.isNot(tok::identifier))
1178 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1180 if (getCurScope()->getFnParent() == nullptr)
1181 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1183 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1184 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1186 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1190 case tok::kw_const_cast:
1191 case tok::kw_dynamic_cast:
1192 case tok::kw_reinterpret_cast:
1193 case tok::kw_static_cast:
1194 Res = ParseCXXCasts();
1196 case tok::kw_typeid:
1197 Res = ParseCXXTypeid();
1199 case tok::kw___uuidof:
1200 Res = ParseCXXUuidof();
1203 Res = ParseCXXThis();
1206 case tok::annot_typename:
1207 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1208 ParsedType Type = getTypeAnnotation(Tok);
1210 // Fake up a Declarator to use with ActOnTypeName.
1211 DeclSpec DS(AttrFactory);
1212 DS.SetRangeStart(Tok.getLocation());
1213 DS.SetRangeEnd(Tok.getLastLoc());
1215 const char *PrevSpec = nullptr;
1217 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1218 PrevSpec, DiagID, Type,
1219 Actions.getASTContext().getPrintingPolicy());
1221 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1222 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1226 ConsumeAnnotationToken();
1227 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1233 case tok::annot_decltype:
1235 case tok::kw_wchar_t:
1236 case tok::kw_char8_t:
1237 case tok::kw_char16_t:
1238 case tok::kw_char32_t:
1243 case tok::kw___int64:
1244 case tok::kw___int128:
1245 case tok::kw_signed:
1246 case tok::kw_unsigned:
1249 case tok::kw_double:
1250 case tok::kw__Float16:
1251 case tok::kw___float128:
1253 case tok::kw_typename:
1254 case tok::kw_typeof:
1255 case tok::kw___vector:
1256 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1257 #include "clang/Basic/OpenCLImageTypes.def"
1259 if (!getLangOpts().CPlusPlus) {
1260 Diag(Tok, diag::err_expected_expression);
1264 if (SavedKind == tok::kw_typename) {
1265 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1266 // typename-specifier braced-init-list
1267 if (TryAnnotateTypeOrScopeToken())
1270 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1271 // We are trying to parse a simple-type-specifier but might not get such
1272 // a token after error recovery.
1276 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1277 // simple-type-specifier braced-init-list
1279 DeclSpec DS(AttrFactory);
1281 ParseCXXSimpleTypeSpecifier(DS);
1282 if (Tok.isNot(tok::l_paren) &&
1283 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1284 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1285 << DS.getSourceRange());
1287 if (Tok.is(tok::l_brace))
1288 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1290 Res = ParseCXXTypeConstructExpression(DS);
1294 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1295 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1296 // (We can end up in this situation after tentative parsing.)
1297 if (TryAnnotateTypeOrScopeToken())
1299 if (!Tok.is(tok::annot_cxxscope))
1300 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1301 NotCastExpr, isTypeCast);
1303 Token Next = NextToken();
1304 if (Next.is(tok::annot_template_id)) {
1305 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1306 if (TemplateId->Kind == TNK_Type_template) {
1307 // We have a qualified template-id that we know refers to a
1308 // type, translate it into a type and continue parsing as a
1311 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1312 /*EnteringContext=*/false);
1313 AnnotateTemplateIdTokenAsType();
1314 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1315 NotCastExpr, isTypeCast);
1319 // Parse as an id-expression.
1320 Res = ParseCXXIdExpression(isAddressOfOperand);
1324 case tok::annot_template_id: { // [C++] template-id
1325 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1326 if (TemplateId->Kind == TNK_Type_template) {
1327 // We have a template-id that we know refers to a type,
1328 // translate it into a type and continue parsing as a cast
1330 AnnotateTemplateIdTokenAsType();
1331 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1332 NotCastExpr, isTypeCast);
1335 // Fall through to treat the template-id as an id-expression.
1339 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1340 Res = ParseCXXIdExpression(isAddressOfOperand);
1343 case tok::coloncolon: {
1344 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1345 // annotates the token, tail recurse.
1346 if (TryAnnotateTypeOrScopeToken())
1348 if (!Tok.is(tok::coloncolon))
1349 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1351 // ::new -> [C++] new-expression
1352 // ::delete -> [C++] delete-expression
1353 SourceLocation CCLoc = ConsumeToken();
1354 if (Tok.is(tok::kw_new))
1355 return ParseCXXNewExpression(true, CCLoc);
1356 if (Tok.is(tok::kw_delete))
1357 return ParseCXXDeleteExpression(true, CCLoc);
1359 // This is not a type name or scope specifier, it is an invalid expression.
1360 Diag(CCLoc, diag::err_expected_expression);
1364 case tok::kw_new: // [C++] new-expression
1365 return ParseCXXNewExpression(false, Tok.getLocation());
1367 case tok::kw_delete: // [C++] delete-expression
1368 return ParseCXXDeleteExpression(false, Tok.getLocation());
1370 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1371 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1372 SourceLocation KeyLoc = ConsumeToken();
1373 BalancedDelimiterTracker T(*this, tok::l_paren);
1375 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1377 // C++11 [expr.unary.noexcept]p1:
1378 // The noexcept operator determines whether the evaluation of its operand,
1379 // which is an unevaluated operand, can throw an exception.
1380 EnterExpressionEvaluationContext Unevaluated(
1381 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1382 ExprResult Result = ParseExpression();
1386 if (!Result.isInvalid())
1387 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1388 Result.get(), T.getCloseLocation());
1392 #define TYPE_TRAIT(N,Spelling,K) \
1393 case tok::kw_##Spelling:
1394 #include "clang/Basic/TokenKinds.def"
1395 return ParseTypeTrait();
1397 case tok::kw___array_rank:
1398 case tok::kw___array_extent:
1399 return ParseArrayTypeTrait();
1401 case tok::kw___is_lvalue_expr:
1402 case tok::kw___is_rvalue_expr:
1403 return ParseExpressionTrait();
1406 SourceLocation AtLoc = ConsumeToken();
1407 return ParseObjCAtExpression(AtLoc);
1410 Res = ParseBlockLiteralExpression();
1412 case tok::code_completion: {
1413 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1418 if (getLangOpts().CPlusPlus11) {
1419 if (getLangOpts().ObjC1) {
1420 // C++11 lambda expressions and Objective-C message sends both start with a
1421 // square bracket. There are three possibilities here:
1422 // we have a valid lambda expression, we have an invalid lambda
1423 // expression, or we have something that doesn't appear to be a lambda.
1424 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1425 Res = TryParseLambdaExpression();
1426 if (!Res.isInvalid() && !Res.get())
1427 Res = ParseObjCMessageExpression();
1430 Res = ParseLambdaExpression();
1433 if (getLangOpts().ObjC1) {
1434 Res = ParseObjCMessageExpression();
1443 // Check to see whether Res is a function designator only. If it is and we
1444 // are compiling for OpenCL, we need to return an error as this implies
1445 // that the address of the function is being taken, which is illegal in CL.
1447 // These can be followed by postfix-expr pieces.
1448 Res = ParsePostfixExpressionSuffix(Res);
1449 if (getLangOpts().OpenCL)
1450 if (Expr *PostfixExpr = Res.get()) {
1451 QualType Ty = PostfixExpr->getType();
1452 if (!Ty.isNull() && Ty->isFunctionType()) {
1453 Diag(PostfixExpr->getExprLoc(),
1454 diag::err_opencl_taking_function_address_parser);
1462 /// Once the leading part of a postfix-expression is parsed, this
1463 /// method parses any suffixes that apply.
1466 /// postfix-expression: [C99 6.5.2]
1467 /// primary-expression
1468 /// postfix-expression '[' expression ']'
1469 /// postfix-expression '[' braced-init-list ']'
1470 /// postfix-expression '(' argument-expression-list[opt] ')'
1471 /// postfix-expression '.' identifier
1472 /// postfix-expression '->' identifier
1473 /// postfix-expression '++'
1474 /// postfix-expression '--'
1475 /// '(' type-name ')' '{' initializer-list '}'
1476 /// '(' type-name ')' '{' initializer-list ',' '}'
1478 /// argument-expression-list: [C99 6.5.2]
1479 /// argument-expression ...[opt]
1480 /// argument-expression-list ',' assignment-expression ...[opt]
1483 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1484 // Now that the primary-expression piece of the postfix-expression has been
1485 // parsed, see if there are any postfix-expression pieces here.
1488 switch (Tok.getKind()) {
1489 case tok::code_completion:
1490 if (InMessageExpression)
1493 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1497 case tok::identifier:
1498 // If we see identifier: after an expression, and we're not already in a
1499 // message send, then this is probably a message send with a missing
1500 // opening bracket '['.
1501 if (getLangOpts().ObjC1 && !InMessageExpression &&
1502 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1503 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1504 nullptr, LHS.get());
1507 // Fall through; this isn't a message send.
1510 default: // Not a postfix-expression suffix.
1512 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1513 // If we have a array postfix expression that starts on a new line and
1514 // Objective-C is enabled, it is highly likely that the user forgot a
1515 // semicolon after the base expression and that the array postfix-expr is
1516 // actually another message send. In this case, do some look-ahead to see
1517 // if the contents of the square brackets are obviously not a valid
1518 // expression and recover by pretending there is no suffix.
1519 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1520 isSimpleObjCMessageExpression())
1523 // Reject array indices starting with a lambda-expression. '[[' is
1524 // reserved for attributes.
1525 if (CheckProhibitedCXX11Attribute()) {
1526 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1530 BalancedDelimiterTracker T(*this, tok::l_square);
1532 Loc = T.getOpenLocation();
1533 ExprResult Idx, Length;
1534 SourceLocation ColonLoc;
1535 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1536 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1537 Idx = ParseBraceInitializer();
1538 } else if (getLangOpts().OpenMP) {
1539 ColonProtectionRAIIObject RAII(*this);
1540 // Parse [: or [ expr or [ expr :
1541 if (!Tok.is(tok::colon)) {
1543 Idx = ParseExpression();
1545 if (Tok.is(tok::colon)) {
1547 ColonLoc = ConsumeToken();
1548 if (Tok.isNot(tok::r_square))
1549 Length = ParseExpression();
1552 Idx = ParseExpression();
1554 SourceLocation RLoc = Tok.getLocation();
1556 ExprResult OrigLHS = LHS;
1557 if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1558 Tok.is(tok::r_square)) {
1559 if (ColonLoc.isValid()) {
1560 LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1561 ColonLoc, Length.get(), RLoc);
1563 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1569 if (LHS.isInvalid()) {
1570 (void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
1571 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1572 (void)Actions.CorrectDelayedTyposInExpr(Length);
1582 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1583 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1584 // '(' argument-expression-list[opt] ')'
1585 tok::TokenKind OpKind = Tok.getKind();
1586 InMessageExpressionRAIIObject InMessage(*this, false);
1588 Expr *ExecConfig = nullptr;
1590 BalancedDelimiterTracker PT(*this, tok::l_paren);
1592 if (OpKind == tok::lesslessless) {
1593 ExprVector ExecConfigExprs;
1594 CommaLocsTy ExecConfigCommaLocs;
1595 SourceLocation OpenLoc = ConsumeToken();
1597 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1598 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1602 SourceLocation CloseLoc;
1603 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1604 } else if (LHS.isInvalid()) {
1605 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1607 // There was an error closing the brackets
1608 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1609 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1610 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1614 if (!LHS.isInvalid()) {
1615 if (ExpectAndConsume(tok::l_paren))
1618 Loc = PrevTokLocation;
1621 if (!LHS.isInvalid()) {
1622 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1626 if (ECResult.isInvalid())
1629 ExecConfig = ECResult.get();
1633 Loc = PT.getOpenLocation();
1636 ExprVector ArgExprs;
1637 CommaLocsTy CommaLocs;
1639 if (Tok.is(tok::code_completion)) {
1640 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1645 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1646 if (Tok.isNot(tok::r_paren)) {
1647 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1648 Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1650 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1652 } else if (LHS.isInvalid()) {
1653 for (auto &E : ArgExprs)
1654 Actions.CorrectDelayedTyposInExpr(E);
1660 if (LHS.isInvalid()) {
1661 SkipUntil(tok::r_paren, StopAtSemi);
1662 } else if (Tok.isNot(tok::r_paren)) {
1663 bool HadDelayedTypo = false;
1664 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1665 HadDelayedTypo = true;
1666 for (auto &E : ArgExprs)
1667 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1668 HadDelayedTypo = true;
1669 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1670 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1671 // the unmatched l_paren.
1673 SkipUntil(tok::r_paren, StopAtSemi);
1678 assert((ArgExprs.size() == 0 ||
1679 ArgExprs.size()-1 == CommaLocs.size())&&
1680 "Unexpected number of commas!");
1681 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1682 ArgExprs, Tok.getLocation(),
1691 // postfix-expression: p-e '->' template[opt] id-expression
1692 // postfix-expression: p-e '.' template[opt] id-expression
1693 tok::TokenKind OpKind = Tok.getKind();
1694 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1697 ParsedType ObjectType;
1698 bool MayBePseudoDestructor = false;
1699 Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr;
1701 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1702 Expr *Base = OrigLHS;
1703 const Type* BaseType = Base->getType().getTypePtrOrNull();
1704 if (BaseType && Tok.is(tok::l_paren) &&
1705 (BaseType->isFunctionType() ||
1706 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1707 Diag(OpLoc, diag::err_function_is_not_record)
1708 << OpKind << Base->getSourceRange()
1709 << FixItHint::CreateRemoval(OpLoc);
1710 return ParsePostfixExpressionSuffix(Base);
1713 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1714 OpLoc, OpKind, ObjectType,
1715 MayBePseudoDestructor);
1716 if (LHS.isInvalid())
1719 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1720 /*EnteringContext=*/false,
1721 &MayBePseudoDestructor);
1722 if (SS.isNotEmpty())
1723 ObjectType = nullptr;
1726 if (Tok.is(tok::code_completion)) {
1727 tok::TokenKind CorrectedOpKind =
1728 OpKind == tok::arrow ? tok::period : tok::arrow;
1729 ExprResult CorrectedLHS(/*IsInvalid=*/true);
1730 if (getLangOpts().CPlusPlus && OrigLHS) {
1731 const bool DiagsAreSuppressed = Diags.getSuppressAllDiagnostics();
1732 Diags.setSuppressAllDiagnostics(true);
1733 CorrectedLHS = Actions.ActOnStartCXXMemberReference(
1734 getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
1735 MayBePseudoDestructor);
1736 Diags.setSuppressAllDiagnostics(DiagsAreSuppressed);
1739 Expr *Base = LHS.get();
1740 Expr *CorrectedBase = CorrectedLHS.get();
1742 // Code completion for a member access expression.
1743 Actions.CodeCompleteMemberReferenceExpr(
1744 getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
1745 Base && ExprStatementTokLoc == Base->getLocStart());
1751 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1752 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1757 // Either the action has told us that this cannot be a
1758 // pseudo-destructor expression (based on the type of base
1759 // expression), or we didn't see a '~' in the right place. We
1760 // can still parse a destructor name here, but in that case it
1761 // names a real destructor.
1762 // Allow explicit constructor calls in Microsoft mode.
1763 // FIXME: Add support for explicit call of template constructor.
1764 SourceLocation TemplateKWLoc;
1766 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1767 Tok.is(tok::kw_class)) {
1769 // After a '.' in a member access expression, treat the keyword
1770 // 'class' as if it were an identifier.
1772 // This hack allows property access to the 'class' method because it is
1773 // such a common method name. For other C++ keywords that are
1774 // Objective-C method names, one must use the message send syntax.
1775 IdentifierInfo *Id = Tok.getIdentifierInfo();
1776 SourceLocation Loc = ConsumeToken();
1777 Name.setIdentifier(Id, Loc);
1778 } else if (ParseUnqualifiedId(SS,
1779 /*EnteringContext=*/false,
1780 /*AllowDestructorName=*/true,
1781 /*AllowConstructorName=*/
1782 getLangOpts().MicrosoftExt,
1783 /*AllowDeductionGuide=*/false,
1784 ObjectType, &TemplateKWLoc, Name)) {
1785 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1789 if (!LHS.isInvalid())
1790 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1791 OpKind, SS, TemplateKWLoc, Name,
1792 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1794 if (!LHS.isInvalid() && Tok.is(tok::less))
1795 checkPotentialAngleBracket(LHS);
1798 case tok::plusplus: // postfix-expression: postfix-expression '++'
1799 case tok::minusminus: // postfix-expression: postfix-expression '--'
1800 if (!LHS.isInvalid()) {
1801 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1802 Tok.getKind(), LHS.get());
1810 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1811 /// vec_step and we are at the start of an expression or a parenthesized
1812 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1813 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1816 /// unary-expression: [C99 6.5.3]
1817 /// 'sizeof' unary-expression
1818 /// 'sizeof' '(' type-name ')'
1819 /// [GNU] '__alignof' unary-expression
1820 /// [GNU] '__alignof' '(' type-name ')'
1821 /// [C11] '_Alignof' '(' type-name ')'
1822 /// [C++0x] 'alignof' '(' type-id ')'
1824 /// [GNU] typeof-specifier:
1825 /// typeof ( expressions )
1826 /// typeof ( type-name )
1827 /// [GNU/C++] typeof unary-expression
1829 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1830 /// vec_step ( expressions )
1831 /// vec_step ( type-name )
1834 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1837 SourceRange &CastRange) {
1839 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1840 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1841 tok::kw___builtin_omp_required_simd_align) &&
1842 "Not a typeof/sizeof/alignof/vec_step expression!");
1846 // If the operand doesn't start with an '(', it must be an expression.
1847 if (Tok.isNot(tok::l_paren)) {
1848 // If construct allows a form without parenthesis, user may forget to put
1849 // pathenthesis around type name.
1850 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1851 tok::kw__Alignof)) {
1852 if (isTypeIdUnambiguously()) {
1853 DeclSpec DS(AttrFactory);
1854 ParseSpecifierQualifierList(DS);
1855 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1856 ParseDeclarator(DeclaratorInfo);
1858 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1859 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1860 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1862 << FixItHint::CreateInsertion(LParenLoc, "(")
1863 << FixItHint::CreateInsertion(RParenLoc, ")");
1870 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1871 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1876 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1878 // If it starts with a '(', we know that it is either a parenthesized
1879 // type-name, or it is a unary-expression that starts with a compound
1880 // literal, or starts with a primary-expression that is a parenthesized
1882 ParenParseOption ExprType = CastExpr;
1883 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1885 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1886 false, CastTy, RParenLoc);
1887 CastRange = SourceRange(LParenLoc, RParenLoc);
1889 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1891 if (ExprType == CastExpr) {
1896 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1897 // GNU typeof in C requires the expression to be parenthesized. Not so for
1898 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1899 // the start of a unary-expression, but doesn't include any postfix
1900 // pieces. Parse these now if present.
1901 if (!Operand.isInvalid())
1902 Operand = ParsePostfixExpressionSuffix(Operand.get());
1906 // If we get here, the operand to the typeof/sizeof/alignof was an expression.
1912 /// Parse a sizeof or alignof expression.
1915 /// unary-expression: [C99 6.5.3]
1916 /// 'sizeof' unary-expression
1917 /// 'sizeof' '(' type-name ')'
1918 /// [C++11] 'sizeof' '...' '(' identifier ')'
1919 /// [GNU] '__alignof' unary-expression
1920 /// [GNU] '__alignof' '(' type-name ')'
1921 /// [C11] '_Alignof' '(' type-name ')'
1922 /// [C++11] 'alignof' '(' type-id ')'
1924 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1925 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1926 tok::kw__Alignof, tok::kw_vec_step,
1927 tok::kw___builtin_omp_required_simd_align) &&
1928 "Not a sizeof/alignof/vec_step expression!");
1932 // [C++11] 'sizeof' '...' '(' identifier ')'
1933 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1934 SourceLocation EllipsisLoc = ConsumeToken();
1935 SourceLocation LParenLoc, RParenLoc;
1936 IdentifierInfo *Name = nullptr;
1937 SourceLocation NameLoc;
1938 if (Tok.is(tok::l_paren)) {
1939 BalancedDelimiterTracker T(*this, tok::l_paren);
1941 LParenLoc = T.getOpenLocation();
1942 if (Tok.is(tok::identifier)) {
1943 Name = Tok.getIdentifierInfo();
1944 NameLoc = ConsumeToken();
1946 RParenLoc = T.getCloseLocation();
1947 if (RParenLoc.isInvalid())
1948 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1950 Diag(Tok, diag::err_expected_parameter_pack);
1951 SkipUntil(tok::r_paren, StopAtSemi);
1953 } else if (Tok.is(tok::identifier)) {
1954 Name = Tok.getIdentifierInfo();
1955 NameLoc = ConsumeToken();
1956 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1957 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1958 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1960 << FixItHint::CreateInsertion(LParenLoc, "(")
1961 << FixItHint::CreateInsertion(RParenLoc, ")");
1963 Diag(Tok, diag::err_sizeof_parameter_pack);
1969 EnterExpressionEvaluationContext Unevaluated(
1970 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1971 Sema::ReuseLambdaContextDecl);
1973 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1974 OpTok.getLocation(),
1979 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1980 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1982 EnterExpressionEvaluationContext Unevaluated(
1983 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1984 Sema::ReuseLambdaContextDecl);
1988 SourceRange CastRange;
1989 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1994 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1995 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1996 ExprKind = UETT_AlignOf;
1997 else if (OpTok.is(tok::kw_vec_step))
1998 ExprKind = UETT_VecStep;
1999 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2000 ExprKind = UETT_OpenMPRequiredSimdAlign;
2003 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2006 CastTy.getAsOpaquePtr(),
2009 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2010 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2012 // If we get here, the operand to the sizeof/alignof was an expression.
2013 if (!Operand.isInvalid())
2014 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2022 /// ParseBuiltinPrimaryExpression
2025 /// primary-expression: [C99 6.5.1]
2026 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2027 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2028 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2030 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2031 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
2033 /// [GNU] offsetof-member-designator:
2034 /// [GNU] identifier
2035 /// [GNU] offsetof-member-designator '.' identifier
2036 /// [GNU] offsetof-member-designator '[' expression ']'
2038 ExprResult Parser::ParseBuiltinPrimaryExpression() {
2040 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2042 tok::TokenKind T = Tok.getKind();
2043 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
2045 // All of these start with an open paren.
2046 if (Tok.isNot(tok::l_paren))
2047 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2050 BalancedDelimiterTracker PT(*this, tok::l_paren);
2056 default: llvm_unreachable("Not a builtin primary expression!");
2057 case tok::kw___builtin_va_arg: {
2058 ExprResult Expr(ParseAssignmentExpression());
2060 if (ExpectAndConsume(tok::comma)) {
2061 SkipUntil(tok::r_paren, StopAtSemi);
2065 TypeResult Ty = ParseTypeName();
2067 if (Tok.isNot(tok::r_paren)) {
2068 Diag(Tok, diag::err_expected) << tok::r_paren;
2072 if (Expr.isInvalid() || Ty.isInvalid())
2075 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2078 case tok::kw___builtin_offsetof: {
2079 SourceLocation TypeLoc = Tok.getLocation();
2080 TypeResult Ty = ParseTypeName();
2081 if (Ty.isInvalid()) {
2082 SkipUntil(tok::r_paren, StopAtSemi);
2086 if (ExpectAndConsume(tok::comma)) {
2087 SkipUntil(tok::r_paren, StopAtSemi);
2091 // We must have at least one identifier here.
2092 if (Tok.isNot(tok::identifier)) {
2093 Diag(Tok, diag::err_expected) << tok::identifier;
2094 SkipUntil(tok::r_paren, StopAtSemi);
2098 // Keep track of the various subcomponents we see.
2099 SmallVector<Sema::OffsetOfComponent, 4> Comps;
2101 Comps.push_back(Sema::OffsetOfComponent());
2102 Comps.back().isBrackets = false;
2103 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2104 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2106 // FIXME: This loop leaks the index expressions on error.
2108 if (Tok.is(tok::period)) {
2109 // offsetof-member-designator: offsetof-member-designator '.' identifier
2110 Comps.push_back(Sema::OffsetOfComponent());
2111 Comps.back().isBrackets = false;
2112 Comps.back().LocStart = ConsumeToken();
2114 if (Tok.isNot(tok::identifier)) {
2115 Diag(Tok, diag::err_expected) << tok::identifier;
2116 SkipUntil(tok::r_paren, StopAtSemi);
2119 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2120 Comps.back().LocEnd = ConsumeToken();
2122 } else if (Tok.is(tok::l_square)) {
2123 if (CheckProhibitedCXX11Attribute())
2126 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2127 Comps.push_back(Sema::OffsetOfComponent());
2128 Comps.back().isBrackets = true;
2129 BalancedDelimiterTracker ST(*this, tok::l_square);
2131 Comps.back().LocStart = ST.getOpenLocation();
2132 Res = ParseExpression();
2133 if (Res.isInvalid()) {
2134 SkipUntil(tok::r_paren, StopAtSemi);
2137 Comps.back().U.E = Res.get();
2140 Comps.back().LocEnd = ST.getCloseLocation();
2142 if (Tok.isNot(tok::r_paren)) {
2145 } else if (Ty.isInvalid()) {
2149 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2151 PT.getCloseLocation());
2158 case tok::kw___builtin_choose_expr: {
2159 ExprResult Cond(ParseAssignmentExpression());
2160 if (Cond.isInvalid()) {
2161 SkipUntil(tok::r_paren, StopAtSemi);
2164 if (ExpectAndConsume(tok::comma)) {
2165 SkipUntil(tok::r_paren, StopAtSemi);
2169 ExprResult Expr1(ParseAssignmentExpression());
2170 if (Expr1.isInvalid()) {
2171 SkipUntil(tok::r_paren, StopAtSemi);
2174 if (ExpectAndConsume(tok::comma)) {
2175 SkipUntil(tok::r_paren, StopAtSemi);
2179 ExprResult Expr2(ParseAssignmentExpression());
2180 if (Expr2.isInvalid()) {
2181 SkipUntil(tok::r_paren, StopAtSemi);
2184 if (Tok.isNot(tok::r_paren)) {
2185 Diag(Tok, diag::err_expected) << tok::r_paren;
2188 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2189 Expr2.get(), ConsumeParen());
2192 case tok::kw___builtin_astype: {
2193 // The first argument is an expression to be converted, followed by a comma.
2194 ExprResult Expr(ParseAssignmentExpression());
2195 if (Expr.isInvalid()) {
2196 SkipUntil(tok::r_paren, StopAtSemi);
2200 if (ExpectAndConsume(tok::comma)) {
2201 SkipUntil(tok::r_paren, StopAtSemi);
2205 // Second argument is the type to bitcast to.
2206 TypeResult DestTy = ParseTypeName();
2207 if (DestTy.isInvalid())
2210 // Attempt to consume the r-paren.
2211 if (Tok.isNot(tok::r_paren)) {
2212 Diag(Tok, diag::err_expected) << tok::r_paren;
2213 SkipUntil(tok::r_paren, StopAtSemi);
2217 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2221 case tok::kw___builtin_convertvector: {
2222 // The first argument is an expression to be converted, followed by a comma.
2223 ExprResult Expr(ParseAssignmentExpression());
2224 if (Expr.isInvalid()) {
2225 SkipUntil(tok::r_paren, StopAtSemi);
2229 if (ExpectAndConsume(tok::comma)) {
2230 SkipUntil(tok::r_paren, StopAtSemi);
2234 // Second argument is the type to bitcast to.
2235 TypeResult DestTy = ParseTypeName();
2236 if (DestTy.isInvalid())
2239 // Attempt to consume the r-paren.
2240 if (Tok.isNot(tok::r_paren)) {
2241 Diag(Tok, diag::err_expected) << tok::r_paren;
2242 SkipUntil(tok::r_paren, StopAtSemi);
2246 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2252 if (Res.isInvalid())
2255 // These can be followed by postfix-expr pieces because they are
2256 // primary-expressions.
2257 return ParsePostfixExpressionSuffix(Res.get());
2260 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2261 /// based on what is allowed by ExprType. The actual thing parsed is returned
2262 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2263 /// not the parsed cast-expression.
2266 /// primary-expression: [C99 6.5.1]
2267 /// '(' expression ')'
2268 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2269 /// postfix-expression: [C99 6.5.2]
2270 /// '(' type-name ')' '{' initializer-list '}'
2271 /// '(' type-name ')' '{' initializer-list ',' '}'
2272 /// cast-expression: [C99 6.5.4]
2273 /// '(' type-name ')' cast-expression
2274 /// [ARC] bridged-cast-expression
2275 /// [ARC] bridged-cast-expression:
2276 /// (__bridge type-name) cast-expression
2277 /// (__bridge_transfer type-name) cast-expression
2278 /// (__bridge_retained type-name) cast-expression
2279 /// fold-expression: [C++1z]
2280 /// '(' cast-expression fold-operator '...' ')'
2281 /// '(' '...' fold-operator cast-expression ')'
2282 /// '(' cast-expression fold-operator '...'
2283 /// fold-operator cast-expression ')'
2286 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2287 bool isTypeCast, ParsedType &CastTy,
2288 SourceLocation &RParenLoc) {
2289 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2290 ColonProtectionRAIIObject ColonProtection(*this, false);
2291 BalancedDelimiterTracker T(*this, tok::l_paren);
2292 if (T.consumeOpen())
2294 SourceLocation OpenLoc = T.getOpenLocation();
2296 ExprResult Result(true);
2297 bool isAmbiguousTypeId;
2300 if (Tok.is(tok::code_completion)) {
2301 Actions.CodeCompleteOrdinaryName(getCurScope(),
2302 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2303 : Sema::PCC_Expression);
2308 // Diagnose use of bridge casts in non-arc mode.
2309 bool BridgeCast = (getLangOpts().ObjC2 &&
2310 Tok.isOneOf(tok::kw___bridge,
2311 tok::kw___bridge_transfer,
2312 tok::kw___bridge_retained,
2313 tok::kw___bridge_retain));
2314 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2315 if (!TryConsumeToken(tok::kw___bridge)) {
2316 StringRef BridgeCastName = Tok.getName();
2317 SourceLocation BridgeKeywordLoc = ConsumeToken();
2318 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2319 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2321 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2326 // None of these cases should fall through with an invalid Result
2327 // unless they've already reported an error.
2328 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2329 Diag(Tok, diag::ext_gnu_statement_expr);
2331 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2332 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2334 // Find the nearest non-record decl context. Variables declared in a
2335 // statement expression behave as if they were declared in the enclosing
2336 // function, block, or other code construct.
2337 DeclContext *CodeDC = Actions.CurContext;
2338 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2339 CodeDC = CodeDC->getParent();
2340 assert(CodeDC && !CodeDC->isFileContext() &&
2341 "statement expr not in code context");
2343 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2345 Actions.ActOnStartStmtExpr();
2347 StmtResult Stmt(ParseCompoundStatement(true));
2348 ExprType = CompoundStmt;
2350 // If the substmt parsed correctly, build the AST node.
2351 if (!Stmt.isInvalid()) {
2352 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2354 Actions.ActOnStmtExprError();
2357 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2358 tok::TokenKind tokenKind = Tok.getKind();
2359 SourceLocation BridgeKeywordLoc = ConsumeToken();
2361 // Parse an Objective-C ARC ownership cast expression.
2362 ObjCBridgeCastKind Kind;
2363 if (tokenKind == tok::kw___bridge)
2365 else if (tokenKind == tok::kw___bridge_transfer)
2366 Kind = OBC_BridgeTransfer;
2367 else if (tokenKind == tok::kw___bridge_retained)
2368 Kind = OBC_BridgeRetained;
2370 // As a hopefully temporary workaround, allow __bridge_retain as
2371 // a synonym for __bridge_retained, but only in system headers.
2372 assert(tokenKind == tok::kw___bridge_retain);
2373 Kind = OBC_BridgeRetained;
2374 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2375 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2376 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2377 "__bridge_retained");
2380 TypeResult Ty = ParseTypeName();
2382 ColonProtection.restore();
2383 RParenLoc = T.getCloseLocation();
2384 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2386 if (Ty.isInvalid() || SubExpr.isInvalid())
2389 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2390 BridgeKeywordLoc, Ty.get(),
2391 RParenLoc, SubExpr.get());
2392 } else if (ExprType >= CompoundLiteral &&
2393 isTypeIdInParens(isAmbiguousTypeId)) {
2395 // Otherwise, this is a compound literal expression or cast expression.
2397 // In C++, if the type-id is ambiguous we disambiguate based on context.
2398 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2399 // in which case we should treat it as type-id.
2400 // if stopIfCastExpr is false, we need to determine the context past the
2401 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2402 if (isAmbiguousTypeId && !stopIfCastExpr) {
2403 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2405 RParenLoc = T.getCloseLocation();
2409 // Parse the type declarator.
2410 DeclSpec DS(AttrFactory);
2411 ParseSpecifierQualifierList(DS);
2412 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2413 ParseDeclarator(DeclaratorInfo);
2415 // If our type is followed by an identifier and either ':' or ']', then
2416 // this is probably an Objective-C message send where the leading '[' is
2417 // missing. Recover as if that were the case.
2418 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2419 !InMessageExpression && getLangOpts().ObjC1 &&
2420 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2423 InMessageExpressionRAIIObject InMessage(*this, false);
2424 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2426 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2432 ColonProtection.restore();
2433 RParenLoc = T.getCloseLocation();
2434 if (Tok.is(tok::l_brace)) {
2435 ExprType = CompoundLiteral;
2438 InMessageExpressionRAIIObject InMessage(*this, false);
2439 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2441 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2444 if (Tok.is(tok::l_paren)) {
2445 // This could be OpenCL vector Literals
2446 if (getLangOpts().OpenCL)
2450 InMessageExpressionRAIIObject InMessage(*this, false);
2451 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2457 QualType QT = Ty.get().get().getCanonicalType();
2458 if (QT->isVectorType())
2460 // We parsed '(' vector-type-name ')' followed by '('
2462 // Parse the cast-expression that follows it next.
2463 // isVectorLiteral = true will make sure we don't parse any
2464 // Postfix expression yet
2465 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2466 /*isAddressOfOperand=*/false,
2467 /*isTypeCast=*/IsTypeCast,
2468 /*isVectorLiteral=*/true);
2470 if (!Result.isInvalid()) {
2471 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2472 DeclaratorInfo, CastTy,
2473 RParenLoc, Result.get());
2476 // After we performed the cast we can check for postfix-expr pieces.
2477 if (!Result.isInvalid()) {
2478 Result = ParsePostfixExpressionSuffix(Result);
2486 if (ExprType == CastExpr) {
2487 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2489 if (DeclaratorInfo.isInvalidType())
2492 // Note that this doesn't parse the subsequent cast-expression, it just
2493 // returns the parsed type to the callee.
2494 if (stopIfCastExpr) {
2497 InMessageExpressionRAIIObject InMessage(*this, false);
2498 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2501 return ExprResult();
2504 // Reject the cast of super idiom in ObjC.
2505 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2506 Tok.getIdentifierInfo() == Ident_super &&
2507 getCurScope()->isInObjcMethodScope() &&
2508 GetLookAheadToken(1).isNot(tok::period)) {
2509 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2510 << SourceRange(OpenLoc, RParenLoc);
2514 // Parse the cast-expression that follows it next.
2515 // TODO: For cast expression with CastTy.
2516 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2517 /*isAddressOfOperand=*/false,
2518 /*isTypeCast=*/IsTypeCast);
2519 if (!Result.isInvalid()) {
2520 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2521 DeclaratorInfo, CastTy,
2522 RParenLoc, Result.get());
2527 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2530 } else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) &&
2531 isFoldOperator(NextToken().getKind())) {
2532 ExprType = FoldExpr;
2533 return ParseFoldExpression(ExprResult(), T);
2534 } else if (isTypeCast) {
2535 // Parse the expression-list.
2536 InMessageExpressionRAIIObject InMessage(*this, false);
2538 ExprVector ArgExprs;
2539 CommaLocsTy CommaLocs;
2541 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2542 // FIXME: If we ever support comma expressions as operands to
2543 // fold-expressions, we'll need to allow multiple ArgExprs here.
2544 if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
2545 isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
2546 ExprType = FoldExpr;
2547 return ParseFoldExpression(ArgExprs[0], T);
2550 ExprType = SimpleExpr;
2551 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2555 InMessageExpressionRAIIObject InMessage(*this, false);
2557 Result = ParseExpression(MaybeTypeCast);
2558 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2559 // Correct typos in non-C++ code earlier so that implicit-cast-like
2560 // expressions are parsed correctly.
2561 Result = Actions.CorrectDelayedTyposInExpr(Result);
2564 if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
2565 NextToken().is(tok::ellipsis)) {
2566 ExprType = FoldExpr;
2567 return ParseFoldExpression(Result, T);
2569 ExprType = SimpleExpr;
2571 // Don't build a paren expression unless we actually match a ')'.
2572 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2574 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2578 if (Result.isInvalid()) {
2579 SkipUntil(tok::r_paren, StopAtSemi);
2584 RParenLoc = T.getCloseLocation();
2588 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2589 /// and we are at the left brace.
2592 /// postfix-expression: [C99 6.5.2]
2593 /// '(' type-name ')' '{' initializer-list '}'
2594 /// '(' type-name ')' '{' initializer-list ',' '}'
2597 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2598 SourceLocation LParenLoc,
2599 SourceLocation RParenLoc) {
2600 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2601 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2602 Diag(LParenLoc, diag::ext_c99_compound_literal);
2603 ExprResult Result = ParseInitializer();
2604 if (!Result.isInvalid() && Ty)
2605 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2609 /// ParseStringLiteralExpression - This handles the various token types that
2610 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2611 /// translation phase #6].
2614 /// primary-expression: [C99 6.5.1]
2617 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2618 assert(isTokenStringLiteral() && "Not a string literal!");
2620 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2621 // considered to be strings for concatenation purposes.
2622 SmallVector<Token, 4> StringToks;
2625 StringToks.push_back(Tok);
2626 ConsumeStringToken();
2627 } while (isTokenStringLiteral());
2629 // Pass the set of string tokens, ready for concatenation, to the actions.
2630 return Actions.ActOnStringLiteral(StringToks,
2631 AllowUserDefinedLiteral ? getCurScope()
2635 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2639 /// generic-selection:
2640 /// _Generic ( assignment-expression , generic-assoc-list )
2641 /// generic-assoc-list:
2642 /// generic-association
2643 /// generic-assoc-list , generic-association
2644 /// generic-association:
2645 /// type-name : assignment-expression
2646 /// default : assignment-expression
2648 ExprResult Parser::ParseGenericSelectionExpression() {
2649 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2650 SourceLocation KeyLoc = ConsumeToken();
2652 if (!getLangOpts().C11)
2653 Diag(KeyLoc, diag::ext_c11_generic_selection);
2655 BalancedDelimiterTracker T(*this, tok::l_paren);
2656 if (T.expectAndConsume())
2659 ExprResult ControllingExpr;
2661 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2663 EnterExpressionEvaluationContext Unevaluated(
2664 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
2666 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2667 if (ControllingExpr.isInvalid()) {
2668 SkipUntil(tok::r_paren, StopAtSemi);
2673 if (ExpectAndConsume(tok::comma)) {
2674 SkipUntil(tok::r_paren, StopAtSemi);
2678 SourceLocation DefaultLoc;
2683 if (Tok.is(tok::kw_default)) {
2684 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2685 // generic association."
2686 if (!DefaultLoc.isInvalid()) {
2687 Diag(Tok, diag::err_duplicate_default_assoc);
2688 Diag(DefaultLoc, diag::note_previous_default_assoc);
2689 SkipUntil(tok::r_paren, StopAtSemi);
2692 DefaultLoc = ConsumeToken();
2695 ColonProtectionRAIIObject X(*this);
2696 TypeResult TR = ParseTypeName();
2697 if (TR.isInvalid()) {
2698 SkipUntil(tok::r_paren, StopAtSemi);
2703 Types.push_back(Ty);
2705 if (ExpectAndConsume(tok::colon)) {
2706 SkipUntil(tok::r_paren, StopAtSemi);
2710 // FIXME: These expressions should be parsed in a potentially potentially
2711 // evaluated context.
2713 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2714 if (ER.isInvalid()) {
2715 SkipUntil(tok::r_paren, StopAtSemi);
2718 Exprs.push_back(ER.get());
2719 } while (TryConsumeToken(tok::comma));
2722 if (T.getCloseLocation().isInvalid())
2725 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2726 T.getCloseLocation(),
2727 ControllingExpr.get(),
2731 /// Parse A C++1z fold-expression after the opening paren and optional
2732 /// left-hand-side expression.
2735 /// fold-expression:
2736 /// ( cast-expression fold-operator ... )
2737 /// ( ... fold-operator cast-expression )
2738 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2739 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2740 BalancedDelimiterTracker &T) {
2741 if (LHS.isInvalid()) {
2746 tok::TokenKind Kind = tok::unknown;
2747 SourceLocation FirstOpLoc;
2748 if (LHS.isUsable()) {
2749 Kind = Tok.getKind();
2750 assert(isFoldOperator(Kind) && "missing fold-operator");
2751 FirstOpLoc = ConsumeToken();
2754 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2755 SourceLocation EllipsisLoc = ConsumeToken();
2758 if (Tok.isNot(tok::r_paren)) {
2759 if (!isFoldOperator(Tok.getKind()))
2760 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2762 if (Kind != tok::unknown && Tok.getKind() != Kind)
2763 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2764 << SourceRange(FirstOpLoc);
2765 Kind = Tok.getKind();
2768 RHS = ParseExpression();
2769 if (RHS.isInvalid()) {
2775 Diag(EllipsisLoc, getLangOpts().CPlusPlus17
2776 ? diag::warn_cxx14_compat_fold_expression
2777 : diag::ext_fold_expression);
2780 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2781 EllipsisLoc, RHS.get(), T.getCloseLocation());
2784 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2787 /// argument-expression-list:
2788 /// assignment-expression
2789 /// argument-expression-list , assignment-expression
2791 /// [C++] expression-list:
2792 /// [C++] assignment-expression
2793 /// [C++] expression-list , assignment-expression
2795 /// [C++0x] expression-list:
2796 /// [C++0x] initializer-list
2798 /// [C++0x] initializer-list
2799 /// [C++0x] initializer-clause ...[opt]
2800 /// [C++0x] initializer-list , initializer-clause ...[opt]
2802 /// [C++0x] initializer-clause:
2803 /// [C++0x] assignment-expression
2804 /// [C++0x] braced-init-list
2806 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2807 SmallVectorImpl<SourceLocation> &CommaLocs,
2808 llvm::function_ref<void()> Completer) {
2809 bool SawError = false;
2811 if (Tok.is(tok::code_completion)) {
2815 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2821 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2822 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2823 Expr = ParseBraceInitializer();
2825 Expr = ParseAssignmentExpression();
2827 if (Tok.is(tok::ellipsis))
2828 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2829 if (Expr.isInvalid()) {
2830 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2833 Exprs.push_back(Expr.get());
2836 if (Tok.isNot(tok::comma))
2838 // Move to the next argument, remember where the comma was.
2840 CommaLocs.push_back(ConsumeToken());
2842 checkPotentialAngleBracketDelimiter(Comma);
2845 // Ensure typos get diagnosed when errors were encountered while parsing the
2847 for (auto &E : Exprs) {
2848 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2849 if (Expr.isUsable()) E = Expr.get();
2855 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2856 /// used for misc language extensions.
2859 /// simple-expression-list:
2860 /// assignment-expression
2861 /// simple-expression-list , assignment-expression
2864 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2865 SmallVectorImpl<SourceLocation> &CommaLocs) {
2867 ExprResult Expr = ParseAssignmentExpression();
2868 if (Expr.isInvalid())
2871 Exprs.push_back(Expr.get());
2873 if (Tok.isNot(tok::comma))
2876 // Move to the next argument, remember where the comma was.
2878 CommaLocs.push_back(ConsumeToken());
2880 checkPotentialAngleBracketDelimiter(Comma);
2884 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2887 /// [clang] block-id:
2888 /// [clang] specifier-qualifier-list block-declarator
2890 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2891 if (Tok.is(tok::code_completion)) {
2892 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2893 return cutOffParsing();
2896 // Parse the specifier-qualifier-list piece.
2897 DeclSpec DS(AttrFactory);
2898 ParseSpecifierQualifierList(DS);
2900 // Parse the block-declarator.
2901 Declarator DeclaratorInfo(DS, DeclaratorContext::BlockLiteralContext);
2902 DeclaratorInfo.setFunctionDefinitionKind(FDK_Definition);
2903 ParseDeclarator(DeclaratorInfo);
2905 MaybeParseGNUAttributes(DeclaratorInfo);
2907 // Inform sema that we are starting a block.
2908 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2911 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2912 /// like ^(int x){ return x+1; }
2916 /// [clang] '^' block-args[opt] compound-statement
2917 /// [clang] '^' block-id compound-statement
2918 /// [clang] block-args:
2919 /// [clang] '(' parameter-list ')'
2921 ExprResult Parser::ParseBlockLiteralExpression() {
2922 assert(Tok.is(tok::caret) && "block literal starts with ^");
2923 SourceLocation CaretLoc = ConsumeToken();
2925 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2926 "block literal parsing");
2928 // Enter a scope to hold everything within the block. This includes the
2929 // argument decls, decls within the compound expression, etc. This also
2930 // allows determining whether a variable reference inside the block is
2931 // within or outside of the block.
2932 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2933 Scope::CompoundStmtScope | Scope::DeclScope);
2935 // Inform sema that we are starting a block.
2936 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2938 // Parse the return type if present.
2939 DeclSpec DS(AttrFactory);
2940 Declarator ParamInfo(DS, DeclaratorContext::BlockLiteralContext);
2941 ParamInfo.setFunctionDefinitionKind(FDK_Definition);
2942 // FIXME: Since the return type isn't actually parsed, it can't be used to
2943 // fill ParamInfo with an initial valid range, so do it manually.
2944 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2946 // If this block has arguments, parse them. There is no ambiguity here with
2947 // the expression case, because the expression case requires a parameter list.
2948 if (Tok.is(tok::l_paren)) {
2949 ParseParenDeclarator(ParamInfo);
2950 // Parse the pieces after the identifier as if we had "int(...)".
2951 // SetIdentifier sets the source range end, but in this case we're past
2953 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2954 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2955 ParamInfo.SetRangeEnd(Tmp);
2956 if (ParamInfo.isInvalidType()) {
2957 // If there was an error parsing the arguments, they may have
2958 // tried to use ^(x+y) which requires an argument list. Just
2959 // skip the whole block literal.
2960 Actions.ActOnBlockError(CaretLoc, getCurScope());
2964 MaybeParseGNUAttributes(ParamInfo);
2966 // Inform sema that we are starting a block.
2967 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2968 } else if (!Tok.is(tok::l_brace)) {
2969 ParseBlockId(CaretLoc);
2971 // Otherwise, pretend we saw (void).
2972 SourceLocation NoLoc;
2973 ParamInfo.AddTypeInfo(
2974 DeclaratorChunk::getFunction(/*HasProto=*/true,
2975 /*IsAmbiguous=*/false,
2976 /*RParenLoc=*/NoLoc,
2977 /*ArgInfo=*/nullptr,
2979 /*EllipsisLoc=*/NoLoc,
2980 /*RParenLoc=*/NoLoc,
2982 /*RefQualifierIsLvalueRef=*/true,
2983 /*RefQualifierLoc=*/NoLoc,
2984 /*ConstQualifierLoc=*/NoLoc,
2985 /*VolatileQualifierLoc=*/NoLoc,
2986 /*RestrictQualifierLoc=*/NoLoc,
2987 /*MutableLoc=*/NoLoc, EST_None,
2988 /*ESpecRange=*/SourceRange(),
2989 /*Exceptions=*/nullptr,
2990 /*ExceptionRanges=*/nullptr,
2991 /*NumExceptions=*/0,
2992 /*NoexceptExpr=*/nullptr,
2993 /*ExceptionSpecTokens=*/nullptr,
2994 /*DeclsInPrototype=*/None, CaretLoc,
2995 CaretLoc, ParamInfo),
2998 MaybeParseGNUAttributes(ParamInfo);
3000 // Inform sema that we are starting a block.
3001 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3005 ExprResult Result(true);
3006 if (!Tok.is(tok::l_brace)) {
3007 // Saw something like: ^expr
3008 Diag(Tok, diag::err_expected_expression);
3009 Actions.ActOnBlockError(CaretLoc, getCurScope());
3013 StmtResult Stmt(ParseCompoundStatementBody());
3015 if (!Stmt.isInvalid())
3016 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3018 Actions.ActOnBlockError(CaretLoc, getCurScope());
3022 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3026 ExprResult Parser::ParseObjCBoolLiteral() {
3027 tok::TokenKind Kind = Tok.getKind();
3028 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3031 /// Validate availability spec list, emitting diagnostics if necessary. Returns
3032 /// true if invalid.
3033 static bool CheckAvailabilitySpecList(Parser &P,
3034 ArrayRef<AvailabilitySpec> AvailSpecs) {
3035 llvm::SmallSet<StringRef, 4> Platforms;
3036 bool HasOtherPlatformSpec = false;
3038 for (const auto &Spec : AvailSpecs) {
3039 if (Spec.isOtherPlatformSpec()) {
3040 if (HasOtherPlatformSpec) {
3041 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3045 HasOtherPlatformSpec = true;
3049 bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3051 // Rule out multiple version specs referring to the same platform.
3052 // For example, we emit an error for:
3053 // @available(macos 10.10, macos 10.11, *)
3054 StringRef Platform = Spec.getPlatform();
3055 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3056 << Spec.getEndLoc() << Platform;
3061 if (!HasOtherPlatformSpec) {
3062 SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3063 P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3064 << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3071 /// Parse availability query specification.
3073 /// availability-spec:
3075 /// identifier version-tuple
3076 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3077 if (Tok.is(tok::star)) {
3078 return AvailabilitySpec(ConsumeToken());
3080 // Parse the platform name.
3081 if (Tok.is(tok::code_completion)) {
3082 Actions.CodeCompleteAvailabilityPlatformName();
3086 if (Tok.isNot(tok::identifier)) {
3087 Diag(Tok, diag::err_avail_query_expected_platform_name);
3091 IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3092 SourceRange VersionRange;
3093 VersionTuple Version = ParseVersionTuple(VersionRange);
3095 if (Version.empty())
3098 StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3099 StringRef Platform =
3100 AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3102 if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3103 Diag(PlatformIdentifier->Loc,
3104 diag::err_avail_query_unrecognized_platform_name)
3109 return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3110 VersionRange.getEnd());
3114 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3115 assert(Tok.is(tok::kw___builtin_available) ||
3116 Tok.isObjCAtKeyword(tok::objc_available));
3118 // Eat the available or __builtin_available.
3121 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3122 if (Parens.expectAndConsume())
3125 SmallVector<AvailabilitySpec, 4> AvailSpecs;
3126 bool HasError = false;
3128 Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3132 AvailSpecs.push_back(*Spec);
3134 if (!TryConsumeToken(tok::comma))
3139 SkipUntil(tok::r_paren, StopAtSemi);
3143 CheckAvailabilitySpecList(*this, AvailSpecs);
3145 if (Parens.consumeClose())
3148 return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3149 Parens.getCloseLocation());