1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Provides the Expression parsing implementation.
13 /// Expressions in C99 basically consist of a bunch of binary operators with
14 /// unary operators and other random stuff at the leaves.
16 /// In the C99 grammar, these unary operators bind tightest and are represented
17 /// as the 'cast-expression' production. Everything else is either a binary
18 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
19 /// handled by ParseCastExpression, the higher level pieces are handled by
20 /// ParseBinaryExpression.
22 //===----------------------------------------------------------------------===//
24 #include "clang/Parse/Parser.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/Basic/PrettyStackTrace.h"
27 #include "clang/Parse/RAIIObjectsForParser.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/ParsedTemplate.h"
30 #include "clang/Sema/Scope.h"
31 #include "clang/Sema/TypoCorrection.h"
32 #include "llvm/ADT/SmallVector.h"
33 using namespace clang;
35 /// \brief Simple precedence-based parser for binary/ternary operators.
37 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
38 /// production. C99 specifies that the LHS of an assignment operator should be
39 /// parsed as a unary-expression, but consistency dictates that it be a
40 /// conditional-expession. In practice, the important thing here is that the
41 /// LHS of an assignment has to be an l-value, which productions between
42 /// unary-expression and conditional-expression don't produce. Because we want
43 /// consistency, we parse the LHS as a conditional-expression, then check for
44 /// l-value-ness in semantic analysis stages.
47 /// pm-expression: [C++ 5.5]
49 /// pm-expression '.*' cast-expression
50 /// pm-expression '->*' cast-expression
52 /// multiplicative-expression: [C99 6.5.5]
53 /// Note: in C++, apply pm-expression instead of cast-expression
55 /// multiplicative-expression '*' cast-expression
56 /// multiplicative-expression '/' cast-expression
57 /// multiplicative-expression '%' cast-expression
59 /// additive-expression: [C99 6.5.6]
60 /// multiplicative-expression
61 /// additive-expression '+' multiplicative-expression
62 /// additive-expression '-' multiplicative-expression
64 /// shift-expression: [C99 6.5.7]
65 /// additive-expression
66 /// shift-expression '<<' additive-expression
67 /// shift-expression '>>' additive-expression
69 /// relational-expression: [C99 6.5.8]
71 /// relational-expression '<' shift-expression
72 /// relational-expression '>' shift-expression
73 /// relational-expression '<=' shift-expression
74 /// relational-expression '>=' shift-expression
76 /// equality-expression: [C99 6.5.9]
77 /// relational-expression
78 /// equality-expression '==' relational-expression
79 /// equality-expression '!=' relational-expression
81 /// AND-expression: [C99 6.5.10]
82 /// equality-expression
83 /// AND-expression '&' equality-expression
85 /// exclusive-OR-expression: [C99 6.5.11]
87 /// exclusive-OR-expression '^' AND-expression
89 /// inclusive-OR-expression: [C99 6.5.12]
90 /// exclusive-OR-expression
91 /// inclusive-OR-expression '|' exclusive-OR-expression
93 /// logical-AND-expression: [C99 6.5.13]
94 /// inclusive-OR-expression
95 /// logical-AND-expression '&&' inclusive-OR-expression
97 /// logical-OR-expression: [C99 6.5.14]
98 /// logical-AND-expression
99 /// logical-OR-expression '||' logical-AND-expression
101 /// conditional-expression: [C99 6.5.15]
102 /// logical-OR-expression
103 /// logical-OR-expression '?' expression ':' conditional-expression
104 /// [GNU] logical-OR-expression '?' ':' conditional-expression
105 /// [C++] the third operand is an assignment-expression
107 /// assignment-expression: [C99 6.5.16]
108 /// conditional-expression
109 /// unary-expression assignment-operator assignment-expression
110 /// [C++] throw-expression [C++ 15]
112 /// assignment-operator: one of
113 /// = *= /= %= += -= <<= >>= &= ^= |=
115 /// expression: [C99 6.5.17]
116 /// assignment-expression ...[opt]
117 /// expression ',' assignment-expression ...[opt]
119 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
120 ExprResult LHS(ParseAssignmentExpression(isTypeCast));
121 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
124 /// This routine is called when the '@' is seen and consumed.
125 /// Current token is an Identifier and is not a 'try'. This
126 /// routine is necessary to disambiguate \@try-statement from,
127 /// for example, \@encode-expression.
130 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
131 ExprResult LHS(ParseObjCAtExpression(AtLoc));
132 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
135 /// This routine is called when a leading '__extension__' is seen and
136 /// consumed. This is necessary because the token gets consumed in the
137 /// process of disambiguating between an expression and a declaration.
139 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
140 ExprResult LHS(true);
142 // Silence extension warnings in the sub-expression
143 ExtensionRAIIObject O(Diags);
145 LHS = ParseCastExpression(false);
148 if (!LHS.isInvalid())
149 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
152 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
155 /// \brief Parse an expr that doesn't include (top-level) commas.
156 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
157 if (Tok.is(tok::code_completion)) {
158 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
163 if (Tok.is(tok::kw_throw))
164 return ParseThrowExpression();
165 if (Tok.is(tok::kw_co_yield))
166 return ParseCoyieldExpression();
168 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
169 /*isAddressOfOperand=*/false,
171 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
174 /// \brief Parse an assignment expression where part of an Objective-C message
175 /// send has already been parsed.
177 /// In this case \p LBracLoc indicates the location of the '[' of the message
178 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
179 /// the receiver of the message.
181 /// Since this handles full assignment-expression's, it handles postfix
182 /// expressions and other binary operators for these expressions as well.
184 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
185 SourceLocation SuperLoc,
186 ParsedType ReceiverType,
187 Expr *ReceiverExpr) {
189 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
190 ReceiverType, ReceiverExpr);
191 R = ParsePostfixExpressionSuffix(R);
192 return ParseRHSOfBinaryExpression(R, prec::Assignment);
196 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
197 // C++03 [basic.def.odr]p2:
198 // An expression is potentially evaluated unless it appears where an
199 // integral constant expression is required (see 5.19) [...].
200 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
201 EnterExpressionEvaluationContext ConstantEvaluated(
202 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
204 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
205 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
206 return Actions.ActOnConstantExpression(Res);
209 /// \brief Parse a constraint-expression.
212 /// constraint-expression: [Concepts TS temp.constr.decl p1]
213 /// logical-or-expression
215 ExprResult Parser::ParseConstraintExpression() {
216 // FIXME: this may erroneously consume a function-body as the braced
217 // initializer list of a compound literal
219 // FIXME: this may erroneously consume a parenthesized rvalue reference
220 // declarator as a parenthesized address-of-label expression
221 ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
222 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
227 bool Parser::isNotExpressionStart() {
228 tok::TokenKind K = Tok.getKind();
229 if (K == tok::l_brace || K == tok::r_brace ||
230 K == tok::kw_for || K == tok::kw_while ||
231 K == tok::kw_if || K == tok::kw_else ||
232 K == tok::kw_goto || K == tok::kw_try)
234 // If this is a decl-specifier, we can't be at the start of an expression.
235 return isKnownToBeDeclarationSpecifier();
238 /// We've parsed something that could plausibly be intended to be a template
239 /// name (\p LHS) followed by a '<' token, and the following code can't possibly
240 /// be an expression. Determine if this is likely to be a template-id and if so,
242 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
243 TentativeParsingAction TPA(*this);
244 // FIXME: We could look at the token sequence in a lot more detail here.
245 if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
246 StopAtSemi | StopBeforeMatch)) {
249 SourceLocation Greater;
250 ParseGreaterThanInTemplateList(Greater, true, false);
251 Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
256 // There's no matching '>' token, this probably isn't supposed to be
257 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
262 static bool isFoldOperator(prec::Level Level) {
263 return Level > prec::Unknown && Level != prec::Conditional;
265 static bool isFoldOperator(tok::TokenKind Kind) {
266 return isFoldOperator(getBinOpPrecedence(Kind, false, true));
269 /// \brief Parse a binary expression that starts with \p LHS and has a
270 /// precedence of at least \p MinPrec.
272 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
273 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
274 GreaterThanIsOperator,
275 getLangOpts().CPlusPlus11);
276 SourceLocation ColonLoc;
279 // If this token has a lower precedence than we are allowed to parse (e.g.
280 // because we are called recursively, or because the token is not a binop),
282 if (NextTokPrec < MinPrec)
285 // Consume the operator, saving the operator token for error reporting.
289 if (OpToken.is(tok::caretcaret)) {
290 return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
292 // Bail out when encountering a comma followed by a token which can't
293 // possibly be the start of an expression. For instance:
294 // int f() { return 1, }
295 // We can't do this before consuming the comma, because
296 // isNotExpressionStart() looks at the token stream.
297 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
303 // If a '<' token is followed by a type that can be a template argument and
304 // cannot be an expression, then this is ill-formed, but might be intended
305 // to be a template-id.
306 if (OpToken.is(tok::less) && Actions.mightBeIntendedToBeTemplateName(LHS) &&
307 (isKnownToBeDeclarationSpecifier() ||
308 Tok.isOneOf(tok::greater, tok::greatergreater,
309 tok::greatergreatergreater)) &&
310 diagnoseUnknownTemplateId(LHS, OpToken.getLocation()))
313 // If the next token is an ellipsis, then this is a fold-expression. Leave
314 // it alone so we can handle it in the paren expression.
315 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
316 // FIXME: We can't check this via lookahead before we consume the token
317 // because that tickles a lexer bug.
323 // Special case handling for the ternary operator.
324 ExprResult TernaryMiddle(true);
325 if (NextTokPrec == prec::Conditional) {
326 if (Tok.isNot(tok::colon)) {
327 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
328 ColonProtectionRAIIObject X(*this);
330 // Handle this production specially:
331 // logical-OR-expression '?' expression ':' conditional-expression
332 // In particular, the RHS of the '?' is 'expression', not
333 // 'logical-OR-expression' as we might expect.
334 TernaryMiddle = ParseExpression();
335 if (TernaryMiddle.isInvalid()) {
336 Actions.CorrectDelayedTyposInExpr(LHS);
338 TernaryMiddle = nullptr;
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 (!TryConsumeToken(tok::colon, ColonLoc)) {
348 // Otherwise, we're missing a ':'. Assume that this was a typo that
349 // the user forgot. If we're not in a macro expansion, we can suggest
350 // a fixit hint. If there were two spaces before the current token,
351 // suggest inserting the colon in between them, otherwise insert ": ".
352 SourceLocation FILoc = Tok.getLocation();
353 const char *FIText = ": ";
354 const SourceManager &SM = PP.getSourceManager();
355 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
356 assert(FILoc.isFileID());
357 bool IsInvalid = false;
358 const char *SourcePtr =
359 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
360 if (!IsInvalid && *SourcePtr == ' ') {
362 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
363 if (!IsInvalid && *SourcePtr == ' ') {
364 FILoc = FILoc.getLocWithOffset(-1);
370 Diag(Tok, diag::err_expected)
371 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
372 Diag(OpToken, diag::note_matching) << tok::question;
373 ColonLoc = Tok.getLocation();
377 // Code completion for the right-hand side of an assignment expression
378 // goes through a special hook that takes the left-hand side into account.
379 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
380 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
385 // Parse another leaf here for the RHS of the operator.
386 // ParseCastExpression works here because all RHS expressions in C have it
387 // as a prefix, at least. However, in C++, an assignment-expression could
388 // be a throw-expression, which is not a valid cast-expression.
389 // Therefore we need some special-casing here.
390 // Also note that the third operand of the conditional operator is
391 // an assignment-expression in C++, and in C++11, we can have a
392 // braced-init-list on the RHS of an assignment. For better diagnostics,
393 // parse as if we were allowed braced-init-lists everywhere, and check that
394 // they only appear on the RHS of assignments later.
396 bool RHSIsInitList = false;
397 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
398 RHS = ParseBraceInitializer();
399 RHSIsInitList = true;
400 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
401 RHS = ParseAssignmentExpression();
403 RHS = ParseCastExpression(false);
405 if (RHS.isInvalid()) {
406 // FIXME: Errors generated by the delayed typo correction should be
407 // printed before errors from parsing the RHS, not after.
408 Actions.CorrectDelayedTyposInExpr(LHS);
409 if (TernaryMiddle.isUsable())
410 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
414 // Remember the precedence of this operator and get the precedence of the
415 // operator immediately to the right of the RHS.
416 prec::Level ThisPrec = NextTokPrec;
417 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
418 getLangOpts().CPlusPlus11);
420 // Assignment and conditional expressions are right-associative.
421 bool isRightAssoc = ThisPrec == prec::Conditional ||
422 ThisPrec == prec::Assignment;
424 // Get the precedence of the operator to the right of the RHS. If it binds
425 // more tightly with RHS than we do, evaluate it completely first.
426 if (ThisPrec < NextTokPrec ||
427 (ThisPrec == NextTokPrec && isRightAssoc)) {
428 if (!RHS.isInvalid() && RHSIsInitList) {
429 Diag(Tok, diag::err_init_list_bin_op)
430 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
433 // If this is left-associative, only parse things on the RHS that bind
434 // more tightly than the current operator. If it is left-associative, it
435 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
436 // A=(B=(C=D)), where each paren is a level of recursion here.
437 // The function takes ownership of the RHS.
438 RHS = ParseRHSOfBinaryExpression(RHS,
439 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
440 RHSIsInitList = false;
442 if (RHS.isInvalid()) {
443 // FIXME: Errors generated by the delayed typo correction should be
444 // printed before errors from ParseRHSOfBinaryExpression, not after.
445 Actions.CorrectDelayedTyposInExpr(LHS);
446 if (TernaryMiddle.isUsable())
447 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
451 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
452 getLangOpts().CPlusPlus11);
455 if (!RHS.isInvalid() && RHSIsInitList) {
456 if (ThisPrec == prec::Assignment) {
457 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
458 << Actions.getExprRange(RHS.get());
460 Diag(OpToken, diag::err_init_list_bin_op)
461 << /*RHS*/1 << PP.getSpelling(OpToken)
462 << Actions.getExprRange(RHS.get());
467 ExprResult OrigLHS = LHS;
468 if (!LHS.isInvalid()) {
469 // Combine the LHS and RHS into the LHS (e.g. build AST).
470 if (TernaryMiddle.isInvalid()) {
471 // If we're using '>>' as an operator within a template
472 // argument list (in C++98), suggest the addition of
473 // parentheses so that the code remains well-formed in C++0x.
474 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
475 SuggestParentheses(OpToken.getLocation(),
476 diag::warn_cxx11_right_shift_in_template_arg,
477 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
478 Actions.getExprRange(RHS.get()).getEnd()));
480 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
481 OpToken.getKind(), LHS.get(), RHS.get());
484 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
485 LHS.get(), TernaryMiddle.get(),
488 // In this case, ActOnBinOp or ActOnConditionalOp performed the
489 // CorrectDelayedTyposInExpr check.
490 if (!getLangOpts().CPlusPlus)
494 // Ensure potential typos aren't left undiagnosed.
495 if (LHS.isInvalid()) {
496 Actions.CorrectDelayedTyposInExpr(OrigLHS);
497 Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
498 Actions.CorrectDelayedTyposInExpr(RHS);
503 /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
504 /// parse a unary-expression.
506 /// \p isAddressOfOperand exists because an id-expression that is the
507 /// operand of address-of gets special treatment due to member pointers.
509 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
510 bool isAddressOfOperand,
511 TypeCastState isTypeCast,
512 bool isVectorLiteral) {
514 ExprResult Res = ParseCastExpression(isUnaryExpression,
520 Diag(Tok, diag::err_expected_expression);
525 class CastExpressionIdValidator : public CorrectionCandidateCallback {
527 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
528 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
529 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
532 bool ValidateCandidate(const TypoCorrection &candidate) override {
533 NamedDecl *ND = candidate.getCorrectionDecl();
535 return candidate.isKeyword();
537 if (isa<TypeDecl>(ND))
538 return WantTypeSpecifiers;
540 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
543 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
546 for (auto *C : candidate) {
547 NamedDecl *ND = C->getUnderlyingDecl();
548 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
560 /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
561 /// a unary-expression.
563 /// \p isAddressOfOperand exists because an id-expression that is the operand
564 /// of address-of gets special treatment due to member pointers. NotCastExpr
565 /// is set to true if the token is not the start of a cast-expression, and no
566 /// diagnostic is emitted in this case and no tokens are consumed.
569 /// cast-expression: [C99 6.5.4]
571 /// '(' type-name ')' cast-expression
573 /// unary-expression: [C99 6.5.3]
574 /// postfix-expression
575 /// '++' unary-expression
576 /// '--' unary-expression
577 /// [Coro] 'co_await' cast-expression
578 /// unary-operator cast-expression
579 /// 'sizeof' unary-expression
580 /// 'sizeof' '(' type-name ')'
581 /// [C++11] 'sizeof' '...' '(' identifier ')'
582 /// [GNU] '__alignof' unary-expression
583 /// [GNU] '__alignof' '(' type-name ')'
584 /// [C11] '_Alignof' '(' type-name ')'
585 /// [C++11] 'alignof' '(' type-id ')'
586 /// [GNU] '&&' identifier
587 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
588 /// [C++] new-expression
589 /// [C++] delete-expression
591 /// unary-operator: one of
592 /// '&' '*' '+' '-' '~' '!'
593 /// [GNU] '__extension__' '__real' '__imag'
595 /// primary-expression: [C99 6.5.1]
597 /// [C++] id-expression
600 /// [C++] boolean-literal [C++ 2.13.5]
601 /// [C++11] 'nullptr' [C++11 2.14.7]
602 /// [C++11] user-defined-literal
603 /// '(' expression ')'
604 /// [C11] generic-selection
605 /// '__func__' [C99 6.4.2.2]
606 /// [GNU] '__FUNCTION__'
607 /// [MS] '__FUNCDNAME__'
608 /// [MS] 'L__FUNCTION__'
609 /// [GNU] '__PRETTY_FUNCTION__'
610 /// [GNU] '(' compound-statement ')'
611 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
612 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
613 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
615 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
617 /// [OBJC] '[' objc-message-expr ']'
618 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
619 /// [OBJC] '\@protocol' '(' identifier ')'
620 /// [OBJC] '\@encode' '(' type-name ')'
621 /// [OBJC] objc-string-literal
622 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
623 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
624 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
625 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
626 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
627 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
628 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
629 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
630 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
631 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
632 /// [C++] 'this' [C++ 9.3.2]
633 /// [G++] unary-type-trait '(' type-id ')'
634 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
635 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
636 /// [clang] '^' block-literal
638 /// constant: [C99 6.4.4]
640 /// floating-constant
641 /// enumeration-constant -> identifier
642 /// character-constant
644 /// id-expression: [C++ 5.1]
648 /// unqualified-id: [C++ 5.1]
650 /// operator-function-id
651 /// conversion-function-id
655 /// new-expression: [C++ 5.3.4]
656 /// '::'[opt] 'new' new-placement[opt] new-type-id
657 /// new-initializer[opt]
658 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
659 /// new-initializer[opt]
661 /// delete-expression: [C++ 5.3.5]
662 /// '::'[opt] 'delete' cast-expression
663 /// '::'[opt] 'delete' '[' ']' cast-expression
665 /// [GNU/Embarcadero] unary-type-trait:
666 /// '__is_arithmetic'
667 /// '__is_floating_point'
669 /// '__is_lvalue_expr'
670 /// '__is_rvalue_expr'
671 /// '__is_complete_type'
676 /// '__is_lvalue_reference'
677 /// '__is_rvalue_reference'
678 /// '__is_fundamental'
683 /// '__is_member_object_pointer'
684 /// '__is_member_function_pointer'
685 /// '__is_member_pointer'
689 /// '__is_standard_layout'
693 /// [GNU] unary-type-trait:
694 /// '__has_nothrow_assign'
695 /// '__has_nothrow_copy'
696 /// '__has_nothrow_constructor'
697 /// '__has_trivial_assign' [TODO]
698 /// '__has_trivial_copy' [TODO]
699 /// '__has_trivial_constructor'
700 /// '__has_trivial_destructor'
701 /// '__has_virtual_destructor'
702 /// '__is_abstract' [TODO]
704 /// '__is_empty' [TODO]
708 /// '__is_polymorphic'
709 /// '__is_sealed' [MS]
713 /// [Clang] unary-type-trait:
715 /// '__trivially_copyable'
717 /// binary-type-trait:
718 /// [GNU] '__is_base_of'
719 /// [MS] '__is_convertible_to'
720 /// '__is_convertible'
723 /// [Embarcadero] array-type-trait:
727 /// [Embarcadero] expression-trait:
728 /// '__is_lvalue_expr'
729 /// '__is_rvalue_expr'
732 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
733 bool isAddressOfOperand,
735 TypeCastState isTypeCast,
736 bool isVectorLiteral) {
738 tok::TokenKind SavedKind = Tok.getKind();
741 // This handles all of cast-expression, unary-expression, postfix-expression,
742 // and primary-expression. We handle them together like this for efficiency
743 // and to simplify handling of an expression starting with a '(' token: which
744 // may be one of a parenthesized expression, cast-expression, compound literal
745 // expression, or statement expression.
747 // If the parsed tokens consist of a primary-expression, the cases below
748 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
749 // to handle the postfix expression suffixes. Cases that cannot be followed
750 // by postfix exprs should return without invoking
751 // ParsePostfixExpressionSuffix.
754 // If this expression is limited to being a unary-expression, the parent can
755 // not start a cast expression.
756 ParenParseOption ParenExprType =
757 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
760 SourceLocation RParenLoc;
761 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
762 isTypeCast == IsTypeCast, CastTy, RParenLoc);
767 switch (ParenExprType) {
768 case SimpleExpr: break; // Nothing else to do.
769 case CompoundStmt: break; // Nothing else to do.
770 case CompoundLiteral:
771 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
772 // postfix-expression exist, parse them now.
775 // We have parsed the cast-expression and no postfix-expr pieces are
783 // primary-expression
784 case tok::numeric_constant:
785 // constant: integer-constant
786 // constant: floating-constant
788 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
794 return ParseCXXBoolLiteral();
796 case tok::kw___objc_yes:
797 case tok::kw___objc_no:
798 return ParseObjCBoolLiteral();
800 case tok::kw_nullptr:
801 Diag(Tok, diag::warn_cxx98_compat_nullptr);
802 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
804 case tok::annot_primary_expr:
805 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
806 Res = getExprAnnotation(Tok);
810 case tok::kw___super:
811 case tok::kw_decltype:
812 // Annotate the token and tail recurse.
813 if (TryAnnotateTypeOrScopeToken())
815 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
816 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
818 case tok::identifier: { // primary-expression: identifier
819 // unqualified-id: identifier
820 // constant: enumeration-constant
821 // Turn a potentially qualified name into a annot_typename or
822 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
823 if (getLangOpts().CPlusPlus) {
824 // Avoid the unnecessary parse-time lookup in the common case
825 // where the syntax forbids a type.
826 const Token &Next = NextToken();
828 // If this identifier was reverted from a token ID, and the next token
829 // is a parenthesis, this is likely to be a use of a type trait. Check
831 if (Next.is(tok::l_paren) &&
832 Tok.is(tok::identifier) &&
833 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
834 IdentifierInfo *II = Tok.getIdentifierInfo();
835 // Build up the mapping of revertible type traits, for future use.
836 if (RevertibleTypeTraits.empty()) {
837 #define RTT_JOIN(X,Y) X##Y
838 #define REVERTIBLE_TYPE_TRAIT(Name) \
839 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
840 = RTT_JOIN(tok::kw_,Name)
842 REVERTIBLE_TYPE_TRAIT(__is_abstract);
843 REVERTIBLE_TYPE_TRAIT(__is_aggregate);
844 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
845 REVERTIBLE_TYPE_TRAIT(__is_array);
846 REVERTIBLE_TYPE_TRAIT(__is_assignable);
847 REVERTIBLE_TYPE_TRAIT(__is_base_of);
848 REVERTIBLE_TYPE_TRAIT(__is_class);
849 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
850 REVERTIBLE_TYPE_TRAIT(__is_compound);
851 REVERTIBLE_TYPE_TRAIT(__is_const);
852 REVERTIBLE_TYPE_TRAIT(__is_constructible);
853 REVERTIBLE_TYPE_TRAIT(__is_convertible);
854 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
855 REVERTIBLE_TYPE_TRAIT(__is_destructible);
856 REVERTIBLE_TYPE_TRAIT(__is_empty);
857 REVERTIBLE_TYPE_TRAIT(__is_enum);
858 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
859 REVERTIBLE_TYPE_TRAIT(__is_final);
860 REVERTIBLE_TYPE_TRAIT(__is_function);
861 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
862 REVERTIBLE_TYPE_TRAIT(__is_integral);
863 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
864 REVERTIBLE_TYPE_TRAIT(__is_literal);
865 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
866 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
867 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
868 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
869 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
870 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
871 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
872 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
873 REVERTIBLE_TYPE_TRAIT(__is_object);
874 REVERTIBLE_TYPE_TRAIT(__is_pod);
875 REVERTIBLE_TYPE_TRAIT(__is_pointer);
876 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
877 REVERTIBLE_TYPE_TRAIT(__is_reference);
878 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
879 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
880 REVERTIBLE_TYPE_TRAIT(__is_same);
881 REVERTIBLE_TYPE_TRAIT(__is_scalar);
882 REVERTIBLE_TYPE_TRAIT(__is_sealed);
883 REVERTIBLE_TYPE_TRAIT(__is_signed);
884 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
885 REVERTIBLE_TYPE_TRAIT(__is_trivial);
886 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
887 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
888 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
889 REVERTIBLE_TYPE_TRAIT(__is_union);
890 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
891 REVERTIBLE_TYPE_TRAIT(__is_void);
892 REVERTIBLE_TYPE_TRAIT(__is_volatile);
893 #undef REVERTIBLE_TYPE_TRAIT
897 // If we find that this is in fact the name of a type trait,
898 // update the token kind in place and parse again to treat it as
899 // the appropriate kind of type trait.
900 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
901 = RevertibleTypeTraits.find(II);
902 if (Known != RevertibleTypeTraits.end()) {
903 Tok.setKind(Known->second);
904 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
905 NotCastExpr, isTypeCast);
909 if ((!ColonIsSacred && Next.is(tok::colon)) ||
910 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
912 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
913 if (TryAnnotateTypeOrScopeToken())
915 if (!Tok.is(tok::identifier))
916 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
920 // Consume the identifier so that we can see if it is followed by a '(' or
922 IdentifierInfo &II = *Tok.getIdentifierInfo();
923 SourceLocation ILoc = ConsumeToken();
925 // Support 'Class.property' and 'super.property' notation.
926 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
927 (Actions.getTypeName(II, ILoc, getCurScope()) ||
928 // Allow the base to be 'super' if in an objc-method.
929 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
932 if (Tok.is(tok::code_completion) && &II != Ident_super) {
933 Actions.CodeCompleteObjCClassPropertyRefExpr(
934 getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
938 // Allow either an identifier or the keyword 'class' (in C++).
939 if (Tok.isNot(tok::identifier) &&
940 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
941 Diag(Tok, diag::err_expected_property_name);
944 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
945 SourceLocation PropertyLoc = ConsumeToken();
947 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
952 // In an Objective-C method, if we have "super" followed by an identifier,
953 // the token sequence is ill-formed. However, if there's a ':' or ']' after
954 // that identifier, this is probably a message send with a missing open
955 // bracket. Treat it as such.
956 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
957 getCurScope()->isInObjcMethodScope() &&
958 ((Tok.is(tok::identifier) &&
959 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
960 Tok.is(tok::code_completion))) {
961 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
966 // If we have an Objective-C class name followed by an identifier
967 // and either ':' or ']', this is an Objective-C class message
968 // send that's missing the opening '['. Recovery
969 // appropriately. Also take this path if we're performing code
970 // completion after an Objective-C class name.
971 if (getLangOpts().ObjC1 &&
972 ((Tok.is(tok::identifier) && !InMessageExpression) ||
973 Tok.is(tok::code_completion))) {
974 const Token& Next = NextToken();
975 if (Tok.is(tok::code_completion) ||
976 Next.is(tok::colon) || Next.is(tok::r_square))
977 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
978 if (Typ.get()->isObjCObjectOrInterfaceType()) {
979 // Fake up a Declarator to use with ActOnTypeName.
980 DeclSpec DS(AttrFactory);
981 DS.SetRangeStart(ILoc);
982 DS.SetRangeEnd(ILoc);
983 const char *PrevSpec = nullptr;
985 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
986 Actions.getASTContext().getPrintingPolicy());
988 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
989 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
994 Res = ParseObjCMessageExpressionBody(SourceLocation(),
1001 // Make sure to pass down the right value for isAddressOfOperand.
1002 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
1003 isAddressOfOperand = false;
1005 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1006 // need to know whether or not this identifier is a function designator or
1009 CXXScopeSpec ScopeSpec;
1010 SourceLocation TemplateKWLoc;
1012 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
1013 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
1014 Validator->IsAddressOfOperand = isAddressOfOperand;
1015 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1016 Validator->WantExpressionKeywords = false;
1017 Validator->WantRemainingKeywords = false;
1019 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
1021 Name.setIdentifier(&II, ILoc);
1022 Res = Actions.ActOnIdExpression(
1023 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1024 isAddressOfOperand, std::move(Validator),
1025 /*IsInlineAsmIdentifier=*/false,
1026 Tok.is(tok::r_paren) ? nullptr : &Replacement);
1027 if (!Res.isInvalid() && !Res.get()) {
1028 UnconsumeToken(Replacement);
1029 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1030 NotCastExpr, isTypeCast);
1034 case tok::char_constant: // constant: character-constant
1035 case tok::wide_char_constant:
1036 case tok::utf8_char_constant:
1037 case tok::utf16_char_constant:
1038 case tok::utf32_char_constant:
1039 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1042 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
1043 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
1044 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
1045 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
1046 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
1047 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1048 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1051 case tok::string_literal: // primary-expression: string-literal
1052 case tok::wide_string_literal:
1053 case tok::utf8_string_literal:
1054 case tok::utf16_string_literal:
1055 case tok::utf32_string_literal:
1056 Res = ParseStringLiteralExpression(true);
1058 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1059 Res = ParseGenericSelectionExpression();
1061 case tok::kw___builtin_available:
1062 return ParseAvailabilityCheckExpr(Tok.getLocation());
1063 case tok::kw___builtin_va_arg:
1064 case tok::kw___builtin_offsetof:
1065 case tok::kw___builtin_choose_expr:
1066 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1067 case tok::kw___builtin_convertvector:
1068 return ParseBuiltinPrimaryExpression();
1069 case tok::kw___null:
1070 return Actions.ActOnGNUNullExpr(ConsumeToken());
1072 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1073 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1074 // C++ [expr.unary] has:
1075 // unary-expression:
1076 // ++ cast-expression
1077 // -- cast-expression
1078 Token SavedTok = Tok;
1080 // One special case is implicitly handled here: if the preceding tokens are
1081 // an ambiguous cast expression, such as "(T())++", then we recurse to
1082 // determine whether the '++' is prefix or postfix.
1083 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1084 /*isAddressOfOperand*/false, NotCastExpr,
1087 // If we return with NotCastExpr = true, we must not consume any tokens,
1088 // so put the token back where we found it.
1089 assert(Res.isInvalid());
1090 UnconsumeToken(SavedTok);
1093 if (!Res.isInvalid())
1094 Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1095 SavedKind, Res.get());
1098 case tok::amp: { // unary-expression: '&' cast-expression
1099 // Special treatment because of member pointers
1100 SourceLocation SavedLoc = ConsumeToken();
1101 Res = ParseCastExpression(false, true);
1102 if (!Res.isInvalid())
1103 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1107 case tok::star: // unary-expression: '*' cast-expression
1108 case tok::plus: // unary-expression: '+' cast-expression
1109 case tok::minus: // unary-expression: '-' cast-expression
1110 case tok::tilde: // unary-expression: '~' cast-expression
1111 case tok::exclaim: // unary-expression: '!' cast-expression
1112 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1113 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1114 SourceLocation SavedLoc = ConsumeToken();
1115 Res = ParseCastExpression(false);
1116 if (!Res.isInvalid())
1117 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1121 case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1122 SourceLocation CoawaitLoc = ConsumeToken();
1123 Res = ParseCastExpression(false);
1124 if (!Res.isInvalid())
1125 Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1129 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1130 // __extension__ silences extension warnings in the subexpression.
1131 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1132 SourceLocation SavedLoc = ConsumeToken();
1133 Res = ParseCastExpression(false);
1134 if (!Res.isInvalid())
1135 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1138 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1139 if (!getLangOpts().C11)
1140 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1142 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1143 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1144 // unary-expression: '__alignof' '(' type-name ')'
1145 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1146 // unary-expression: 'sizeof' '(' type-name ')'
1147 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1148 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1149 case tok::kw___builtin_omp_required_simd_align:
1150 return ParseUnaryExprOrTypeTraitExpression();
1151 case tok::ampamp: { // unary-expression: '&&' identifier
1152 SourceLocation AmpAmpLoc = ConsumeToken();
1153 if (Tok.isNot(tok::identifier))
1154 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1156 if (getCurScope()->getFnParent() == nullptr)
1157 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1159 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1160 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1162 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1166 case tok::kw_const_cast:
1167 case tok::kw_dynamic_cast:
1168 case tok::kw_reinterpret_cast:
1169 case tok::kw_static_cast:
1170 Res = ParseCXXCasts();
1172 case tok::kw_typeid:
1173 Res = ParseCXXTypeid();
1175 case tok::kw___uuidof:
1176 Res = ParseCXXUuidof();
1179 Res = ParseCXXThis();
1182 case tok::annot_typename:
1183 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1184 ParsedType Type = getTypeAnnotation(Tok);
1186 // Fake up a Declarator to use with ActOnTypeName.
1187 DeclSpec DS(AttrFactory);
1188 DS.SetRangeStart(Tok.getLocation());
1189 DS.SetRangeEnd(Tok.getLastLoc());
1191 const char *PrevSpec = nullptr;
1193 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1194 PrevSpec, DiagID, Type,
1195 Actions.getASTContext().getPrintingPolicy());
1197 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1198 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1203 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1209 case tok::annot_decltype:
1211 case tok::kw_wchar_t:
1212 case tok::kw_char16_t:
1213 case tok::kw_char32_t:
1218 case tok::kw___int64:
1219 case tok::kw___int128:
1220 case tok::kw_signed:
1221 case tok::kw_unsigned:
1224 case tok::kw_double:
1225 case tok::kw___float128:
1227 case tok::kw_typename:
1228 case tok::kw_typeof:
1229 case tok::kw___vector:
1230 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1231 #include "clang/Basic/OpenCLImageTypes.def"
1233 if (!getLangOpts().CPlusPlus) {
1234 Diag(Tok, diag::err_expected_expression);
1238 if (SavedKind == tok::kw_typename) {
1239 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1240 // typename-specifier braced-init-list
1241 if (TryAnnotateTypeOrScopeToken())
1244 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1245 // We are trying to parse a simple-type-specifier but might not get such
1246 // a token after error recovery.
1250 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1251 // simple-type-specifier braced-init-list
1253 DeclSpec DS(AttrFactory);
1255 ParseCXXSimpleTypeSpecifier(DS);
1256 if (Tok.isNot(tok::l_paren) &&
1257 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1258 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1259 << DS.getSourceRange());
1261 if (Tok.is(tok::l_brace))
1262 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1264 Res = ParseCXXTypeConstructExpression(DS);
1268 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1269 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1270 // (We can end up in this situation after tentative parsing.)
1271 if (TryAnnotateTypeOrScopeToken())
1273 if (!Tok.is(tok::annot_cxxscope))
1274 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1275 NotCastExpr, isTypeCast);
1277 Token Next = NextToken();
1278 if (Next.is(tok::annot_template_id)) {
1279 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1280 if (TemplateId->Kind == TNK_Type_template) {
1281 // We have a qualified template-id that we know refers to a
1282 // type, translate it into a type and continue parsing as a
1285 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1286 /*EnteringContext=*/false);
1287 AnnotateTemplateIdTokenAsType();
1288 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1289 NotCastExpr, isTypeCast);
1293 // Parse as an id-expression.
1294 Res = ParseCXXIdExpression(isAddressOfOperand);
1298 case tok::annot_template_id: { // [C++] template-id
1299 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1300 if (TemplateId->Kind == TNK_Type_template) {
1301 // We have a template-id that we know refers to a type,
1302 // translate it into a type and continue parsing as a cast
1304 AnnotateTemplateIdTokenAsType();
1305 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1306 NotCastExpr, isTypeCast);
1309 // Fall through to treat the template-id as an id-expression.
1312 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1313 Res = ParseCXXIdExpression(isAddressOfOperand);
1316 case tok::coloncolon: {
1317 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1318 // annotates the token, tail recurse.
1319 if (TryAnnotateTypeOrScopeToken())
1321 if (!Tok.is(tok::coloncolon))
1322 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1324 // ::new -> [C++] new-expression
1325 // ::delete -> [C++] delete-expression
1326 SourceLocation CCLoc = ConsumeToken();
1327 if (Tok.is(tok::kw_new))
1328 return ParseCXXNewExpression(true, CCLoc);
1329 if (Tok.is(tok::kw_delete))
1330 return ParseCXXDeleteExpression(true, CCLoc);
1332 // This is not a type name or scope specifier, it is an invalid expression.
1333 Diag(CCLoc, diag::err_expected_expression);
1337 case tok::kw_new: // [C++] new-expression
1338 return ParseCXXNewExpression(false, Tok.getLocation());
1340 case tok::kw_delete: // [C++] delete-expression
1341 return ParseCXXDeleteExpression(false, Tok.getLocation());
1343 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1344 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1345 SourceLocation KeyLoc = ConsumeToken();
1346 BalancedDelimiterTracker T(*this, tok::l_paren);
1348 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1350 // C++11 [expr.unary.noexcept]p1:
1351 // The noexcept operator determines whether the evaluation of its operand,
1352 // which is an unevaluated operand, can throw an exception.
1353 EnterExpressionEvaluationContext Unevaluated(
1354 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1355 ExprResult Result = ParseExpression();
1359 if (!Result.isInvalid())
1360 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1361 Result.get(), T.getCloseLocation());
1365 #define TYPE_TRAIT(N,Spelling,K) \
1366 case tok::kw_##Spelling:
1367 #include "clang/Basic/TokenKinds.def"
1368 return ParseTypeTrait();
1370 case tok::kw___array_rank:
1371 case tok::kw___array_extent:
1372 return ParseArrayTypeTrait();
1374 case tok::kw___is_lvalue_expr:
1375 case tok::kw___is_rvalue_expr:
1376 return ParseExpressionTrait();
1379 SourceLocation AtLoc = ConsumeToken();
1380 return ParseObjCAtExpression(AtLoc);
1383 Res = ParseBlockLiteralExpression();
1385 case tok::code_completion: {
1386 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1391 if (getLangOpts().CPlusPlus11) {
1392 if (getLangOpts().ObjC1) {
1393 // C++11 lambda expressions and Objective-C message sends both start with a
1394 // square bracket. There are three possibilities here:
1395 // we have a valid lambda expression, we have an invalid lambda
1396 // expression, or we have something that doesn't appear to be a lambda.
1397 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1398 Res = TryParseLambdaExpression();
1399 if (!Res.isInvalid() && !Res.get())
1400 Res = ParseObjCMessageExpression();
1403 Res = ParseLambdaExpression();
1406 if (getLangOpts().ObjC1) {
1407 Res = ParseObjCMessageExpression();
1416 // Check to see whether Res is a function designator only. If it is and we
1417 // are compiling for OpenCL, we need to return an error as this implies
1418 // that the address of the function is being taken, which is illegal in CL.
1420 // These can be followed by postfix-expr pieces.
1421 Res = ParsePostfixExpressionSuffix(Res);
1422 if (getLangOpts().OpenCL)
1423 if (Expr *PostfixExpr = Res.get()) {
1424 QualType Ty = PostfixExpr->getType();
1425 if (!Ty.isNull() && Ty->isFunctionType()) {
1426 Diag(PostfixExpr->getExprLoc(),
1427 diag::err_opencl_taking_function_address_parser);
1435 /// \brief Once the leading part of a postfix-expression is parsed, this
1436 /// method parses any suffixes that apply.
1439 /// postfix-expression: [C99 6.5.2]
1440 /// primary-expression
1441 /// postfix-expression '[' expression ']'
1442 /// postfix-expression '[' braced-init-list ']'
1443 /// postfix-expression '(' argument-expression-list[opt] ')'
1444 /// postfix-expression '.' identifier
1445 /// postfix-expression '->' identifier
1446 /// postfix-expression '++'
1447 /// postfix-expression '--'
1448 /// '(' type-name ')' '{' initializer-list '}'
1449 /// '(' type-name ')' '{' initializer-list ',' '}'
1451 /// argument-expression-list: [C99 6.5.2]
1452 /// argument-expression ...[opt]
1453 /// argument-expression-list ',' assignment-expression ...[opt]
1456 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1457 // Now that the primary-expression piece of the postfix-expression has been
1458 // parsed, see if there are any postfix-expression pieces here.
1461 switch (Tok.getKind()) {
1462 case tok::code_completion:
1463 if (InMessageExpression)
1466 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1470 case tok::identifier:
1471 // If we see identifier: after an expression, and we're not already in a
1472 // message send, then this is probably a message send with a missing
1473 // opening bracket '['.
1474 if (getLangOpts().ObjC1 && !InMessageExpression &&
1475 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1476 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1477 nullptr, LHS.get());
1481 // Fall through; this isn't a message send.
1483 default: // Not a postfix-expression suffix.
1485 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1486 // If we have a array postfix expression that starts on a new line and
1487 // Objective-C is enabled, it is highly likely that the user forgot a
1488 // semicolon after the base expression and that the array postfix-expr is
1489 // actually another message send. In this case, do some look-ahead to see
1490 // if the contents of the square brackets are obviously not a valid
1491 // expression and recover by pretending there is no suffix.
1492 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1493 isSimpleObjCMessageExpression())
1496 // Reject array indices starting with a lambda-expression. '[[' is
1497 // reserved for attributes.
1498 if (CheckProhibitedCXX11Attribute()) {
1499 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1503 BalancedDelimiterTracker T(*this, tok::l_square);
1505 Loc = T.getOpenLocation();
1506 ExprResult Idx, Length;
1507 SourceLocation ColonLoc;
1508 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1509 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1510 Idx = ParseBraceInitializer();
1511 } else if (getLangOpts().OpenMP) {
1512 ColonProtectionRAIIObject RAII(*this);
1513 // Parse [: or [ expr or [ expr :
1514 if (!Tok.is(tok::colon)) {
1516 Idx = ParseExpression();
1518 if (Tok.is(tok::colon)) {
1520 ColonLoc = ConsumeToken();
1521 if (Tok.isNot(tok::r_square))
1522 Length = ParseExpression();
1525 Idx = ParseExpression();
1527 SourceLocation RLoc = Tok.getLocation();
1529 ExprResult OrigLHS = LHS;
1530 if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1531 Tok.is(tok::r_square)) {
1532 if (ColonLoc.isValid()) {
1533 LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1534 ColonLoc, Length.get(), RLoc);
1536 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1542 if (LHS.isInvalid()) {
1543 (void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
1544 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1545 (void)Actions.CorrectDelayedTyposInExpr(Length);
1555 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1556 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1557 // '(' argument-expression-list[opt] ')'
1558 tok::TokenKind OpKind = Tok.getKind();
1559 InMessageExpressionRAIIObject InMessage(*this, false);
1561 Expr *ExecConfig = nullptr;
1563 BalancedDelimiterTracker PT(*this, tok::l_paren);
1565 if (OpKind == tok::lesslessless) {
1566 ExprVector ExecConfigExprs;
1567 CommaLocsTy ExecConfigCommaLocs;
1568 SourceLocation OpenLoc = ConsumeToken();
1570 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1571 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1575 SourceLocation CloseLoc;
1576 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1577 } else if (LHS.isInvalid()) {
1578 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1580 // There was an error closing the brackets
1581 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1582 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1583 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1587 if (!LHS.isInvalid()) {
1588 if (ExpectAndConsume(tok::l_paren))
1591 Loc = PrevTokLocation;
1594 if (!LHS.isInvalid()) {
1595 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1599 if (ECResult.isInvalid())
1602 ExecConfig = ECResult.get();
1606 Loc = PT.getOpenLocation();
1609 ExprVector ArgExprs;
1610 CommaLocsTy CommaLocs;
1612 if (Tok.is(tok::code_completion)) {
1613 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1618 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1619 if (Tok.isNot(tok::r_paren)) {
1620 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1621 Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1623 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1625 } else if (LHS.isInvalid()) {
1626 for (auto &E : ArgExprs)
1627 Actions.CorrectDelayedTyposInExpr(E);
1633 if (LHS.isInvalid()) {
1634 SkipUntil(tok::r_paren, StopAtSemi);
1635 } else if (Tok.isNot(tok::r_paren)) {
1636 bool HadDelayedTypo = false;
1637 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1638 HadDelayedTypo = true;
1639 for (auto &E : ArgExprs)
1640 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1641 HadDelayedTypo = true;
1642 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1643 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1644 // the unmatched l_paren.
1646 SkipUntil(tok::r_paren, StopAtSemi);
1651 assert((ArgExprs.size() == 0 ||
1652 ArgExprs.size()-1 == CommaLocs.size())&&
1653 "Unexpected number of commas!");
1654 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1655 ArgExprs, Tok.getLocation(),
1664 // postfix-expression: p-e '->' template[opt] id-expression
1665 // postfix-expression: p-e '.' template[opt] id-expression
1666 tok::TokenKind OpKind = Tok.getKind();
1667 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1670 ParsedType ObjectType;
1671 bool MayBePseudoDestructor = false;
1672 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1673 Expr *Base = LHS.get();
1674 const Type* BaseType = Base->getType().getTypePtrOrNull();
1675 if (BaseType && Tok.is(tok::l_paren) &&
1676 (BaseType->isFunctionType() ||
1677 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1678 Diag(OpLoc, diag::err_function_is_not_record)
1679 << OpKind << Base->getSourceRange()
1680 << FixItHint::CreateRemoval(OpLoc);
1681 return ParsePostfixExpressionSuffix(Base);
1684 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1685 OpLoc, OpKind, ObjectType,
1686 MayBePseudoDestructor);
1687 if (LHS.isInvalid())
1690 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1691 /*EnteringContext=*/false,
1692 &MayBePseudoDestructor);
1693 if (SS.isNotEmpty())
1694 ObjectType = nullptr;
1697 if (Tok.is(tok::code_completion)) {
1698 // Code completion for a member access expression.
1699 if (Expr *Base = LHS.get())
1700 Actions.CodeCompleteMemberReferenceExpr(
1701 getCurScope(), Base, OpLoc, OpKind == tok::arrow,
1702 ExprStatementTokLoc == Base->getLocStart());
1708 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1709 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1714 // Either the action has told us that this cannot be a
1715 // pseudo-destructor expression (based on the type of base
1716 // expression), or we didn't see a '~' in the right place. We
1717 // can still parse a destructor name here, but in that case it
1718 // names a real destructor.
1719 // Allow explicit constructor calls in Microsoft mode.
1720 // FIXME: Add support for explicit call of template constructor.
1721 SourceLocation TemplateKWLoc;
1723 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1724 Tok.is(tok::kw_class)) {
1726 // After a '.' in a member access expression, treat the keyword
1727 // 'class' as if it were an identifier.
1729 // This hack allows property access to the 'class' method because it is
1730 // such a common method name. For other C++ keywords that are
1731 // Objective-C method names, one must use the message send syntax.
1732 IdentifierInfo *Id = Tok.getIdentifierInfo();
1733 SourceLocation Loc = ConsumeToken();
1734 Name.setIdentifier(Id, Loc);
1735 } else if (ParseUnqualifiedId(SS,
1736 /*EnteringContext=*/false,
1737 /*AllowDestructorName=*/true,
1738 /*AllowConstructorName=*/
1739 getLangOpts().MicrosoftExt,
1740 /*AllowDeductionGuide=*/false,
1741 ObjectType, TemplateKWLoc, Name)) {
1742 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1746 if (!LHS.isInvalid())
1747 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1748 OpKind, SS, TemplateKWLoc, Name,
1749 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1753 case tok::plusplus: // postfix-expression: postfix-expression '++'
1754 case tok::minusminus: // postfix-expression: postfix-expression '--'
1755 if (!LHS.isInvalid()) {
1756 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1757 Tok.getKind(), LHS.get());
1765 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1766 /// vec_step and we are at the start of an expression or a parenthesized
1767 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1768 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1771 /// unary-expression: [C99 6.5.3]
1772 /// 'sizeof' unary-expression
1773 /// 'sizeof' '(' type-name ')'
1774 /// [GNU] '__alignof' unary-expression
1775 /// [GNU] '__alignof' '(' type-name ')'
1776 /// [C11] '_Alignof' '(' type-name ')'
1777 /// [C++0x] 'alignof' '(' type-id ')'
1779 /// [GNU] typeof-specifier:
1780 /// typeof ( expressions )
1781 /// typeof ( type-name )
1782 /// [GNU/C++] typeof unary-expression
1784 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1785 /// vec_step ( expressions )
1786 /// vec_step ( type-name )
1789 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1792 SourceRange &CastRange) {
1794 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1795 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1796 tok::kw___builtin_omp_required_simd_align) &&
1797 "Not a typeof/sizeof/alignof/vec_step expression!");
1801 // If the operand doesn't start with an '(', it must be an expression.
1802 if (Tok.isNot(tok::l_paren)) {
1803 // If construct allows a form without parenthesis, user may forget to put
1804 // pathenthesis around type name.
1805 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1806 tok::kw__Alignof)) {
1807 if (isTypeIdUnambiguously()) {
1808 DeclSpec DS(AttrFactory);
1809 ParseSpecifierQualifierList(DS);
1810 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1811 ParseDeclarator(DeclaratorInfo);
1813 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1814 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1815 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1817 << FixItHint::CreateInsertion(LParenLoc, "(")
1818 << FixItHint::CreateInsertion(RParenLoc, ")");
1825 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1826 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1831 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1833 // If it starts with a '(', we know that it is either a parenthesized
1834 // type-name, or it is a unary-expression that starts with a compound
1835 // literal, or starts with a primary-expression that is a parenthesized
1837 ParenParseOption ExprType = CastExpr;
1838 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1840 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1841 false, CastTy, RParenLoc);
1842 CastRange = SourceRange(LParenLoc, RParenLoc);
1844 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1846 if (ExprType == CastExpr) {
1851 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1852 // GNU typeof in C requires the expression to be parenthesized. Not so for
1853 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1854 // the start of a unary-expression, but doesn't include any postfix
1855 // pieces. Parse these now if present.
1856 if (!Operand.isInvalid())
1857 Operand = ParsePostfixExpressionSuffix(Operand.get());
1861 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1867 /// \brief Parse a sizeof or alignof expression.
1870 /// unary-expression: [C99 6.5.3]
1871 /// 'sizeof' unary-expression
1872 /// 'sizeof' '(' type-name ')'
1873 /// [C++11] 'sizeof' '...' '(' identifier ')'
1874 /// [GNU] '__alignof' unary-expression
1875 /// [GNU] '__alignof' '(' type-name ')'
1876 /// [C11] '_Alignof' '(' type-name ')'
1877 /// [C++11] 'alignof' '(' type-id ')'
1879 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1880 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1881 tok::kw__Alignof, tok::kw_vec_step,
1882 tok::kw___builtin_omp_required_simd_align) &&
1883 "Not a sizeof/alignof/vec_step expression!");
1887 // [C++11] 'sizeof' '...' '(' identifier ')'
1888 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1889 SourceLocation EllipsisLoc = ConsumeToken();
1890 SourceLocation LParenLoc, RParenLoc;
1891 IdentifierInfo *Name = nullptr;
1892 SourceLocation NameLoc;
1893 if (Tok.is(tok::l_paren)) {
1894 BalancedDelimiterTracker T(*this, tok::l_paren);
1896 LParenLoc = T.getOpenLocation();
1897 if (Tok.is(tok::identifier)) {
1898 Name = Tok.getIdentifierInfo();
1899 NameLoc = ConsumeToken();
1901 RParenLoc = T.getCloseLocation();
1902 if (RParenLoc.isInvalid())
1903 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1905 Diag(Tok, diag::err_expected_parameter_pack);
1906 SkipUntil(tok::r_paren, StopAtSemi);
1908 } else if (Tok.is(tok::identifier)) {
1909 Name = Tok.getIdentifierInfo();
1910 NameLoc = ConsumeToken();
1911 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1912 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1913 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1915 << FixItHint::CreateInsertion(LParenLoc, "(")
1916 << FixItHint::CreateInsertion(RParenLoc, ")");
1918 Diag(Tok, diag::err_sizeof_parameter_pack);
1924 EnterExpressionEvaluationContext Unevaluated(
1925 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1926 Sema::ReuseLambdaContextDecl);
1928 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1929 OpTok.getLocation(),
1934 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1935 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1937 EnterExpressionEvaluationContext Unevaluated(
1938 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1939 Sema::ReuseLambdaContextDecl);
1943 SourceRange CastRange;
1944 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1949 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1950 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1951 ExprKind = UETT_AlignOf;
1952 else if (OpTok.is(tok::kw_vec_step))
1953 ExprKind = UETT_VecStep;
1954 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
1955 ExprKind = UETT_OpenMPRequiredSimdAlign;
1958 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1961 CastTy.getAsOpaquePtr(),
1964 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1965 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1967 // If we get here, the operand to the sizeof/alignof was an expresion.
1968 if (!Operand.isInvalid())
1969 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1977 /// ParseBuiltinPrimaryExpression
1980 /// primary-expression: [C99 6.5.1]
1981 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1982 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1983 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1985 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1986 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1988 /// [GNU] offsetof-member-designator:
1989 /// [GNU] identifier
1990 /// [GNU] offsetof-member-designator '.' identifier
1991 /// [GNU] offsetof-member-designator '[' expression ']'
1993 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1995 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1997 tok::TokenKind T = Tok.getKind();
1998 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
2000 // All of these start with an open paren.
2001 if (Tok.isNot(tok::l_paren))
2002 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2005 BalancedDelimiterTracker PT(*this, tok::l_paren);
2011 default: llvm_unreachable("Not a builtin primary expression!");
2012 case tok::kw___builtin_va_arg: {
2013 ExprResult Expr(ParseAssignmentExpression());
2015 if (ExpectAndConsume(tok::comma)) {
2016 SkipUntil(tok::r_paren, StopAtSemi);
2020 TypeResult Ty = ParseTypeName();
2022 if (Tok.isNot(tok::r_paren)) {
2023 Diag(Tok, diag::err_expected) << tok::r_paren;
2027 if (Expr.isInvalid() || Ty.isInvalid())
2030 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2033 case tok::kw___builtin_offsetof: {
2034 SourceLocation TypeLoc = Tok.getLocation();
2035 TypeResult Ty = ParseTypeName();
2036 if (Ty.isInvalid()) {
2037 SkipUntil(tok::r_paren, StopAtSemi);
2041 if (ExpectAndConsume(tok::comma)) {
2042 SkipUntil(tok::r_paren, StopAtSemi);
2046 // We must have at least one identifier here.
2047 if (Tok.isNot(tok::identifier)) {
2048 Diag(Tok, diag::err_expected) << tok::identifier;
2049 SkipUntil(tok::r_paren, StopAtSemi);
2053 // Keep track of the various subcomponents we see.
2054 SmallVector<Sema::OffsetOfComponent, 4> Comps;
2056 Comps.push_back(Sema::OffsetOfComponent());
2057 Comps.back().isBrackets = false;
2058 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2059 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2061 // FIXME: This loop leaks the index expressions on error.
2063 if (Tok.is(tok::period)) {
2064 // offsetof-member-designator: offsetof-member-designator '.' identifier
2065 Comps.push_back(Sema::OffsetOfComponent());
2066 Comps.back().isBrackets = false;
2067 Comps.back().LocStart = ConsumeToken();
2069 if (Tok.isNot(tok::identifier)) {
2070 Diag(Tok, diag::err_expected) << tok::identifier;
2071 SkipUntil(tok::r_paren, StopAtSemi);
2074 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2075 Comps.back().LocEnd = ConsumeToken();
2077 } else if (Tok.is(tok::l_square)) {
2078 if (CheckProhibitedCXX11Attribute())
2081 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2082 Comps.push_back(Sema::OffsetOfComponent());
2083 Comps.back().isBrackets = true;
2084 BalancedDelimiterTracker ST(*this, tok::l_square);
2086 Comps.back().LocStart = ST.getOpenLocation();
2087 Res = ParseExpression();
2088 if (Res.isInvalid()) {
2089 SkipUntil(tok::r_paren, StopAtSemi);
2092 Comps.back().U.E = Res.get();
2095 Comps.back().LocEnd = ST.getCloseLocation();
2097 if (Tok.isNot(tok::r_paren)) {
2100 } else if (Ty.isInvalid()) {
2104 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2106 PT.getCloseLocation());
2113 case tok::kw___builtin_choose_expr: {
2114 ExprResult Cond(ParseAssignmentExpression());
2115 if (Cond.isInvalid()) {
2116 SkipUntil(tok::r_paren, StopAtSemi);
2119 if (ExpectAndConsume(tok::comma)) {
2120 SkipUntil(tok::r_paren, StopAtSemi);
2124 ExprResult Expr1(ParseAssignmentExpression());
2125 if (Expr1.isInvalid()) {
2126 SkipUntil(tok::r_paren, StopAtSemi);
2129 if (ExpectAndConsume(tok::comma)) {
2130 SkipUntil(tok::r_paren, StopAtSemi);
2134 ExprResult Expr2(ParseAssignmentExpression());
2135 if (Expr2.isInvalid()) {
2136 SkipUntil(tok::r_paren, StopAtSemi);
2139 if (Tok.isNot(tok::r_paren)) {
2140 Diag(Tok, diag::err_expected) << tok::r_paren;
2143 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2144 Expr2.get(), ConsumeParen());
2147 case tok::kw___builtin_astype: {
2148 // The first argument is an expression to be converted, followed by a comma.
2149 ExprResult Expr(ParseAssignmentExpression());
2150 if (Expr.isInvalid()) {
2151 SkipUntil(tok::r_paren, StopAtSemi);
2155 if (ExpectAndConsume(tok::comma)) {
2156 SkipUntil(tok::r_paren, StopAtSemi);
2160 // Second argument is the type to bitcast to.
2161 TypeResult DestTy = ParseTypeName();
2162 if (DestTy.isInvalid())
2165 // Attempt to consume the r-paren.
2166 if (Tok.isNot(tok::r_paren)) {
2167 Diag(Tok, diag::err_expected) << tok::r_paren;
2168 SkipUntil(tok::r_paren, StopAtSemi);
2172 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2176 case tok::kw___builtin_convertvector: {
2177 // The first argument is an expression to be converted, followed by a comma.
2178 ExprResult Expr(ParseAssignmentExpression());
2179 if (Expr.isInvalid()) {
2180 SkipUntil(tok::r_paren, StopAtSemi);
2184 if (ExpectAndConsume(tok::comma)) {
2185 SkipUntil(tok::r_paren, StopAtSemi);
2189 // Second argument is the type to bitcast to.
2190 TypeResult DestTy = ParseTypeName();
2191 if (DestTy.isInvalid())
2194 // Attempt to consume the r-paren.
2195 if (Tok.isNot(tok::r_paren)) {
2196 Diag(Tok, diag::err_expected) << tok::r_paren;
2197 SkipUntil(tok::r_paren, StopAtSemi);
2201 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2207 if (Res.isInvalid())
2210 // These can be followed by postfix-expr pieces because they are
2211 // primary-expressions.
2212 return ParsePostfixExpressionSuffix(Res.get());
2215 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2216 /// based on what is allowed by ExprType. The actual thing parsed is returned
2217 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2218 /// not the parsed cast-expression.
2221 /// primary-expression: [C99 6.5.1]
2222 /// '(' expression ')'
2223 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2224 /// postfix-expression: [C99 6.5.2]
2225 /// '(' type-name ')' '{' initializer-list '}'
2226 /// '(' type-name ')' '{' initializer-list ',' '}'
2227 /// cast-expression: [C99 6.5.4]
2228 /// '(' type-name ')' cast-expression
2229 /// [ARC] bridged-cast-expression
2230 /// [ARC] bridged-cast-expression:
2231 /// (__bridge type-name) cast-expression
2232 /// (__bridge_transfer type-name) cast-expression
2233 /// (__bridge_retained type-name) cast-expression
2234 /// fold-expression: [C++1z]
2235 /// '(' cast-expression fold-operator '...' ')'
2236 /// '(' '...' fold-operator cast-expression ')'
2237 /// '(' cast-expression fold-operator '...'
2238 /// fold-operator cast-expression ')'
2241 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2242 bool isTypeCast, ParsedType &CastTy,
2243 SourceLocation &RParenLoc) {
2244 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2245 ColonProtectionRAIIObject ColonProtection(*this, false);
2246 BalancedDelimiterTracker T(*this, tok::l_paren);
2247 if (T.consumeOpen())
2249 SourceLocation OpenLoc = T.getOpenLocation();
2251 ExprResult Result(true);
2252 bool isAmbiguousTypeId;
2255 if (Tok.is(tok::code_completion)) {
2256 Actions.CodeCompleteOrdinaryName(getCurScope(),
2257 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2258 : Sema::PCC_Expression);
2263 // Diagnose use of bridge casts in non-arc mode.
2264 bool BridgeCast = (getLangOpts().ObjC2 &&
2265 Tok.isOneOf(tok::kw___bridge,
2266 tok::kw___bridge_transfer,
2267 tok::kw___bridge_retained,
2268 tok::kw___bridge_retain));
2269 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2270 if (!TryConsumeToken(tok::kw___bridge)) {
2271 StringRef BridgeCastName = Tok.getName();
2272 SourceLocation BridgeKeywordLoc = ConsumeToken();
2273 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2274 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2276 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2281 // None of these cases should fall through with an invalid Result
2282 // unless they've already reported an error.
2283 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2284 Diag(Tok, diag::ext_gnu_statement_expr);
2286 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2287 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2289 // Find the nearest non-record decl context. Variables declared in a
2290 // statement expression behave as if they were declared in the enclosing
2291 // function, block, or other code construct.
2292 DeclContext *CodeDC = Actions.CurContext;
2293 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2294 CodeDC = CodeDC->getParent();
2295 assert(CodeDC && !CodeDC->isFileContext() &&
2296 "statement expr not in code context");
2298 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2300 Actions.ActOnStartStmtExpr();
2302 StmtResult Stmt(ParseCompoundStatement(true));
2303 ExprType = CompoundStmt;
2305 // If the substmt parsed correctly, build the AST node.
2306 if (!Stmt.isInvalid()) {
2307 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2309 Actions.ActOnStmtExprError();
2312 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2313 tok::TokenKind tokenKind = Tok.getKind();
2314 SourceLocation BridgeKeywordLoc = ConsumeToken();
2316 // Parse an Objective-C ARC ownership cast expression.
2317 ObjCBridgeCastKind Kind;
2318 if (tokenKind == tok::kw___bridge)
2320 else if (tokenKind == tok::kw___bridge_transfer)
2321 Kind = OBC_BridgeTransfer;
2322 else if (tokenKind == tok::kw___bridge_retained)
2323 Kind = OBC_BridgeRetained;
2325 // As a hopefully temporary workaround, allow __bridge_retain as
2326 // a synonym for __bridge_retained, but only in system headers.
2327 assert(tokenKind == tok::kw___bridge_retain);
2328 Kind = OBC_BridgeRetained;
2329 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2330 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2331 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2332 "__bridge_retained");
2335 TypeResult Ty = ParseTypeName();
2337 ColonProtection.restore();
2338 RParenLoc = T.getCloseLocation();
2339 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2341 if (Ty.isInvalid() || SubExpr.isInvalid())
2344 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2345 BridgeKeywordLoc, Ty.get(),
2346 RParenLoc, SubExpr.get());
2347 } else if (ExprType >= CompoundLiteral &&
2348 isTypeIdInParens(isAmbiguousTypeId)) {
2350 // Otherwise, this is a compound literal expression or cast expression.
2352 // In C++, if the type-id is ambiguous we disambiguate based on context.
2353 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2354 // in which case we should treat it as type-id.
2355 // if stopIfCastExpr is false, we need to determine the context past the
2356 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2357 if (isAmbiguousTypeId && !stopIfCastExpr) {
2358 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2360 RParenLoc = T.getCloseLocation();
2364 // Parse the type declarator.
2365 DeclSpec DS(AttrFactory);
2366 ParseSpecifierQualifierList(DS);
2367 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2368 ParseDeclarator(DeclaratorInfo);
2370 // If our type is followed by an identifier and either ':' or ']', then
2371 // this is probably an Objective-C message send where the leading '[' is
2372 // missing. Recover as if that were the case.
2373 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2374 !InMessageExpression && getLangOpts().ObjC1 &&
2375 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2378 InMessageExpressionRAIIObject InMessage(*this, false);
2379 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2381 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2387 ColonProtection.restore();
2388 RParenLoc = T.getCloseLocation();
2389 if (Tok.is(tok::l_brace)) {
2390 ExprType = CompoundLiteral;
2393 InMessageExpressionRAIIObject InMessage(*this, false);
2394 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2396 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2399 if (Tok.is(tok::l_paren)) {
2400 // This could be OpenCL vector Literals
2401 if (getLangOpts().OpenCL)
2405 InMessageExpressionRAIIObject InMessage(*this, false);
2406 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2412 QualType QT = Ty.get().get().getCanonicalType();
2413 if (QT->isVectorType())
2415 // We parsed '(' vector-type-name ')' followed by '('
2417 // Parse the cast-expression that follows it next.
2418 // isVectorLiteral = true will make sure we don't parse any
2419 // Postfix expression yet
2420 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2421 /*isAddressOfOperand=*/false,
2422 /*isTypeCast=*/IsTypeCast,
2423 /*isVectorLiteral=*/true);
2425 if (!Result.isInvalid()) {
2426 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2427 DeclaratorInfo, CastTy,
2428 RParenLoc, Result.get());
2431 // After we performed the cast we can check for postfix-expr pieces.
2432 if (!Result.isInvalid()) {
2433 Result = ParsePostfixExpressionSuffix(Result);
2441 if (ExprType == CastExpr) {
2442 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2444 if (DeclaratorInfo.isInvalidType())
2447 // Note that this doesn't parse the subsequent cast-expression, it just
2448 // returns the parsed type to the callee.
2449 if (stopIfCastExpr) {
2452 InMessageExpressionRAIIObject InMessage(*this, false);
2453 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2456 return ExprResult();
2459 // Reject the cast of super idiom in ObjC.
2460 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2461 Tok.getIdentifierInfo() == Ident_super &&
2462 getCurScope()->isInObjcMethodScope() &&
2463 GetLookAheadToken(1).isNot(tok::period)) {
2464 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2465 << SourceRange(OpenLoc, RParenLoc);
2469 // Parse the cast-expression that follows it next.
2470 // TODO: For cast expression with CastTy.
2471 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2472 /*isAddressOfOperand=*/false,
2473 /*isTypeCast=*/IsTypeCast);
2474 if (!Result.isInvalid()) {
2475 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2476 DeclaratorInfo, CastTy,
2477 RParenLoc, Result.get());
2482 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2485 } else if (Tok.is(tok::ellipsis) &&
2486 isFoldOperator(NextToken().getKind())) {
2487 return ParseFoldExpression(ExprResult(), T);
2488 } else if (isTypeCast) {
2489 // Parse the expression-list.
2490 InMessageExpressionRAIIObject InMessage(*this, false);
2492 ExprVector ArgExprs;
2493 CommaLocsTy CommaLocs;
2495 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2496 // FIXME: If we ever support comma expressions as operands to
2497 // fold-expressions, we'll need to allow multiple ArgExprs here.
2498 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2499 NextToken().is(tok::ellipsis))
2500 return ParseFoldExpression(ArgExprs[0], T);
2502 ExprType = SimpleExpr;
2503 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2507 InMessageExpressionRAIIObject InMessage(*this, false);
2509 Result = ParseExpression(MaybeTypeCast);
2510 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2511 // Correct typos in non-C++ code earlier so that implicit-cast-like
2512 // expressions are parsed correctly.
2513 Result = Actions.CorrectDelayedTyposInExpr(Result);
2515 ExprType = SimpleExpr;
2517 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2518 return ParseFoldExpression(Result, T);
2520 // Don't build a paren expression unless we actually match a ')'.
2521 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2523 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2527 if (Result.isInvalid()) {
2528 SkipUntil(tok::r_paren, StopAtSemi);
2533 RParenLoc = T.getCloseLocation();
2537 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2538 /// and we are at the left brace.
2541 /// postfix-expression: [C99 6.5.2]
2542 /// '(' type-name ')' '{' initializer-list '}'
2543 /// '(' type-name ')' '{' initializer-list ',' '}'
2546 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2547 SourceLocation LParenLoc,
2548 SourceLocation RParenLoc) {
2549 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2550 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2551 Diag(LParenLoc, diag::ext_c99_compound_literal);
2552 ExprResult Result = ParseInitializer();
2553 if (!Result.isInvalid() && Ty)
2554 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2558 /// ParseStringLiteralExpression - This handles the various token types that
2559 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2560 /// translation phase #6].
2563 /// primary-expression: [C99 6.5.1]
2566 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2567 assert(isTokenStringLiteral() && "Not a string literal!");
2569 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2570 // considered to be strings for concatenation purposes.
2571 SmallVector<Token, 4> StringToks;
2574 StringToks.push_back(Tok);
2575 ConsumeStringToken();
2576 } while (isTokenStringLiteral());
2578 // Pass the set of string tokens, ready for concatenation, to the actions.
2579 return Actions.ActOnStringLiteral(StringToks,
2580 AllowUserDefinedLiteral ? getCurScope()
2584 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2588 /// generic-selection:
2589 /// _Generic ( assignment-expression , generic-assoc-list )
2590 /// generic-assoc-list:
2591 /// generic-association
2592 /// generic-assoc-list , generic-association
2593 /// generic-association:
2594 /// type-name : assignment-expression
2595 /// default : assignment-expression
2597 ExprResult Parser::ParseGenericSelectionExpression() {
2598 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2599 SourceLocation KeyLoc = ConsumeToken();
2601 if (!getLangOpts().C11)
2602 Diag(KeyLoc, diag::ext_c11_generic_selection);
2604 BalancedDelimiterTracker T(*this, tok::l_paren);
2605 if (T.expectAndConsume())
2608 ExprResult ControllingExpr;
2610 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2612 EnterExpressionEvaluationContext Unevaluated(
2613 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
2615 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2616 if (ControllingExpr.isInvalid()) {
2617 SkipUntil(tok::r_paren, StopAtSemi);
2622 if (ExpectAndConsume(tok::comma)) {
2623 SkipUntil(tok::r_paren, StopAtSemi);
2627 SourceLocation DefaultLoc;
2632 if (Tok.is(tok::kw_default)) {
2633 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2634 // generic association."
2635 if (!DefaultLoc.isInvalid()) {
2636 Diag(Tok, diag::err_duplicate_default_assoc);
2637 Diag(DefaultLoc, diag::note_previous_default_assoc);
2638 SkipUntil(tok::r_paren, StopAtSemi);
2641 DefaultLoc = ConsumeToken();
2644 ColonProtectionRAIIObject X(*this);
2645 TypeResult TR = ParseTypeName();
2646 if (TR.isInvalid()) {
2647 SkipUntil(tok::r_paren, StopAtSemi);
2652 Types.push_back(Ty);
2654 if (ExpectAndConsume(tok::colon)) {
2655 SkipUntil(tok::r_paren, StopAtSemi);
2659 // FIXME: These expressions should be parsed in a potentially potentially
2660 // evaluated context.
2662 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2663 if (ER.isInvalid()) {
2664 SkipUntil(tok::r_paren, StopAtSemi);
2667 Exprs.push_back(ER.get());
2668 } while (TryConsumeToken(tok::comma));
2671 if (T.getCloseLocation().isInvalid())
2674 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2675 T.getCloseLocation(),
2676 ControllingExpr.get(),
2680 /// \brief Parse A C++1z fold-expression after the opening paren and optional
2681 /// left-hand-side expression.
2684 /// fold-expression:
2685 /// ( cast-expression fold-operator ... )
2686 /// ( ... fold-operator cast-expression )
2687 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2688 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2689 BalancedDelimiterTracker &T) {
2690 if (LHS.isInvalid()) {
2695 tok::TokenKind Kind = tok::unknown;
2696 SourceLocation FirstOpLoc;
2697 if (LHS.isUsable()) {
2698 Kind = Tok.getKind();
2699 assert(isFoldOperator(Kind) && "missing fold-operator");
2700 FirstOpLoc = ConsumeToken();
2703 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2704 SourceLocation EllipsisLoc = ConsumeToken();
2707 if (Tok.isNot(tok::r_paren)) {
2708 if (!isFoldOperator(Tok.getKind()))
2709 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2711 if (Kind != tok::unknown && Tok.getKind() != Kind)
2712 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2713 << SourceRange(FirstOpLoc);
2714 Kind = Tok.getKind();
2717 RHS = ParseExpression();
2718 if (RHS.isInvalid()) {
2724 Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
2725 ? diag::warn_cxx14_compat_fold_expression
2726 : diag::ext_fold_expression);
2729 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2730 EllipsisLoc, RHS.get(), T.getCloseLocation());
2733 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2736 /// argument-expression-list:
2737 /// assignment-expression
2738 /// argument-expression-list , assignment-expression
2740 /// [C++] expression-list:
2741 /// [C++] assignment-expression
2742 /// [C++] expression-list , assignment-expression
2744 /// [C++0x] expression-list:
2745 /// [C++0x] initializer-list
2747 /// [C++0x] initializer-list
2748 /// [C++0x] initializer-clause ...[opt]
2749 /// [C++0x] initializer-list , initializer-clause ...[opt]
2751 /// [C++0x] initializer-clause:
2752 /// [C++0x] assignment-expression
2753 /// [C++0x] braced-init-list
2755 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2756 SmallVectorImpl<SourceLocation> &CommaLocs,
2757 std::function<void()> Completer) {
2758 bool SawError = false;
2760 if (Tok.is(tok::code_completion)) {
2764 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2770 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2771 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2772 Expr = ParseBraceInitializer();
2774 Expr = ParseAssignmentExpression();
2776 if (Tok.is(tok::ellipsis))
2777 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2778 if (Expr.isInvalid()) {
2779 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2782 Exprs.push_back(Expr.get());
2785 if (Tok.isNot(tok::comma))
2787 // Move to the next argument, remember where the comma was.
2788 CommaLocs.push_back(ConsumeToken());
2791 // Ensure typos get diagnosed when errors were encountered while parsing the
2793 for (auto &E : Exprs) {
2794 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2795 if (Expr.isUsable()) E = Expr.get();
2801 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2802 /// used for misc language extensions.
2805 /// simple-expression-list:
2806 /// assignment-expression
2807 /// simple-expression-list , assignment-expression
2810 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2811 SmallVectorImpl<SourceLocation> &CommaLocs) {
2813 ExprResult Expr = ParseAssignmentExpression();
2814 if (Expr.isInvalid())
2817 Exprs.push_back(Expr.get());
2819 if (Tok.isNot(tok::comma))
2822 // Move to the next argument, remember where the comma was.
2823 CommaLocs.push_back(ConsumeToken());
2827 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2830 /// [clang] block-id:
2831 /// [clang] specifier-qualifier-list block-declarator
2833 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2834 if (Tok.is(tok::code_completion)) {
2835 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2836 return cutOffParsing();
2839 // Parse the specifier-qualifier-list piece.
2840 DeclSpec DS(AttrFactory);
2841 ParseSpecifierQualifierList(DS);
2843 // Parse the block-declarator.
2844 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2845 DeclaratorInfo.setFunctionDefinitionKind(FDK_Definition);
2846 ParseDeclarator(DeclaratorInfo);
2848 MaybeParseGNUAttributes(DeclaratorInfo);
2850 // Inform sema that we are starting a block.
2851 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2854 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2855 /// like ^(int x){ return x+1; }
2859 /// [clang] '^' block-args[opt] compound-statement
2860 /// [clang] '^' block-id compound-statement
2861 /// [clang] block-args:
2862 /// [clang] '(' parameter-list ')'
2864 ExprResult Parser::ParseBlockLiteralExpression() {
2865 assert(Tok.is(tok::caret) && "block literal starts with ^");
2866 SourceLocation CaretLoc = ConsumeToken();
2868 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2869 "block literal parsing");
2871 // Enter a scope to hold everything within the block. This includes the
2872 // argument decls, decls within the compound expression, etc. This also
2873 // allows determining whether a variable reference inside the block is
2874 // within or outside of the block.
2875 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2878 // Inform sema that we are starting a block.
2879 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2881 // Parse the return type if present.
2882 DeclSpec DS(AttrFactory);
2883 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2884 ParamInfo.setFunctionDefinitionKind(FDK_Definition);
2885 // FIXME: Since the return type isn't actually parsed, it can't be used to
2886 // fill ParamInfo with an initial valid range, so do it manually.
2887 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2889 // If this block has arguments, parse them. There is no ambiguity here with
2890 // the expression case, because the expression case requires a parameter list.
2891 if (Tok.is(tok::l_paren)) {
2892 ParseParenDeclarator(ParamInfo);
2893 // Parse the pieces after the identifier as if we had "int(...)".
2894 // SetIdentifier sets the source range end, but in this case we're past
2896 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2897 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2898 ParamInfo.SetRangeEnd(Tmp);
2899 if (ParamInfo.isInvalidType()) {
2900 // If there was an error parsing the arguments, they may have
2901 // tried to use ^(x+y) which requires an argument list. Just
2902 // skip the whole block literal.
2903 Actions.ActOnBlockError(CaretLoc, getCurScope());
2907 MaybeParseGNUAttributes(ParamInfo);
2909 // Inform sema that we are starting a block.
2910 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2911 } else if (!Tok.is(tok::l_brace)) {
2912 ParseBlockId(CaretLoc);
2914 // Otherwise, pretend we saw (void).
2915 ParsedAttributes attrs(AttrFactory);
2916 SourceLocation NoLoc;
2917 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2918 /*IsAmbiguous=*/false,
2919 /*RParenLoc=*/NoLoc,
2920 /*ArgInfo=*/nullptr,
2922 /*EllipsisLoc=*/NoLoc,
2923 /*RParenLoc=*/NoLoc,
2925 /*RefQualifierIsLvalueRef=*/true,
2926 /*RefQualifierLoc=*/NoLoc,
2927 /*ConstQualifierLoc=*/NoLoc,
2928 /*VolatileQualifierLoc=*/NoLoc,
2929 /*RestrictQualifierLoc=*/NoLoc,
2930 /*MutableLoc=*/NoLoc,
2932 /*ESpecRange=*/SourceRange(),
2933 /*Exceptions=*/nullptr,
2934 /*ExceptionRanges=*/nullptr,
2935 /*NumExceptions=*/0,
2936 /*NoexceptExpr=*/nullptr,
2937 /*ExceptionSpecTokens=*/nullptr,
2938 /*DeclsInPrototype=*/None,
2943 MaybeParseGNUAttributes(ParamInfo);
2945 // Inform sema that we are starting a block.
2946 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2950 ExprResult Result(true);
2951 if (!Tok.is(tok::l_brace)) {
2952 // Saw something like: ^expr
2953 Diag(Tok, diag::err_expected_expression);
2954 Actions.ActOnBlockError(CaretLoc, getCurScope());
2958 StmtResult Stmt(ParseCompoundStatementBody());
2960 if (!Stmt.isInvalid())
2961 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2963 Actions.ActOnBlockError(CaretLoc, getCurScope());
2967 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2971 ExprResult Parser::ParseObjCBoolLiteral() {
2972 tok::TokenKind Kind = Tok.getKind();
2973 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
2976 /// Validate availability spec list, emitting diagnostics if necessary. Returns
2977 /// true if invalid.
2978 static bool CheckAvailabilitySpecList(Parser &P,
2979 ArrayRef<AvailabilitySpec> AvailSpecs) {
2980 llvm::SmallSet<StringRef, 4> Platforms;
2981 bool HasOtherPlatformSpec = false;
2983 for (const auto &Spec : AvailSpecs) {
2984 if (Spec.isOtherPlatformSpec()) {
2985 if (HasOtherPlatformSpec) {
2986 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
2990 HasOtherPlatformSpec = true;
2994 bool Inserted = Platforms.insert(Spec.getPlatform()).second;
2996 // Rule out multiple version specs referring to the same platform.
2997 // For example, we emit an error for:
2998 // @available(macos 10.10, macos 10.11, *)
2999 StringRef Platform = Spec.getPlatform();
3000 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3001 << Spec.getEndLoc() << Platform;
3006 if (!HasOtherPlatformSpec) {
3007 SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3008 P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3009 << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3016 /// Parse availability query specification.
3018 /// availability-spec:
3020 /// identifier version-tuple
3021 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3022 if (Tok.is(tok::star)) {
3023 return AvailabilitySpec(ConsumeToken());
3025 // Parse the platform name.
3026 if (Tok.is(tok::code_completion)) {
3027 Actions.CodeCompleteAvailabilityPlatformName();
3031 if (Tok.isNot(tok::identifier)) {
3032 Diag(Tok, diag::err_avail_query_expected_platform_name);
3036 IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3037 SourceRange VersionRange;
3038 VersionTuple Version = ParseVersionTuple(VersionRange);
3040 if (Version.empty())
3043 StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3044 StringRef Platform =
3045 AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3047 if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3048 Diag(PlatformIdentifier->Loc,
3049 diag::err_avail_query_unrecognized_platform_name)
3054 return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3055 VersionRange.getEnd());
3059 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3060 assert(Tok.is(tok::kw___builtin_available) ||
3061 Tok.isObjCAtKeyword(tok::objc_available));
3063 // Eat the available or __builtin_available.
3066 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3067 if (Parens.expectAndConsume())
3070 SmallVector<AvailabilitySpec, 4> AvailSpecs;
3071 bool HasError = false;
3073 Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3077 AvailSpecs.push_back(*Spec);
3079 if (!TryConsumeToken(tok::comma))
3084 SkipUntil(tok::r_paren, StopAtSemi);
3088 CheckAvailabilitySpecList(*this, AvailSpecs);
3090 if (Parens.consumeClose())
3093 return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3094 Parens.getCloseLocation());