1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Provides the Expression parsing implementation.
13 /// Expressions in C99 basically consist of a bunch of binary operators with
14 /// unary operators and other random stuff at the leaves.
16 /// In the C99 grammar, these unary operators bind tightest and are represented
17 /// as the 'cast-expression' production. Everything else is either a binary
18 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
19 /// handled by ParseCastExpression, the higher level pieces are handled by
20 /// ParseBinaryExpression.
22 //===----------------------------------------------------------------------===//
24 #include "clang/Parse/Parser.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/Basic/PrettyStackTrace.h"
27 #include "clang/Parse/RAIIObjectsForParser.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/ParsedTemplate.h"
30 #include "clang/Sema/Scope.h"
31 #include "clang/Sema/TypoCorrection.h"
32 #include "llvm/ADT/SmallVector.h"
33 using namespace clang;
35 /// Simple precedence-based parser for binary/ternary operators.
37 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
38 /// production. C99 specifies that the LHS of an assignment operator should be
39 /// parsed as a unary-expression, but consistency dictates that it be a
40 /// conditional-expession. In practice, the important thing here is that the
41 /// LHS of an assignment has to be an l-value, which productions between
42 /// unary-expression and conditional-expression don't produce. Because we want
43 /// consistency, we parse the LHS as a conditional-expression, then check for
44 /// l-value-ness in semantic analysis stages.
47 /// pm-expression: [C++ 5.5]
49 /// pm-expression '.*' cast-expression
50 /// pm-expression '->*' cast-expression
52 /// multiplicative-expression: [C99 6.5.5]
53 /// Note: in C++, apply pm-expression instead of cast-expression
55 /// multiplicative-expression '*' cast-expression
56 /// multiplicative-expression '/' cast-expression
57 /// multiplicative-expression '%' cast-expression
59 /// additive-expression: [C99 6.5.6]
60 /// multiplicative-expression
61 /// additive-expression '+' multiplicative-expression
62 /// additive-expression '-' multiplicative-expression
64 /// shift-expression: [C99 6.5.7]
65 /// additive-expression
66 /// shift-expression '<<' additive-expression
67 /// shift-expression '>>' additive-expression
69 /// compare-expression: [C++20 expr.spaceship]
71 /// compare-expression '<=>' shift-expression
73 /// relational-expression: [C99 6.5.8]
74 /// compare-expression
75 /// relational-expression '<' compare-expression
76 /// relational-expression '>' compare-expression
77 /// relational-expression '<=' compare-expression
78 /// relational-expression '>=' compare-expression
80 /// equality-expression: [C99 6.5.9]
81 /// relational-expression
82 /// equality-expression '==' relational-expression
83 /// equality-expression '!=' relational-expression
85 /// AND-expression: [C99 6.5.10]
86 /// equality-expression
87 /// AND-expression '&' equality-expression
89 /// exclusive-OR-expression: [C99 6.5.11]
91 /// exclusive-OR-expression '^' AND-expression
93 /// inclusive-OR-expression: [C99 6.5.12]
94 /// exclusive-OR-expression
95 /// inclusive-OR-expression '|' exclusive-OR-expression
97 /// logical-AND-expression: [C99 6.5.13]
98 /// inclusive-OR-expression
99 /// logical-AND-expression '&&' inclusive-OR-expression
101 /// logical-OR-expression: [C99 6.5.14]
102 /// logical-AND-expression
103 /// logical-OR-expression '||' logical-AND-expression
105 /// conditional-expression: [C99 6.5.15]
106 /// logical-OR-expression
107 /// logical-OR-expression '?' expression ':' conditional-expression
108 /// [GNU] logical-OR-expression '?' ':' conditional-expression
109 /// [C++] the third operand is an assignment-expression
111 /// assignment-expression: [C99 6.5.16]
112 /// conditional-expression
113 /// unary-expression assignment-operator assignment-expression
114 /// [C++] throw-expression [C++ 15]
116 /// assignment-operator: one of
117 /// = *= /= %= += -= <<= >>= &= ^= |=
119 /// expression: [C99 6.5.17]
120 /// assignment-expression ...[opt]
121 /// expression ',' assignment-expression ...[opt]
123 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
124 ExprResult LHS(ParseAssignmentExpression(isTypeCast));
125 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
128 /// This routine is called when the '@' is seen and consumed.
129 /// Current token is an Identifier and is not a 'try'. This
130 /// routine is necessary to disambiguate \@try-statement from,
131 /// for example, \@encode-expression.
134 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
135 ExprResult LHS(ParseObjCAtExpression(AtLoc));
136 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
139 /// This routine is called when a leading '__extension__' is seen and
140 /// consumed. This is necessary because the token gets consumed in the
141 /// process of disambiguating between an expression and a declaration.
143 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
144 ExprResult LHS(true);
146 // Silence extension warnings in the sub-expression
147 ExtensionRAIIObject O(Diags);
149 LHS = ParseCastExpression(false);
152 if (!LHS.isInvalid())
153 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
156 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
159 /// Parse an expr that doesn't include (top-level) commas.
160 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
161 if (Tok.is(tok::code_completion)) {
162 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
167 if (Tok.is(tok::kw_throw))
168 return ParseThrowExpression();
169 if (Tok.is(tok::kw_co_yield))
170 return ParseCoyieldExpression();
172 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
173 /*isAddressOfOperand=*/false,
175 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
178 /// Parse an assignment expression where part of an Objective-C message
179 /// send has already been parsed.
181 /// In this case \p LBracLoc indicates the location of the '[' of the message
182 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
183 /// the receiver of the message.
185 /// Since this handles full assignment-expression's, it handles postfix
186 /// expressions and other binary operators for these expressions as well.
188 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
189 SourceLocation SuperLoc,
190 ParsedType ReceiverType,
191 Expr *ReceiverExpr) {
193 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
194 ReceiverType, ReceiverExpr);
195 R = ParsePostfixExpressionSuffix(R);
196 return ParseRHSOfBinaryExpression(R, prec::Assignment);
200 Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) {
201 assert(Actions.ExprEvalContexts.back().Context ==
202 Sema::ExpressionEvaluationContext::ConstantEvaluated &&
203 "Call this function only if your ExpressionEvaluationContext is "
204 "already ConstantEvaluated");
205 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
206 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
207 return Actions.ActOnConstantExpression(Res);
210 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
211 // C++03 [basic.def.odr]p2:
212 // An expression is potentially evaluated unless it appears where an
213 // integral constant expression is required (see 5.19) [...].
214 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
215 EnterExpressionEvaluationContext ConstantEvaluated(
216 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
217 return ParseConstantExpressionInExprEvalContext(isTypeCast);
220 ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
221 EnterExpressionEvaluationContext ConstantEvaluated(
222 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
223 ExprResult LHS(ParseCastExpression(false, false, NotTypeCast));
224 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
225 return Actions.ActOnCaseExpr(CaseLoc, Res);
228 /// Parse a constraint-expression.
231 /// constraint-expression: [Concepts TS temp.constr.decl p1]
232 /// logical-or-expression
234 ExprResult Parser::ParseConstraintExpression() {
235 // FIXME: this may erroneously consume a function-body as the braced
236 // initializer list of a compound literal
238 // FIXME: this may erroneously consume a parenthesized rvalue reference
239 // declarator as a parenthesized address-of-label expression
240 ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
241 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
246 bool Parser::isNotExpressionStart() {
247 tok::TokenKind K = Tok.getKind();
248 if (K == tok::l_brace || K == tok::r_brace ||
249 K == tok::kw_for || K == tok::kw_while ||
250 K == tok::kw_if || K == tok::kw_else ||
251 K == tok::kw_goto || K == tok::kw_try)
253 // If this is a decl-specifier, we can't be at the start of an expression.
254 return isKnownToBeDeclarationSpecifier();
257 bool Parser::isFoldOperator(prec::Level Level) const {
258 return Level > prec::Unknown && Level != prec::Conditional &&
259 Level != prec::Spaceship;
262 bool Parser::isFoldOperator(tok::TokenKind Kind) const {
263 return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
266 /// Parse a binary expression that starts with \p LHS and has a
267 /// precedence of at least \p MinPrec.
269 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
270 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
271 GreaterThanIsOperator,
272 getLangOpts().CPlusPlus11);
273 SourceLocation ColonLoc;
276 // If this token has a lower precedence than we are allowed to parse (e.g.
277 // because we are called recursively, or because the token is not a binop),
279 if (NextTokPrec < MinPrec)
282 // Consume the operator, saving the operator token for error reporting.
286 if (OpToken.is(tok::caretcaret)) {
287 return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
290 // If we're potentially in a template-id, we may now be able to determine
291 // whether we're actually in one or not.
292 if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
293 tok::greatergreatergreater) &&
294 checkPotentialAngleBracketDelimiter(OpToken))
297 // Bail out when encountering a comma followed by a token which can't
298 // possibly be the start of an expression. For instance:
299 // int f() { return 1, }
300 // We can't do this before consuming the comma, because
301 // isNotExpressionStart() looks at the token stream.
302 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
308 // If the next token is an ellipsis, then this is a fold-expression. Leave
309 // it alone so we can handle it in the paren expression.
310 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
311 // FIXME: We can't check this via lookahead before we consume the token
312 // because that tickles a lexer bug.
318 // In Objective-C++, alternative operator tokens can be used as keyword args
319 // in message expressions. Unconsume the token so that it can reinterpreted
320 // as an identifier in ParseObjCMessageExpressionBody. i.e., we support:
321 // [foo meth:0 and:0];
323 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
324 Tok.isOneOf(tok::colon, tok::r_square) &&
325 OpToken.getIdentifierInfo() != nullptr) {
331 // Special case handling for the ternary operator.
332 ExprResult TernaryMiddle(true);
333 if (NextTokPrec == prec::Conditional) {
334 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
335 // Parse a braced-init-list here for error recovery purposes.
336 SourceLocation BraceLoc = Tok.getLocation();
337 TernaryMiddle = ParseBraceInitializer();
338 if (!TernaryMiddle.isInvalid()) {
339 Diag(BraceLoc, diag::err_init_list_bin_op)
340 << /*RHS*/ 1 << PP.getSpelling(OpToken)
341 << Actions.getExprRange(TernaryMiddle.get());
342 TernaryMiddle = ExprError();
344 } else if (Tok.isNot(tok::colon)) {
345 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
346 ColonProtectionRAIIObject X(*this);
348 // Handle this production specially:
349 // logical-OR-expression '?' expression ':' conditional-expression
350 // In particular, the RHS of the '?' is 'expression', not
351 // 'logical-OR-expression' as we might expect.
352 TernaryMiddle = ParseExpression();
354 // Special case handling of "X ? Y : Z" where Y is empty:
355 // logical-OR-expression '?' ':' conditional-expression [GNU]
356 TernaryMiddle = nullptr;
357 Diag(Tok, diag::ext_gnu_conditional_expr);
360 if (TernaryMiddle.isInvalid()) {
361 Actions.CorrectDelayedTyposInExpr(LHS);
363 TernaryMiddle = nullptr;
366 if (!TryConsumeToken(tok::colon, ColonLoc)) {
367 // Otherwise, we're missing a ':'. Assume that this was a typo that
368 // the user forgot. If we're not in a macro expansion, we can suggest
369 // a fixit hint. If there were two spaces before the current token,
370 // suggest inserting the colon in between them, otherwise insert ": ".
371 SourceLocation FILoc = Tok.getLocation();
372 const char *FIText = ": ";
373 const SourceManager &SM = PP.getSourceManager();
374 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
375 assert(FILoc.isFileID());
376 bool IsInvalid = false;
377 const char *SourcePtr =
378 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
379 if (!IsInvalid && *SourcePtr == ' ') {
381 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
382 if (!IsInvalid && *SourcePtr == ' ') {
383 FILoc = FILoc.getLocWithOffset(-1);
389 Diag(Tok, diag::err_expected)
390 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
391 Diag(OpToken, diag::note_matching) << tok::question;
392 ColonLoc = Tok.getLocation();
396 // Code completion for the right-hand side of a binary expression goes
397 // through a special hook that takes the left-hand side into account.
398 if (Tok.is(tok::code_completion)) {
399 Actions.CodeCompleteBinaryRHS(getCurScope(), LHS.get(),
405 // Parse another leaf here for the RHS of the operator.
406 // ParseCastExpression works here because all RHS expressions in C have it
407 // as a prefix, at least. However, in C++, an assignment-expression could
408 // be a throw-expression, which is not a valid cast-expression.
409 // Therefore we need some special-casing here.
410 // Also note that the third operand of the conditional operator is
411 // an assignment-expression in C++, and in C++11, we can have a
412 // braced-init-list on the RHS of an assignment. For better diagnostics,
413 // parse as if we were allowed braced-init-lists everywhere, and check that
414 // they only appear on the RHS of assignments later.
416 bool RHSIsInitList = false;
417 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
418 RHS = ParseBraceInitializer();
419 RHSIsInitList = true;
420 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
421 RHS = ParseAssignmentExpression();
423 RHS = ParseCastExpression(false);
425 if (RHS.isInvalid()) {
426 // FIXME: Errors generated by the delayed typo correction should be
427 // printed before errors from parsing the RHS, not after.
428 Actions.CorrectDelayedTyposInExpr(LHS);
429 if (TernaryMiddle.isUsable())
430 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
434 // Remember the precedence of this operator and get the precedence of the
435 // operator immediately to the right of the RHS.
436 prec::Level ThisPrec = NextTokPrec;
437 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
438 getLangOpts().CPlusPlus11);
440 // Assignment and conditional expressions are right-associative.
441 bool isRightAssoc = ThisPrec == prec::Conditional ||
442 ThisPrec == prec::Assignment;
444 // Get the precedence of the operator to the right of the RHS. If it binds
445 // more tightly with RHS than we do, evaluate it completely first.
446 if (ThisPrec < NextTokPrec ||
447 (ThisPrec == NextTokPrec && isRightAssoc)) {
448 if (!RHS.isInvalid() && RHSIsInitList) {
449 Diag(Tok, diag::err_init_list_bin_op)
450 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
453 // If this is left-associative, only parse things on the RHS that bind
454 // more tightly than the current operator. If it is left-associative, it
455 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
456 // A=(B=(C=D)), where each paren is a level of recursion here.
457 // The function takes ownership of the RHS.
458 RHS = ParseRHSOfBinaryExpression(RHS,
459 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
460 RHSIsInitList = false;
462 if (RHS.isInvalid()) {
463 // FIXME: Errors generated by the delayed typo correction should be
464 // printed before errors from ParseRHSOfBinaryExpression, not after.
465 Actions.CorrectDelayedTyposInExpr(LHS);
466 if (TernaryMiddle.isUsable())
467 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
471 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
472 getLangOpts().CPlusPlus11);
475 if (!RHS.isInvalid() && RHSIsInitList) {
476 if (ThisPrec == prec::Assignment) {
477 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
478 << Actions.getExprRange(RHS.get());
479 } else if (ColonLoc.isValid()) {
480 Diag(ColonLoc, diag::err_init_list_bin_op)
482 << Actions.getExprRange(RHS.get());
485 Diag(OpToken, diag::err_init_list_bin_op)
486 << /*RHS*/1 << PP.getSpelling(OpToken)
487 << Actions.getExprRange(RHS.get());
492 ExprResult OrigLHS = LHS;
493 if (!LHS.isInvalid()) {
494 // Combine the LHS and RHS into the LHS (e.g. build AST).
495 if (TernaryMiddle.isInvalid()) {
496 // If we're using '>>' as an operator within a template
497 // argument list (in C++98), suggest the addition of
498 // parentheses so that the code remains well-formed in C++0x.
499 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
500 SuggestParentheses(OpToken.getLocation(),
501 diag::warn_cxx11_right_shift_in_template_arg,
502 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
503 Actions.getExprRange(RHS.get()).getEnd()));
505 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
506 OpToken.getKind(), LHS.get(), RHS.get());
509 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
510 LHS.get(), TernaryMiddle.get(),
513 // In this case, ActOnBinOp or ActOnConditionalOp performed the
514 // CorrectDelayedTyposInExpr check.
515 if (!getLangOpts().CPlusPlus)
519 // Ensure potential typos aren't left undiagnosed.
520 if (LHS.isInvalid()) {
521 Actions.CorrectDelayedTyposInExpr(OrigLHS);
522 Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
523 Actions.CorrectDelayedTyposInExpr(RHS);
528 /// Parse a cast-expression, or, if \p isUnaryExpression is true,
529 /// parse a unary-expression.
531 /// \p isAddressOfOperand exists because an id-expression that is the
532 /// operand of address-of gets special treatment due to member pointers.
534 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
535 bool isAddressOfOperand,
536 TypeCastState isTypeCast,
537 bool isVectorLiteral) {
539 ExprResult Res = ParseCastExpression(isUnaryExpression,
545 Diag(Tok, diag::err_expected_expression);
550 class CastExpressionIdValidator : public CorrectionCandidateCallback {
552 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
553 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
554 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
557 bool ValidateCandidate(const TypoCorrection &candidate) override {
558 NamedDecl *ND = candidate.getCorrectionDecl();
560 return candidate.isKeyword();
562 if (isa<TypeDecl>(ND))
563 return WantTypeSpecifiers;
565 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
568 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
571 for (auto *C : candidate) {
572 NamedDecl *ND = C->getUnderlyingDecl();
573 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
585 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
586 /// a unary-expression.
588 /// \p isAddressOfOperand exists because an id-expression that is the operand
589 /// of address-of gets special treatment due to member pointers. NotCastExpr
590 /// is set to true if the token is not the start of a cast-expression, and no
591 /// diagnostic is emitted in this case and no tokens are consumed.
594 /// cast-expression: [C99 6.5.4]
596 /// '(' type-name ')' cast-expression
598 /// unary-expression: [C99 6.5.3]
599 /// postfix-expression
600 /// '++' unary-expression
601 /// '--' unary-expression
602 /// [Coro] 'co_await' cast-expression
603 /// unary-operator cast-expression
604 /// 'sizeof' unary-expression
605 /// 'sizeof' '(' type-name ')'
606 /// [C++11] 'sizeof' '...' '(' identifier ')'
607 /// [GNU] '__alignof' unary-expression
608 /// [GNU] '__alignof' '(' type-name ')'
609 /// [C11] '_Alignof' '(' type-name ')'
610 /// [C++11] 'alignof' '(' type-id ')'
611 /// [GNU] '&&' identifier
612 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
613 /// [C++] new-expression
614 /// [C++] delete-expression
616 /// unary-operator: one of
617 /// '&' '*' '+' '-' '~' '!'
618 /// [GNU] '__extension__' '__real' '__imag'
620 /// primary-expression: [C99 6.5.1]
622 /// [C++] id-expression
625 /// [C++] boolean-literal [C++ 2.13.5]
626 /// [C++11] 'nullptr' [C++11 2.14.7]
627 /// [C++11] user-defined-literal
628 /// '(' expression ')'
629 /// [C11] generic-selection
630 /// '__func__' [C99 6.4.2.2]
631 /// [GNU] '__FUNCTION__'
632 /// [MS] '__FUNCDNAME__'
633 /// [MS] 'L__FUNCTION__'
634 /// [MS] '__FUNCSIG__'
635 /// [MS] 'L__FUNCSIG__'
636 /// [GNU] '__PRETTY_FUNCTION__'
637 /// [GNU] '(' compound-statement ')'
638 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
639 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
640 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
642 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
644 /// [OBJC] '[' objc-message-expr ']'
645 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
646 /// [OBJC] '\@protocol' '(' identifier ')'
647 /// [OBJC] '\@encode' '(' type-name ')'
648 /// [OBJC] objc-string-literal
649 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
650 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
651 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
652 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
653 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
654 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
655 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
656 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
657 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
658 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
659 /// [C++] 'this' [C++ 9.3.2]
660 /// [G++] unary-type-trait '(' type-id ')'
661 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
662 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
663 /// [clang] '^' block-literal
665 /// constant: [C99 6.4.4]
667 /// floating-constant
668 /// enumeration-constant -> identifier
669 /// character-constant
671 /// id-expression: [C++ 5.1]
675 /// unqualified-id: [C++ 5.1]
677 /// operator-function-id
678 /// conversion-function-id
682 /// new-expression: [C++ 5.3.4]
683 /// '::'[opt] 'new' new-placement[opt] new-type-id
684 /// new-initializer[opt]
685 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
686 /// new-initializer[opt]
688 /// delete-expression: [C++ 5.3.5]
689 /// '::'[opt] 'delete' cast-expression
690 /// '::'[opt] 'delete' '[' ']' cast-expression
692 /// [GNU/Embarcadero] unary-type-trait:
693 /// '__is_arithmetic'
694 /// '__is_floating_point'
696 /// '__is_lvalue_expr'
697 /// '__is_rvalue_expr'
698 /// '__is_complete_type'
703 /// '__is_lvalue_reference'
704 /// '__is_rvalue_reference'
705 /// '__is_fundamental'
710 /// '__is_member_object_pointer'
711 /// '__is_member_function_pointer'
712 /// '__is_member_pointer'
716 /// '__is_standard_layout'
720 /// [GNU] unary-type-trait:
721 /// '__has_nothrow_assign'
722 /// '__has_nothrow_copy'
723 /// '__has_nothrow_constructor'
724 /// '__has_trivial_assign' [TODO]
725 /// '__has_trivial_copy' [TODO]
726 /// '__has_trivial_constructor'
727 /// '__has_trivial_destructor'
728 /// '__has_virtual_destructor'
729 /// '__is_abstract' [TODO]
731 /// '__is_empty' [TODO]
735 /// '__is_polymorphic'
736 /// '__is_sealed' [MS]
739 /// '__has_unique_object_representations'
741 /// [Clang] unary-type-trait:
743 /// '__trivially_copyable'
745 /// binary-type-trait:
746 /// [GNU] '__is_base_of'
747 /// [MS] '__is_convertible_to'
748 /// '__is_convertible'
751 /// [Embarcadero] array-type-trait:
755 /// [Embarcadero] expression-trait:
756 /// '__is_lvalue_expr'
757 /// '__is_rvalue_expr'
760 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
761 bool isAddressOfOperand,
763 TypeCastState isTypeCast,
764 bool isVectorLiteral) {
766 tok::TokenKind SavedKind = Tok.getKind();
769 // This handles all of cast-expression, unary-expression, postfix-expression,
770 // and primary-expression. We handle them together like this for efficiency
771 // and to simplify handling of an expression starting with a '(' token: which
772 // may be one of a parenthesized expression, cast-expression, compound literal
773 // expression, or statement expression.
775 // If the parsed tokens consist of a primary-expression, the cases below
776 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
777 // to handle the postfix expression suffixes. Cases that cannot be followed
778 // by postfix exprs should return without invoking
779 // ParsePostfixExpressionSuffix.
782 // If this expression is limited to being a unary-expression, the parent can
783 // not start a cast expression.
784 ParenParseOption ParenExprType =
785 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
788 SourceLocation RParenLoc;
789 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
790 isTypeCast == IsTypeCast, CastTy, RParenLoc);
795 switch (ParenExprType) {
796 case SimpleExpr: break; // Nothing else to do.
797 case CompoundStmt: break; // Nothing else to do.
798 case CompoundLiteral:
799 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
800 // postfix-expression exist, parse them now.
803 // We have parsed the cast-expression and no postfix-expr pieces are
807 // We only parsed a fold-expression. There might be postfix-expr pieces
808 // afterwards; parse them now.
815 // primary-expression
816 case tok::numeric_constant:
817 // constant: integer-constant
818 // constant: floating-constant
820 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
826 Res = ParseCXXBoolLiteral();
829 case tok::kw___objc_yes:
830 case tok::kw___objc_no:
831 return ParseObjCBoolLiteral();
833 case tok::kw_nullptr:
834 Diag(Tok, diag::warn_cxx98_compat_nullptr);
835 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
837 case tok::annot_primary_expr:
838 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
839 Res = getExprAnnotation(Tok);
840 ConsumeAnnotationToken();
841 if (!Res.isInvalid() && Tok.is(tok::less))
842 checkPotentialAngleBracket(Res);
845 case tok::kw___super:
846 case tok::kw_decltype:
847 // Annotate the token and tail recurse.
848 if (TryAnnotateTypeOrScopeToken())
850 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
851 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
853 case tok::identifier: { // primary-expression: identifier
854 // unqualified-id: identifier
855 // constant: enumeration-constant
856 // Turn a potentially qualified name into a annot_typename or
857 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
858 if (getLangOpts().CPlusPlus) {
859 // Avoid the unnecessary parse-time lookup in the common case
860 // where the syntax forbids a type.
861 const Token &Next = NextToken();
863 // If this identifier was reverted from a token ID, and the next token
864 // is a parenthesis, this is likely to be a use of a type trait. Check
866 if (Next.is(tok::l_paren) &&
867 Tok.is(tok::identifier) &&
868 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
869 IdentifierInfo *II = Tok.getIdentifierInfo();
870 // Build up the mapping of revertible type traits, for future use.
871 if (RevertibleTypeTraits.empty()) {
872 #define RTT_JOIN(X,Y) X##Y
873 #define REVERTIBLE_TYPE_TRAIT(Name) \
874 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
875 = RTT_JOIN(tok::kw_,Name)
877 REVERTIBLE_TYPE_TRAIT(__is_abstract);
878 REVERTIBLE_TYPE_TRAIT(__is_aggregate);
879 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
880 REVERTIBLE_TYPE_TRAIT(__is_array);
881 REVERTIBLE_TYPE_TRAIT(__is_assignable);
882 REVERTIBLE_TYPE_TRAIT(__is_base_of);
883 REVERTIBLE_TYPE_TRAIT(__is_class);
884 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
885 REVERTIBLE_TYPE_TRAIT(__is_compound);
886 REVERTIBLE_TYPE_TRAIT(__is_const);
887 REVERTIBLE_TYPE_TRAIT(__is_constructible);
888 REVERTIBLE_TYPE_TRAIT(__is_convertible);
889 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
890 REVERTIBLE_TYPE_TRAIT(__is_destructible);
891 REVERTIBLE_TYPE_TRAIT(__is_empty);
892 REVERTIBLE_TYPE_TRAIT(__is_enum);
893 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
894 REVERTIBLE_TYPE_TRAIT(__is_final);
895 REVERTIBLE_TYPE_TRAIT(__is_function);
896 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
897 REVERTIBLE_TYPE_TRAIT(__is_integral);
898 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
899 REVERTIBLE_TYPE_TRAIT(__is_literal);
900 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
901 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
902 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
903 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
904 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
905 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
906 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
907 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
908 REVERTIBLE_TYPE_TRAIT(__is_object);
909 REVERTIBLE_TYPE_TRAIT(__is_pod);
910 REVERTIBLE_TYPE_TRAIT(__is_pointer);
911 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
912 REVERTIBLE_TYPE_TRAIT(__is_reference);
913 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
914 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
915 REVERTIBLE_TYPE_TRAIT(__is_same);
916 REVERTIBLE_TYPE_TRAIT(__is_scalar);
917 REVERTIBLE_TYPE_TRAIT(__is_sealed);
918 REVERTIBLE_TYPE_TRAIT(__is_signed);
919 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
920 REVERTIBLE_TYPE_TRAIT(__is_trivial);
921 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
922 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
923 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
924 REVERTIBLE_TYPE_TRAIT(__is_union);
925 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
926 REVERTIBLE_TYPE_TRAIT(__is_void);
927 REVERTIBLE_TYPE_TRAIT(__is_volatile);
928 #undef REVERTIBLE_TYPE_TRAIT
932 // If we find that this is in fact the name of a type trait,
933 // update the token kind in place and parse again to treat it as
934 // the appropriate kind of type trait.
935 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
936 = RevertibleTypeTraits.find(II);
937 if (Known != RevertibleTypeTraits.end()) {
938 Tok.setKind(Known->second);
939 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
940 NotCastExpr, isTypeCast);
944 if ((!ColonIsSacred && Next.is(tok::colon)) ||
945 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
947 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
948 if (TryAnnotateTypeOrScopeToken())
950 if (!Tok.is(tok::identifier))
951 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
955 // Consume the identifier so that we can see if it is followed by a '(' or
957 IdentifierInfo &II = *Tok.getIdentifierInfo();
958 SourceLocation ILoc = ConsumeToken();
960 // Support 'Class.property' and 'super.property' notation.
961 if (getLangOpts().ObjC && Tok.is(tok::period) &&
962 (Actions.getTypeName(II, ILoc, getCurScope()) ||
963 // Allow the base to be 'super' if in an objc-method.
964 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
967 if (Tok.is(tok::code_completion) && &II != Ident_super) {
968 Actions.CodeCompleteObjCClassPropertyRefExpr(
969 getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
973 // Allow either an identifier or the keyword 'class' (in C++).
974 if (Tok.isNot(tok::identifier) &&
975 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
976 Diag(Tok, diag::err_expected_property_name);
979 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
980 SourceLocation PropertyLoc = ConsumeToken();
982 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
987 // In an Objective-C method, if we have "super" followed by an identifier,
988 // the token sequence is ill-formed. However, if there's a ':' or ']' after
989 // that identifier, this is probably a message send with a missing open
990 // bracket. Treat it as such.
991 if (getLangOpts().ObjC && &II == Ident_super && !InMessageExpression &&
992 getCurScope()->isInObjcMethodScope() &&
993 ((Tok.is(tok::identifier) &&
994 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
995 Tok.is(tok::code_completion))) {
996 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
1001 // If we have an Objective-C class name followed by an identifier
1002 // and either ':' or ']', this is an Objective-C class message
1003 // send that's missing the opening '['. Recovery
1004 // appropriately. Also take this path if we're performing code
1005 // completion after an Objective-C class name.
1006 if (getLangOpts().ObjC &&
1007 ((Tok.is(tok::identifier) && !InMessageExpression) ||
1008 Tok.is(tok::code_completion))) {
1009 const Token& Next = NextToken();
1010 if (Tok.is(tok::code_completion) ||
1011 Next.is(tok::colon) || Next.is(tok::r_square))
1012 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
1013 if (Typ.get()->isObjCObjectOrInterfaceType()) {
1014 // Fake up a Declarator to use with ActOnTypeName.
1015 DeclSpec DS(AttrFactory);
1016 DS.SetRangeStart(ILoc);
1017 DS.SetRangeEnd(ILoc);
1018 const char *PrevSpec = nullptr;
1020 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1021 Actions.getASTContext().getPrintingPolicy());
1023 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1024 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1029 Res = ParseObjCMessageExpressionBody(SourceLocation(),
1036 // Make sure to pass down the right value for isAddressOfOperand.
1037 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
1038 isAddressOfOperand = false;
1040 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1041 // need to know whether or not this identifier is a function designator or
1044 CXXScopeSpec ScopeSpec;
1045 SourceLocation TemplateKWLoc;
1047 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
1048 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
1049 Validator->IsAddressOfOperand = isAddressOfOperand;
1050 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1051 Validator->WantExpressionKeywords = false;
1052 Validator->WantRemainingKeywords = false;
1054 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
1056 Name.setIdentifier(&II, ILoc);
1057 Res = Actions.ActOnIdExpression(
1058 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1059 isAddressOfOperand, std::move(Validator),
1060 /*IsInlineAsmIdentifier=*/false,
1061 Tok.is(tok::r_paren) ? nullptr : &Replacement);
1062 if (!Res.isInvalid() && Res.isUnset()) {
1063 UnconsumeToken(Replacement);
1064 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1065 NotCastExpr, isTypeCast);
1067 if (!Res.isInvalid() && Tok.is(tok::less))
1068 checkPotentialAngleBracket(Res);
1071 case tok::char_constant: // constant: character-constant
1072 case tok::wide_char_constant:
1073 case tok::utf8_char_constant:
1074 case tok::utf16_char_constant:
1075 case tok::utf32_char_constant:
1076 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1079 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
1080 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
1081 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
1082 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
1083 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
1084 case tok::kw_L__FUNCSIG__: // primary-expression: L__FUNCSIG__ [MS]
1085 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1086 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1089 case tok::string_literal: // primary-expression: string-literal
1090 case tok::wide_string_literal:
1091 case tok::utf8_string_literal:
1092 case tok::utf16_string_literal:
1093 case tok::utf32_string_literal:
1094 Res = ParseStringLiteralExpression(true);
1096 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1097 Res = ParseGenericSelectionExpression();
1099 case tok::kw___builtin_available:
1100 return ParseAvailabilityCheckExpr(Tok.getLocation());
1101 case tok::kw___builtin_va_arg:
1102 case tok::kw___builtin_offsetof:
1103 case tok::kw___builtin_choose_expr:
1104 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1105 case tok::kw___builtin_convertvector:
1106 return ParseBuiltinPrimaryExpression();
1107 case tok::kw___null:
1108 return Actions.ActOnGNUNullExpr(ConsumeToken());
1110 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1111 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1112 // C++ [expr.unary] has:
1113 // unary-expression:
1114 // ++ cast-expression
1115 // -- cast-expression
1116 Token SavedTok = Tok;
1118 // One special case is implicitly handled here: if the preceding tokens are
1119 // an ambiguous cast expression, such as "(T())++", then we recurse to
1120 // determine whether the '++' is prefix or postfix.
1121 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1122 /*isAddressOfOperand*/false, NotCastExpr,
1125 // If we return with NotCastExpr = true, we must not consume any tokens,
1126 // so put the token back where we found it.
1127 assert(Res.isInvalid());
1128 UnconsumeToken(SavedTok);
1131 if (!Res.isInvalid())
1132 Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1133 SavedKind, Res.get());
1136 case tok::amp: { // unary-expression: '&' cast-expression
1137 // Special treatment because of member pointers
1138 SourceLocation SavedLoc = ConsumeToken();
1139 Res = ParseCastExpression(false, true);
1140 if (!Res.isInvalid())
1141 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1145 case tok::star: // unary-expression: '*' cast-expression
1146 case tok::plus: // unary-expression: '+' cast-expression
1147 case tok::minus: // unary-expression: '-' cast-expression
1148 case tok::tilde: // unary-expression: '~' cast-expression
1149 case tok::exclaim: // unary-expression: '!' cast-expression
1150 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1151 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1152 SourceLocation SavedLoc = ConsumeToken();
1153 Res = ParseCastExpression(false);
1154 if (!Res.isInvalid())
1155 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1159 case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1160 SourceLocation CoawaitLoc = ConsumeToken();
1161 Res = ParseCastExpression(false);
1162 if (!Res.isInvalid())
1163 Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1167 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1168 // __extension__ silences extension warnings in the subexpression.
1169 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1170 SourceLocation SavedLoc = ConsumeToken();
1171 Res = ParseCastExpression(false);
1172 if (!Res.isInvalid())
1173 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1176 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1177 if (!getLangOpts().C11)
1178 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1180 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1181 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1182 // unary-expression: '__alignof' '(' type-name ')'
1183 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1184 // unary-expression: 'sizeof' '(' type-name ')'
1185 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1186 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1187 case tok::kw___builtin_omp_required_simd_align:
1188 return ParseUnaryExprOrTypeTraitExpression();
1189 case tok::ampamp: { // unary-expression: '&&' identifier
1190 SourceLocation AmpAmpLoc = ConsumeToken();
1191 if (Tok.isNot(tok::identifier))
1192 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1194 if (getCurScope()->getFnParent() == nullptr)
1195 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1197 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1198 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1200 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1204 case tok::kw_const_cast:
1205 case tok::kw_dynamic_cast:
1206 case tok::kw_reinterpret_cast:
1207 case tok::kw_static_cast:
1208 Res = ParseCXXCasts();
1210 case tok::kw_typeid:
1211 Res = ParseCXXTypeid();
1213 case tok::kw___uuidof:
1214 Res = ParseCXXUuidof();
1217 Res = ParseCXXThis();
1220 case tok::annot_typename:
1221 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1222 ParsedType Type = getTypeAnnotation(Tok);
1224 // Fake up a Declarator to use with ActOnTypeName.
1225 DeclSpec DS(AttrFactory);
1226 DS.SetRangeStart(Tok.getLocation());
1227 DS.SetRangeEnd(Tok.getLastLoc());
1229 const char *PrevSpec = nullptr;
1231 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1232 PrevSpec, DiagID, Type,
1233 Actions.getASTContext().getPrintingPolicy());
1235 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1236 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1240 ConsumeAnnotationToken();
1241 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1247 case tok::annot_decltype:
1249 case tok::kw_wchar_t:
1250 case tok::kw_char8_t:
1251 case tok::kw_char16_t:
1252 case tok::kw_char32_t:
1257 case tok::kw___int64:
1258 case tok::kw___int128:
1259 case tok::kw_signed:
1260 case tok::kw_unsigned:
1263 case tok::kw_double:
1264 case tok::kw__Float16:
1265 case tok::kw___float128:
1267 case tok::kw_typename:
1268 case tok::kw_typeof:
1269 case tok::kw___vector:
1270 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1271 #include "clang/Basic/OpenCLImageTypes.def"
1273 if (!getLangOpts().CPlusPlus) {
1274 Diag(Tok, diag::err_expected_expression);
1278 if (SavedKind == tok::kw_typename) {
1279 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1280 // typename-specifier braced-init-list
1281 if (TryAnnotateTypeOrScopeToken())
1284 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1285 // We are trying to parse a simple-type-specifier but might not get such
1286 // a token after error recovery.
1290 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1291 // simple-type-specifier braced-init-list
1293 DeclSpec DS(AttrFactory);
1295 ParseCXXSimpleTypeSpecifier(DS);
1296 if (Tok.isNot(tok::l_paren) &&
1297 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1298 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1299 << DS.getSourceRange());
1301 if (Tok.is(tok::l_brace))
1302 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1304 Res = ParseCXXTypeConstructExpression(DS);
1308 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1309 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1310 // (We can end up in this situation after tentative parsing.)
1311 if (TryAnnotateTypeOrScopeToken())
1313 if (!Tok.is(tok::annot_cxxscope))
1314 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1315 NotCastExpr, isTypeCast);
1317 Token Next = NextToken();
1318 if (Next.is(tok::annot_template_id)) {
1319 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1320 if (TemplateId->Kind == TNK_Type_template) {
1321 // We have a qualified template-id that we know refers to a
1322 // type, translate it into a type and continue parsing as a
1325 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1326 /*EnteringContext=*/false);
1327 AnnotateTemplateIdTokenAsType();
1328 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1329 NotCastExpr, isTypeCast);
1333 // Parse as an id-expression.
1334 Res = ParseCXXIdExpression(isAddressOfOperand);
1338 case tok::annot_template_id: { // [C++] template-id
1339 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1340 if (TemplateId->Kind == TNK_Type_template) {
1341 // We have a template-id that we know refers to a type,
1342 // translate it into a type and continue parsing as a cast
1344 AnnotateTemplateIdTokenAsType();
1345 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1346 NotCastExpr, isTypeCast);
1349 // Fall through to treat the template-id as an id-expression.
1353 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1354 Res = ParseCXXIdExpression(isAddressOfOperand);
1357 case tok::coloncolon: {
1358 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1359 // annotates the token, tail recurse.
1360 if (TryAnnotateTypeOrScopeToken())
1362 if (!Tok.is(tok::coloncolon))
1363 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1365 // ::new -> [C++] new-expression
1366 // ::delete -> [C++] delete-expression
1367 SourceLocation CCLoc = ConsumeToken();
1368 if (Tok.is(tok::kw_new))
1369 return ParseCXXNewExpression(true, CCLoc);
1370 if (Tok.is(tok::kw_delete))
1371 return ParseCXXDeleteExpression(true, CCLoc);
1373 // This is not a type name or scope specifier, it is an invalid expression.
1374 Diag(CCLoc, diag::err_expected_expression);
1378 case tok::kw_new: // [C++] new-expression
1379 return ParseCXXNewExpression(false, Tok.getLocation());
1381 case tok::kw_delete: // [C++] delete-expression
1382 return ParseCXXDeleteExpression(false, Tok.getLocation());
1384 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1385 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1386 SourceLocation KeyLoc = ConsumeToken();
1387 BalancedDelimiterTracker T(*this, tok::l_paren);
1389 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1391 // C++11 [expr.unary.noexcept]p1:
1392 // The noexcept operator determines whether the evaluation of its operand,
1393 // which is an unevaluated operand, can throw an exception.
1394 EnterExpressionEvaluationContext Unevaluated(
1395 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1396 ExprResult Result = ParseExpression();
1400 if (!Result.isInvalid())
1401 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1402 Result.get(), T.getCloseLocation());
1406 #define TYPE_TRAIT(N,Spelling,K) \
1407 case tok::kw_##Spelling:
1408 #include "clang/Basic/TokenKinds.def"
1409 return ParseTypeTrait();
1411 case tok::kw___array_rank:
1412 case tok::kw___array_extent:
1413 return ParseArrayTypeTrait();
1415 case tok::kw___is_lvalue_expr:
1416 case tok::kw___is_rvalue_expr:
1417 return ParseExpressionTrait();
1420 SourceLocation AtLoc = ConsumeToken();
1421 return ParseObjCAtExpression(AtLoc);
1424 Res = ParseBlockLiteralExpression();
1426 case tok::code_completion: {
1427 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1432 if (getLangOpts().CPlusPlus11) {
1433 if (getLangOpts().ObjC) {
1434 // C++11 lambda expressions and Objective-C message sends both start with a
1435 // square bracket. There are three possibilities here:
1436 // we have a valid lambda expression, we have an invalid lambda
1437 // expression, or we have something that doesn't appear to be a lambda.
1438 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1439 Res = TryParseLambdaExpression();
1440 if (!Res.isInvalid() && !Res.get())
1441 Res = ParseObjCMessageExpression();
1444 Res = ParseLambdaExpression();
1447 if (getLangOpts().ObjC) {
1448 Res = ParseObjCMessageExpression();
1457 // Check to see whether Res is a function designator only. If it is and we
1458 // are compiling for OpenCL, we need to return an error as this implies
1459 // that the address of the function is being taken, which is illegal in CL.
1461 // These can be followed by postfix-expr pieces.
1462 Res = ParsePostfixExpressionSuffix(Res);
1463 if (getLangOpts().OpenCL)
1464 if (Expr *PostfixExpr = Res.get()) {
1465 QualType Ty = PostfixExpr->getType();
1466 if (!Ty.isNull() && Ty->isFunctionType()) {
1467 Diag(PostfixExpr->getExprLoc(),
1468 diag::err_opencl_taking_function_address_parser);
1476 /// Once the leading part of a postfix-expression is parsed, this
1477 /// method parses any suffixes that apply.
1480 /// postfix-expression: [C99 6.5.2]
1481 /// primary-expression
1482 /// postfix-expression '[' expression ']'
1483 /// postfix-expression '[' braced-init-list ']'
1484 /// postfix-expression '(' argument-expression-list[opt] ')'
1485 /// postfix-expression '.' identifier
1486 /// postfix-expression '->' identifier
1487 /// postfix-expression '++'
1488 /// postfix-expression '--'
1489 /// '(' type-name ')' '{' initializer-list '}'
1490 /// '(' type-name ')' '{' initializer-list ',' '}'
1492 /// argument-expression-list: [C99 6.5.2]
1493 /// argument-expression ...[opt]
1494 /// argument-expression-list ',' assignment-expression ...[opt]
1497 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1498 // Now that the primary-expression piece of the postfix-expression has been
1499 // parsed, see if there are any postfix-expression pieces here.
1502 switch (Tok.getKind()) {
1503 case tok::code_completion:
1504 if (InMessageExpression)
1507 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1511 case tok::identifier:
1512 // If we see identifier: after an expression, and we're not already in a
1513 // message send, then this is probably a message send with a missing
1514 // opening bracket '['.
1515 if (getLangOpts().ObjC && !InMessageExpression &&
1516 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1517 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1518 nullptr, LHS.get());
1521 // Fall through; this isn't a message send.
1524 default: // Not a postfix-expression suffix.
1526 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1527 // If we have a array postfix expression that starts on a new line and
1528 // Objective-C is enabled, it is highly likely that the user forgot a
1529 // semicolon after the base expression and that the array postfix-expr is
1530 // actually another message send. In this case, do some look-ahead to see
1531 // if the contents of the square brackets are obviously not a valid
1532 // expression and recover by pretending there is no suffix.
1533 if (getLangOpts().ObjC && Tok.isAtStartOfLine() &&
1534 isSimpleObjCMessageExpression())
1537 // Reject array indices starting with a lambda-expression. '[[' is
1538 // reserved for attributes.
1539 if (CheckProhibitedCXX11Attribute()) {
1540 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1544 BalancedDelimiterTracker T(*this, tok::l_square);
1546 Loc = T.getOpenLocation();
1547 ExprResult Idx, Length;
1548 SourceLocation ColonLoc;
1549 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1550 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1551 Idx = ParseBraceInitializer();
1552 } else if (getLangOpts().OpenMP) {
1553 ColonProtectionRAIIObject RAII(*this);
1554 // Parse [: or [ expr or [ expr :
1555 if (!Tok.is(tok::colon)) {
1557 Idx = ParseExpression();
1559 if (Tok.is(tok::colon)) {
1561 ColonLoc = ConsumeToken();
1562 if (Tok.isNot(tok::r_square))
1563 Length = ParseExpression();
1566 Idx = ParseExpression();
1568 SourceLocation RLoc = Tok.getLocation();
1570 ExprResult OrigLHS = LHS;
1571 if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1572 Tok.is(tok::r_square)) {
1573 if (ColonLoc.isValid()) {
1574 LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1575 ColonLoc, Length.get(), RLoc);
1577 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1583 if (LHS.isInvalid()) {
1584 (void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
1585 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1586 (void)Actions.CorrectDelayedTyposInExpr(Length);
1596 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1597 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1598 // '(' argument-expression-list[opt] ')'
1599 tok::TokenKind OpKind = Tok.getKind();
1600 InMessageExpressionRAIIObject InMessage(*this, false);
1602 Expr *ExecConfig = nullptr;
1604 BalancedDelimiterTracker PT(*this, tok::l_paren);
1606 if (OpKind == tok::lesslessless) {
1607 ExprVector ExecConfigExprs;
1608 CommaLocsTy ExecConfigCommaLocs;
1609 SourceLocation OpenLoc = ConsumeToken();
1611 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1612 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1616 SourceLocation CloseLoc;
1617 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1618 } else if (LHS.isInvalid()) {
1619 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1621 // There was an error closing the brackets
1622 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1623 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1624 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1628 if (!LHS.isInvalid()) {
1629 if (ExpectAndConsume(tok::l_paren))
1632 Loc = PrevTokLocation;
1635 if (!LHS.isInvalid()) {
1636 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1640 if (ECResult.isInvalid())
1643 ExecConfig = ECResult.get();
1647 Loc = PT.getOpenLocation();
1650 ExprVector ArgExprs;
1651 CommaLocsTy CommaLocs;
1653 if (Tok.is(tok::code_completion)) {
1654 QualType PreferredType = Actions.ProduceCallSignatureHelp(
1655 getCurScope(), LHS.get(), None, PT.getOpenLocation());
1656 CalledSignatureHelp = true;
1657 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
1662 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1663 if (Tok.isNot(tok::r_paren)) {
1664 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1665 QualType PreferredType = Actions.ProduceCallSignatureHelp(
1666 getCurScope(), LHS.get(), ArgExprs, PT.getOpenLocation());
1667 CalledSignatureHelp = true;
1668 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
1670 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1671 // If we got an error when parsing expression list, we don't call
1672 // the CodeCompleteCall handler inside the parser. So call it here
1673 // to make sure we get overload suggestions even when we are in the
1674 // middle of a parameter.
1675 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
1676 Actions.ProduceCallSignatureHelp(getCurScope(), LHS.get(),
1677 ArgExprs, PT.getOpenLocation());
1678 CalledSignatureHelp = true;
1681 } else if (LHS.isInvalid()) {
1682 for (auto &E : ArgExprs)
1683 Actions.CorrectDelayedTyposInExpr(E);
1689 if (LHS.isInvalid()) {
1690 SkipUntil(tok::r_paren, StopAtSemi);
1691 } else if (Tok.isNot(tok::r_paren)) {
1692 bool HadDelayedTypo = false;
1693 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1694 HadDelayedTypo = true;
1695 for (auto &E : ArgExprs)
1696 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1697 HadDelayedTypo = true;
1698 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1699 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1700 // the unmatched l_paren.
1702 SkipUntil(tok::r_paren, StopAtSemi);
1707 assert((ArgExprs.size() == 0 ||
1708 ArgExprs.size()-1 == CommaLocs.size())&&
1709 "Unexpected number of commas!");
1710 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1711 ArgExprs, Tok.getLocation(),
1720 // postfix-expression: p-e '->' template[opt] id-expression
1721 // postfix-expression: p-e '.' template[opt] id-expression
1722 tok::TokenKind OpKind = Tok.getKind();
1723 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1726 ParsedType ObjectType;
1727 bool MayBePseudoDestructor = false;
1728 Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr;
1730 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1731 Expr *Base = OrigLHS;
1732 const Type* BaseType = Base->getType().getTypePtrOrNull();
1733 if (BaseType && Tok.is(tok::l_paren) &&
1734 (BaseType->isFunctionType() ||
1735 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1736 Diag(OpLoc, diag::err_function_is_not_record)
1737 << OpKind << Base->getSourceRange()
1738 << FixItHint::CreateRemoval(OpLoc);
1739 return ParsePostfixExpressionSuffix(Base);
1742 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1743 OpLoc, OpKind, ObjectType,
1744 MayBePseudoDestructor);
1745 if (LHS.isInvalid())
1748 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1749 /*EnteringContext=*/false,
1750 &MayBePseudoDestructor);
1751 if (SS.isNotEmpty())
1752 ObjectType = nullptr;
1755 if (Tok.is(tok::code_completion)) {
1756 tok::TokenKind CorrectedOpKind =
1757 OpKind == tok::arrow ? tok::period : tok::arrow;
1758 ExprResult CorrectedLHS(/*IsInvalid=*/true);
1759 if (getLangOpts().CPlusPlus && OrigLHS) {
1760 const bool DiagsAreSuppressed = Diags.getSuppressAllDiagnostics();
1761 Diags.setSuppressAllDiagnostics(true);
1762 CorrectedLHS = Actions.ActOnStartCXXMemberReference(
1763 getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
1764 MayBePseudoDestructor);
1765 Diags.setSuppressAllDiagnostics(DiagsAreSuppressed);
1768 Expr *Base = LHS.get();
1769 Expr *CorrectedBase = CorrectedLHS.get();
1770 if (!CorrectedBase && !getLangOpts().CPlusPlus)
1771 CorrectedBase = Base;
1773 // Code completion for a member access expression.
1774 Actions.CodeCompleteMemberReferenceExpr(
1775 getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
1776 Base && ExprStatementTokLoc == Base->getBeginLoc());
1782 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1783 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1788 // Either the action has told us that this cannot be a
1789 // pseudo-destructor expression (based on the type of base
1790 // expression), or we didn't see a '~' in the right place. We
1791 // can still parse a destructor name here, but in that case it
1792 // names a real destructor.
1793 // Allow explicit constructor calls in Microsoft mode.
1794 // FIXME: Add support for explicit call of template constructor.
1795 SourceLocation TemplateKWLoc;
1797 if (getLangOpts().ObjC && OpKind == tok::period &&
1798 Tok.is(tok::kw_class)) {
1800 // After a '.' in a member access expression, treat the keyword
1801 // 'class' as if it were an identifier.
1803 // This hack allows property access to the 'class' method because it is
1804 // such a common method name. For other C++ keywords that are
1805 // Objective-C method names, one must use the message send syntax.
1806 IdentifierInfo *Id = Tok.getIdentifierInfo();
1807 SourceLocation Loc = ConsumeToken();
1808 Name.setIdentifier(Id, Loc);
1809 } else if (ParseUnqualifiedId(SS,
1810 /*EnteringContext=*/false,
1811 /*AllowDestructorName=*/true,
1812 /*AllowConstructorName=*/
1813 getLangOpts().MicrosoftExt &&
1815 /*AllowDeductionGuide=*/false,
1816 ObjectType, &TemplateKWLoc, Name)) {
1817 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1821 if (!LHS.isInvalid())
1822 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1823 OpKind, SS, TemplateKWLoc, Name,
1824 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1826 if (!LHS.isInvalid() && Tok.is(tok::less))
1827 checkPotentialAngleBracket(LHS);
1830 case tok::plusplus: // postfix-expression: postfix-expression '++'
1831 case tok::minusminus: // postfix-expression: postfix-expression '--'
1832 if (!LHS.isInvalid()) {
1833 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1834 Tok.getKind(), LHS.get());
1842 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1843 /// vec_step and we are at the start of an expression or a parenthesized
1844 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1845 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1848 /// unary-expression: [C99 6.5.3]
1849 /// 'sizeof' unary-expression
1850 /// 'sizeof' '(' type-name ')'
1851 /// [GNU] '__alignof' unary-expression
1852 /// [GNU] '__alignof' '(' type-name ')'
1853 /// [C11] '_Alignof' '(' type-name ')'
1854 /// [C++0x] 'alignof' '(' type-id ')'
1856 /// [GNU] typeof-specifier:
1857 /// typeof ( expressions )
1858 /// typeof ( type-name )
1859 /// [GNU/C++] typeof unary-expression
1861 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1862 /// vec_step ( expressions )
1863 /// vec_step ( type-name )
1866 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1869 SourceRange &CastRange) {
1871 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1872 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1873 tok::kw___builtin_omp_required_simd_align) &&
1874 "Not a typeof/sizeof/alignof/vec_step expression!");
1878 // If the operand doesn't start with an '(', it must be an expression.
1879 if (Tok.isNot(tok::l_paren)) {
1880 // If construct allows a form without parenthesis, user may forget to put
1881 // pathenthesis around type name.
1882 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1883 tok::kw__Alignof)) {
1884 if (isTypeIdUnambiguously()) {
1885 DeclSpec DS(AttrFactory);
1886 ParseSpecifierQualifierList(DS);
1887 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1888 ParseDeclarator(DeclaratorInfo);
1890 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1891 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1892 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1894 << FixItHint::CreateInsertion(LParenLoc, "(")
1895 << FixItHint::CreateInsertion(RParenLoc, ")");
1902 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1903 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1908 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1910 // If it starts with a '(', we know that it is either a parenthesized
1911 // type-name, or it is a unary-expression that starts with a compound
1912 // literal, or starts with a primary-expression that is a parenthesized
1914 ParenParseOption ExprType = CastExpr;
1915 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1917 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1918 false, CastTy, RParenLoc);
1919 CastRange = SourceRange(LParenLoc, RParenLoc);
1921 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1923 if (ExprType == CastExpr) {
1928 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1929 // GNU typeof in C requires the expression to be parenthesized. Not so for
1930 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1931 // the start of a unary-expression, but doesn't include any postfix
1932 // pieces. Parse these now if present.
1933 if (!Operand.isInvalid())
1934 Operand = ParsePostfixExpressionSuffix(Operand.get());
1938 // If we get here, the operand to the typeof/sizeof/alignof was an expression.
1944 /// Parse a sizeof or alignof expression.
1947 /// unary-expression: [C99 6.5.3]
1948 /// 'sizeof' unary-expression
1949 /// 'sizeof' '(' type-name ')'
1950 /// [C++11] 'sizeof' '...' '(' identifier ')'
1951 /// [GNU] '__alignof' unary-expression
1952 /// [GNU] '__alignof' '(' type-name ')'
1953 /// [C11] '_Alignof' '(' type-name ')'
1954 /// [C++11] 'alignof' '(' type-id ')'
1956 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1957 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1958 tok::kw__Alignof, tok::kw_vec_step,
1959 tok::kw___builtin_omp_required_simd_align) &&
1960 "Not a sizeof/alignof/vec_step expression!");
1964 // [C++11] 'sizeof' '...' '(' identifier ')'
1965 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1966 SourceLocation EllipsisLoc = ConsumeToken();
1967 SourceLocation LParenLoc, RParenLoc;
1968 IdentifierInfo *Name = nullptr;
1969 SourceLocation NameLoc;
1970 if (Tok.is(tok::l_paren)) {
1971 BalancedDelimiterTracker T(*this, tok::l_paren);
1973 LParenLoc = T.getOpenLocation();
1974 if (Tok.is(tok::identifier)) {
1975 Name = Tok.getIdentifierInfo();
1976 NameLoc = ConsumeToken();
1978 RParenLoc = T.getCloseLocation();
1979 if (RParenLoc.isInvalid())
1980 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1982 Diag(Tok, diag::err_expected_parameter_pack);
1983 SkipUntil(tok::r_paren, StopAtSemi);
1985 } else if (Tok.is(tok::identifier)) {
1986 Name = Tok.getIdentifierInfo();
1987 NameLoc = ConsumeToken();
1988 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1989 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1990 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1992 << FixItHint::CreateInsertion(LParenLoc, "(")
1993 << FixItHint::CreateInsertion(RParenLoc, ")");
1995 Diag(Tok, diag::err_sizeof_parameter_pack);
2001 EnterExpressionEvaluationContext Unevaluated(
2002 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2003 Sema::ReuseLambdaContextDecl);
2005 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
2006 OpTok.getLocation(),
2011 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2012 Diag(OpTok, diag::warn_cxx98_compat_alignof);
2014 EnterExpressionEvaluationContext Unevaluated(
2015 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2016 Sema::ReuseLambdaContextDecl);
2020 SourceRange CastRange;
2021 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
2026 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2027 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2028 ExprKind = UETT_AlignOf;
2029 else if (OpTok.is(tok::kw___alignof))
2030 ExprKind = UETT_PreferredAlignOf;
2031 else if (OpTok.is(tok::kw_vec_step))
2032 ExprKind = UETT_VecStep;
2033 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2034 ExprKind = UETT_OpenMPRequiredSimdAlign;
2037 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2040 CastTy.getAsOpaquePtr(),
2043 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2044 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2046 // If we get here, the operand to the sizeof/alignof was an expression.
2047 if (!Operand.isInvalid())
2048 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2056 /// ParseBuiltinPrimaryExpression
2059 /// primary-expression: [C99 6.5.1]
2060 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2061 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2062 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2064 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2065 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
2067 /// [GNU] offsetof-member-designator:
2068 /// [GNU] identifier
2069 /// [GNU] offsetof-member-designator '.' identifier
2070 /// [GNU] offsetof-member-designator '[' expression ']'
2072 ExprResult Parser::ParseBuiltinPrimaryExpression() {
2074 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2076 tok::TokenKind T = Tok.getKind();
2077 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
2079 // All of these start with an open paren.
2080 if (Tok.isNot(tok::l_paren))
2081 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2084 BalancedDelimiterTracker PT(*this, tok::l_paren);
2090 default: llvm_unreachable("Not a builtin primary expression!");
2091 case tok::kw___builtin_va_arg: {
2092 ExprResult Expr(ParseAssignmentExpression());
2094 if (ExpectAndConsume(tok::comma)) {
2095 SkipUntil(tok::r_paren, StopAtSemi);
2099 TypeResult Ty = ParseTypeName();
2101 if (Tok.isNot(tok::r_paren)) {
2102 Diag(Tok, diag::err_expected) << tok::r_paren;
2106 if (Expr.isInvalid() || Ty.isInvalid())
2109 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2112 case tok::kw___builtin_offsetof: {
2113 SourceLocation TypeLoc = Tok.getLocation();
2114 TypeResult Ty = ParseTypeName();
2115 if (Ty.isInvalid()) {
2116 SkipUntil(tok::r_paren, StopAtSemi);
2120 if (ExpectAndConsume(tok::comma)) {
2121 SkipUntil(tok::r_paren, StopAtSemi);
2125 // We must have at least one identifier here.
2126 if (Tok.isNot(tok::identifier)) {
2127 Diag(Tok, diag::err_expected) << tok::identifier;
2128 SkipUntil(tok::r_paren, StopAtSemi);
2132 // Keep track of the various subcomponents we see.
2133 SmallVector<Sema::OffsetOfComponent, 4> Comps;
2135 Comps.push_back(Sema::OffsetOfComponent());
2136 Comps.back().isBrackets = false;
2137 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2138 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2140 // FIXME: This loop leaks the index expressions on error.
2142 if (Tok.is(tok::period)) {
2143 // offsetof-member-designator: offsetof-member-designator '.' identifier
2144 Comps.push_back(Sema::OffsetOfComponent());
2145 Comps.back().isBrackets = false;
2146 Comps.back().LocStart = ConsumeToken();
2148 if (Tok.isNot(tok::identifier)) {
2149 Diag(Tok, diag::err_expected) << tok::identifier;
2150 SkipUntil(tok::r_paren, StopAtSemi);
2153 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2154 Comps.back().LocEnd = ConsumeToken();
2156 } else if (Tok.is(tok::l_square)) {
2157 if (CheckProhibitedCXX11Attribute())
2160 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2161 Comps.push_back(Sema::OffsetOfComponent());
2162 Comps.back().isBrackets = true;
2163 BalancedDelimiterTracker ST(*this, tok::l_square);
2165 Comps.back().LocStart = ST.getOpenLocation();
2166 Res = ParseExpression();
2167 if (Res.isInvalid()) {
2168 SkipUntil(tok::r_paren, StopAtSemi);
2171 Comps.back().U.E = Res.get();
2174 Comps.back().LocEnd = ST.getCloseLocation();
2176 if (Tok.isNot(tok::r_paren)) {
2179 } else if (Ty.isInvalid()) {
2183 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2185 PT.getCloseLocation());
2192 case tok::kw___builtin_choose_expr: {
2193 ExprResult Cond(ParseAssignmentExpression());
2194 if (Cond.isInvalid()) {
2195 SkipUntil(tok::r_paren, StopAtSemi);
2198 if (ExpectAndConsume(tok::comma)) {
2199 SkipUntil(tok::r_paren, StopAtSemi);
2203 ExprResult Expr1(ParseAssignmentExpression());
2204 if (Expr1.isInvalid()) {
2205 SkipUntil(tok::r_paren, StopAtSemi);
2208 if (ExpectAndConsume(tok::comma)) {
2209 SkipUntil(tok::r_paren, StopAtSemi);
2213 ExprResult Expr2(ParseAssignmentExpression());
2214 if (Expr2.isInvalid()) {
2215 SkipUntil(tok::r_paren, StopAtSemi);
2218 if (Tok.isNot(tok::r_paren)) {
2219 Diag(Tok, diag::err_expected) << tok::r_paren;
2222 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2223 Expr2.get(), ConsumeParen());
2226 case tok::kw___builtin_astype: {
2227 // The first argument is an expression to be converted, followed by a comma.
2228 ExprResult Expr(ParseAssignmentExpression());
2229 if (Expr.isInvalid()) {
2230 SkipUntil(tok::r_paren, StopAtSemi);
2234 if (ExpectAndConsume(tok::comma)) {
2235 SkipUntil(tok::r_paren, StopAtSemi);
2239 // Second argument is the type to bitcast to.
2240 TypeResult DestTy = ParseTypeName();
2241 if (DestTy.isInvalid())
2244 // Attempt to consume the r-paren.
2245 if (Tok.isNot(tok::r_paren)) {
2246 Diag(Tok, diag::err_expected) << tok::r_paren;
2247 SkipUntil(tok::r_paren, StopAtSemi);
2251 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2255 case tok::kw___builtin_convertvector: {
2256 // The first argument is an expression to be converted, followed by a comma.
2257 ExprResult Expr(ParseAssignmentExpression());
2258 if (Expr.isInvalid()) {
2259 SkipUntil(tok::r_paren, StopAtSemi);
2263 if (ExpectAndConsume(tok::comma)) {
2264 SkipUntil(tok::r_paren, StopAtSemi);
2268 // Second argument is the type to bitcast to.
2269 TypeResult DestTy = ParseTypeName();
2270 if (DestTy.isInvalid())
2273 // Attempt to consume the r-paren.
2274 if (Tok.isNot(tok::r_paren)) {
2275 Diag(Tok, diag::err_expected) << tok::r_paren;
2276 SkipUntil(tok::r_paren, StopAtSemi);
2280 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2286 if (Res.isInvalid())
2289 // These can be followed by postfix-expr pieces because they are
2290 // primary-expressions.
2291 return ParsePostfixExpressionSuffix(Res.get());
2294 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2295 /// based on what is allowed by ExprType. The actual thing parsed is returned
2296 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2297 /// not the parsed cast-expression.
2300 /// primary-expression: [C99 6.5.1]
2301 /// '(' expression ')'
2302 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2303 /// postfix-expression: [C99 6.5.2]
2304 /// '(' type-name ')' '{' initializer-list '}'
2305 /// '(' type-name ')' '{' initializer-list ',' '}'
2306 /// cast-expression: [C99 6.5.4]
2307 /// '(' type-name ')' cast-expression
2308 /// [ARC] bridged-cast-expression
2309 /// [ARC] bridged-cast-expression:
2310 /// (__bridge type-name) cast-expression
2311 /// (__bridge_transfer type-name) cast-expression
2312 /// (__bridge_retained type-name) cast-expression
2313 /// fold-expression: [C++1z]
2314 /// '(' cast-expression fold-operator '...' ')'
2315 /// '(' '...' fold-operator cast-expression ')'
2316 /// '(' cast-expression fold-operator '...'
2317 /// fold-operator cast-expression ')'
2320 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2321 bool isTypeCast, ParsedType &CastTy,
2322 SourceLocation &RParenLoc) {
2323 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2324 ColonProtectionRAIIObject ColonProtection(*this, false);
2325 BalancedDelimiterTracker T(*this, tok::l_paren);
2326 if (T.consumeOpen())
2328 SourceLocation OpenLoc = T.getOpenLocation();
2330 ExprResult Result(true);
2331 bool isAmbiguousTypeId;
2334 if (Tok.is(tok::code_completion)) {
2335 Actions.CodeCompleteOrdinaryName(getCurScope(),
2336 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2337 : Sema::PCC_Expression);
2342 // Diagnose use of bridge casts in non-arc mode.
2343 bool BridgeCast = (getLangOpts().ObjC &&
2344 Tok.isOneOf(tok::kw___bridge,
2345 tok::kw___bridge_transfer,
2346 tok::kw___bridge_retained,
2347 tok::kw___bridge_retain));
2348 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2349 if (!TryConsumeToken(tok::kw___bridge)) {
2350 StringRef BridgeCastName = Tok.getName();
2351 SourceLocation BridgeKeywordLoc = ConsumeToken();
2352 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2353 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2355 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2360 // None of these cases should fall through with an invalid Result
2361 // unless they've already reported an error.
2362 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2363 Diag(Tok, diag::ext_gnu_statement_expr);
2365 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2366 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2368 // Find the nearest non-record decl context. Variables declared in a
2369 // statement expression behave as if they were declared in the enclosing
2370 // function, block, or other code construct.
2371 DeclContext *CodeDC = Actions.CurContext;
2372 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2373 CodeDC = CodeDC->getParent();
2374 assert(CodeDC && !CodeDC->isFileContext() &&
2375 "statement expr not in code context");
2377 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2379 Actions.ActOnStartStmtExpr();
2381 StmtResult Stmt(ParseCompoundStatement(true));
2382 ExprType = CompoundStmt;
2384 // If the substmt parsed correctly, build the AST node.
2385 if (!Stmt.isInvalid()) {
2386 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2388 Actions.ActOnStmtExprError();
2391 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2392 tok::TokenKind tokenKind = Tok.getKind();
2393 SourceLocation BridgeKeywordLoc = ConsumeToken();
2395 // Parse an Objective-C ARC ownership cast expression.
2396 ObjCBridgeCastKind Kind;
2397 if (tokenKind == tok::kw___bridge)
2399 else if (tokenKind == tok::kw___bridge_transfer)
2400 Kind = OBC_BridgeTransfer;
2401 else if (tokenKind == tok::kw___bridge_retained)
2402 Kind = OBC_BridgeRetained;
2404 // As a hopefully temporary workaround, allow __bridge_retain as
2405 // a synonym for __bridge_retained, but only in system headers.
2406 assert(tokenKind == tok::kw___bridge_retain);
2407 Kind = OBC_BridgeRetained;
2408 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2409 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2410 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2411 "__bridge_retained");
2414 TypeResult Ty = ParseTypeName();
2416 ColonProtection.restore();
2417 RParenLoc = T.getCloseLocation();
2418 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2420 if (Ty.isInvalid() || SubExpr.isInvalid())
2423 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2424 BridgeKeywordLoc, Ty.get(),
2425 RParenLoc, SubExpr.get());
2426 } else if (ExprType >= CompoundLiteral &&
2427 isTypeIdInParens(isAmbiguousTypeId)) {
2429 // Otherwise, this is a compound literal expression or cast expression.
2431 // In C++, if the type-id is ambiguous we disambiguate based on context.
2432 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2433 // in which case we should treat it as type-id.
2434 // if stopIfCastExpr is false, we need to determine the context past the
2435 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2436 if (isAmbiguousTypeId && !stopIfCastExpr) {
2437 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2439 RParenLoc = T.getCloseLocation();
2443 // Parse the type declarator.
2444 DeclSpec DS(AttrFactory);
2445 ParseSpecifierQualifierList(DS);
2446 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2447 ParseDeclarator(DeclaratorInfo);
2449 // If our type is followed by an identifier and either ':' or ']', then
2450 // this is probably an Objective-C message send where the leading '[' is
2451 // missing. Recover as if that were the case.
2452 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2453 !InMessageExpression && getLangOpts().ObjC &&
2454 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2457 InMessageExpressionRAIIObject InMessage(*this, false);
2458 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2460 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2466 ColonProtection.restore();
2467 RParenLoc = T.getCloseLocation();
2468 if (Tok.is(tok::l_brace)) {
2469 ExprType = CompoundLiteral;
2472 InMessageExpressionRAIIObject InMessage(*this, false);
2473 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2475 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2478 if (Tok.is(tok::l_paren)) {
2479 // This could be OpenCL vector Literals
2480 if (getLangOpts().OpenCL)
2484 InMessageExpressionRAIIObject InMessage(*this, false);
2485 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2491 QualType QT = Ty.get().get().getCanonicalType();
2492 if (QT->isVectorType())
2494 // We parsed '(' vector-type-name ')' followed by '('
2496 // Parse the cast-expression that follows it next.
2497 // isVectorLiteral = true will make sure we don't parse any
2498 // Postfix expression yet
2499 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2500 /*isAddressOfOperand=*/false,
2501 /*isTypeCast=*/IsTypeCast,
2502 /*isVectorLiteral=*/true);
2504 if (!Result.isInvalid()) {
2505 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2506 DeclaratorInfo, CastTy,
2507 RParenLoc, Result.get());
2510 // After we performed the cast we can check for postfix-expr pieces.
2511 if (!Result.isInvalid()) {
2512 Result = ParsePostfixExpressionSuffix(Result);
2520 if (ExprType == CastExpr) {
2521 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2523 if (DeclaratorInfo.isInvalidType())
2526 // Note that this doesn't parse the subsequent cast-expression, it just
2527 // returns the parsed type to the callee.
2528 if (stopIfCastExpr) {
2531 InMessageExpressionRAIIObject InMessage(*this, false);
2532 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2535 return ExprResult();
2538 // Reject the cast of super idiom in ObjC.
2539 if (Tok.is(tok::identifier) && getLangOpts().ObjC &&
2540 Tok.getIdentifierInfo() == Ident_super &&
2541 getCurScope()->isInObjcMethodScope() &&
2542 GetLookAheadToken(1).isNot(tok::period)) {
2543 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2544 << SourceRange(OpenLoc, RParenLoc);
2548 // Parse the cast-expression that follows it next.
2549 // TODO: For cast expression with CastTy.
2550 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2551 /*isAddressOfOperand=*/false,
2552 /*isTypeCast=*/IsTypeCast);
2553 if (!Result.isInvalid()) {
2554 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2555 DeclaratorInfo, CastTy,
2556 RParenLoc, Result.get());
2561 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2564 } else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) &&
2565 isFoldOperator(NextToken().getKind())) {
2566 ExprType = FoldExpr;
2567 return ParseFoldExpression(ExprResult(), T);
2568 } else if (isTypeCast) {
2569 // Parse the expression-list.
2570 InMessageExpressionRAIIObject InMessage(*this, false);
2572 ExprVector ArgExprs;
2573 CommaLocsTy CommaLocs;
2575 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2576 // FIXME: If we ever support comma expressions as operands to
2577 // fold-expressions, we'll need to allow multiple ArgExprs here.
2578 if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
2579 isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
2580 ExprType = FoldExpr;
2581 return ParseFoldExpression(ArgExprs[0], T);
2584 ExprType = SimpleExpr;
2585 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2589 InMessageExpressionRAIIObject InMessage(*this, false);
2591 Result = ParseExpression(MaybeTypeCast);
2592 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2593 // Correct typos in non-C++ code earlier so that implicit-cast-like
2594 // expressions are parsed correctly.
2595 Result = Actions.CorrectDelayedTyposInExpr(Result);
2598 if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
2599 NextToken().is(tok::ellipsis)) {
2600 ExprType = FoldExpr;
2601 return ParseFoldExpression(Result, T);
2603 ExprType = SimpleExpr;
2605 // Don't build a paren expression unless we actually match a ')'.
2606 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2608 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2612 if (Result.isInvalid()) {
2613 SkipUntil(tok::r_paren, StopAtSemi);
2618 RParenLoc = T.getCloseLocation();
2622 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2623 /// and we are at the left brace.
2626 /// postfix-expression: [C99 6.5.2]
2627 /// '(' type-name ')' '{' initializer-list '}'
2628 /// '(' type-name ')' '{' initializer-list ',' '}'
2631 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2632 SourceLocation LParenLoc,
2633 SourceLocation RParenLoc) {
2634 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2635 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2636 Diag(LParenLoc, diag::ext_c99_compound_literal);
2637 ExprResult Result = ParseInitializer();
2638 if (!Result.isInvalid() && Ty)
2639 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2643 /// ParseStringLiteralExpression - This handles the various token types that
2644 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2645 /// translation phase #6].
2648 /// primary-expression: [C99 6.5.1]
2651 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2652 assert(isTokenStringLiteral() && "Not a string literal!");
2654 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2655 // considered to be strings for concatenation purposes.
2656 SmallVector<Token, 4> StringToks;
2659 StringToks.push_back(Tok);
2660 ConsumeStringToken();
2661 } while (isTokenStringLiteral());
2663 // Pass the set of string tokens, ready for concatenation, to the actions.
2664 return Actions.ActOnStringLiteral(StringToks,
2665 AllowUserDefinedLiteral ? getCurScope()
2669 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2673 /// generic-selection:
2674 /// _Generic ( assignment-expression , generic-assoc-list )
2675 /// generic-assoc-list:
2676 /// generic-association
2677 /// generic-assoc-list , generic-association
2678 /// generic-association:
2679 /// type-name : assignment-expression
2680 /// default : assignment-expression
2682 ExprResult Parser::ParseGenericSelectionExpression() {
2683 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2684 SourceLocation KeyLoc = ConsumeToken();
2686 if (!getLangOpts().C11)
2687 Diag(KeyLoc, diag::ext_c11_generic_selection);
2689 BalancedDelimiterTracker T(*this, tok::l_paren);
2690 if (T.expectAndConsume())
2693 ExprResult ControllingExpr;
2695 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2697 EnterExpressionEvaluationContext Unevaluated(
2698 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
2700 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2701 if (ControllingExpr.isInvalid()) {
2702 SkipUntil(tok::r_paren, StopAtSemi);
2707 if (ExpectAndConsume(tok::comma)) {
2708 SkipUntil(tok::r_paren, StopAtSemi);
2712 SourceLocation DefaultLoc;
2717 if (Tok.is(tok::kw_default)) {
2718 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2719 // generic association."
2720 if (!DefaultLoc.isInvalid()) {
2721 Diag(Tok, diag::err_duplicate_default_assoc);
2722 Diag(DefaultLoc, diag::note_previous_default_assoc);
2723 SkipUntil(tok::r_paren, StopAtSemi);
2726 DefaultLoc = ConsumeToken();
2729 ColonProtectionRAIIObject X(*this);
2730 TypeResult TR = ParseTypeName();
2731 if (TR.isInvalid()) {
2732 SkipUntil(tok::r_paren, StopAtSemi);
2737 Types.push_back(Ty);
2739 if (ExpectAndConsume(tok::colon)) {
2740 SkipUntil(tok::r_paren, StopAtSemi);
2744 // FIXME: These expressions should be parsed in a potentially potentially
2745 // evaluated context.
2747 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2748 if (ER.isInvalid()) {
2749 SkipUntil(tok::r_paren, StopAtSemi);
2752 Exprs.push_back(ER.get());
2753 } while (TryConsumeToken(tok::comma));
2756 if (T.getCloseLocation().isInvalid())
2759 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2760 T.getCloseLocation(),
2761 ControllingExpr.get(),
2765 /// Parse A C++1z fold-expression after the opening paren and optional
2766 /// left-hand-side expression.
2769 /// fold-expression:
2770 /// ( cast-expression fold-operator ... )
2771 /// ( ... fold-operator cast-expression )
2772 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2773 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2774 BalancedDelimiterTracker &T) {
2775 if (LHS.isInvalid()) {
2780 tok::TokenKind Kind = tok::unknown;
2781 SourceLocation FirstOpLoc;
2782 if (LHS.isUsable()) {
2783 Kind = Tok.getKind();
2784 assert(isFoldOperator(Kind) && "missing fold-operator");
2785 FirstOpLoc = ConsumeToken();
2788 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2789 SourceLocation EllipsisLoc = ConsumeToken();
2792 if (Tok.isNot(tok::r_paren)) {
2793 if (!isFoldOperator(Tok.getKind()))
2794 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2796 if (Kind != tok::unknown && Tok.getKind() != Kind)
2797 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2798 << SourceRange(FirstOpLoc);
2799 Kind = Tok.getKind();
2802 RHS = ParseExpression();
2803 if (RHS.isInvalid()) {
2809 Diag(EllipsisLoc, getLangOpts().CPlusPlus17
2810 ? diag::warn_cxx14_compat_fold_expression
2811 : diag::ext_fold_expression);
2814 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2815 EllipsisLoc, RHS.get(), T.getCloseLocation());
2818 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2821 /// argument-expression-list:
2822 /// assignment-expression
2823 /// argument-expression-list , assignment-expression
2825 /// [C++] expression-list:
2826 /// [C++] assignment-expression
2827 /// [C++] expression-list , assignment-expression
2829 /// [C++0x] expression-list:
2830 /// [C++0x] initializer-list
2832 /// [C++0x] initializer-list
2833 /// [C++0x] initializer-clause ...[opt]
2834 /// [C++0x] initializer-list , initializer-clause ...[opt]
2836 /// [C++0x] initializer-clause:
2837 /// [C++0x] assignment-expression
2838 /// [C++0x] braced-init-list
2840 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2841 SmallVectorImpl<SourceLocation> &CommaLocs,
2842 llvm::function_ref<void()> Completer) {
2843 bool SawError = false;
2845 if (Tok.is(tok::code_completion)) {
2849 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2855 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2856 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2857 Expr = ParseBraceInitializer();
2859 Expr = ParseAssignmentExpression();
2861 if (Tok.is(tok::ellipsis))
2862 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2863 if (Expr.isInvalid()) {
2864 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2867 Exprs.push_back(Expr.get());
2870 if (Tok.isNot(tok::comma))
2872 // Move to the next argument, remember where the comma was.
2874 CommaLocs.push_back(ConsumeToken());
2876 checkPotentialAngleBracketDelimiter(Comma);
2879 // Ensure typos get diagnosed when errors were encountered while parsing the
2881 for (auto &E : Exprs) {
2882 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2883 if (Expr.isUsable()) E = Expr.get();
2889 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2890 /// used for misc language extensions.
2893 /// simple-expression-list:
2894 /// assignment-expression
2895 /// simple-expression-list , assignment-expression
2898 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2899 SmallVectorImpl<SourceLocation> &CommaLocs) {
2901 ExprResult Expr = ParseAssignmentExpression();
2902 if (Expr.isInvalid())
2905 Exprs.push_back(Expr.get());
2907 if (Tok.isNot(tok::comma))
2910 // Move to the next argument, remember where the comma was.
2912 CommaLocs.push_back(ConsumeToken());
2914 checkPotentialAngleBracketDelimiter(Comma);
2918 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2921 /// [clang] block-id:
2922 /// [clang] specifier-qualifier-list block-declarator
2924 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2925 if (Tok.is(tok::code_completion)) {
2926 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2927 return cutOffParsing();
2930 // Parse the specifier-qualifier-list piece.
2931 DeclSpec DS(AttrFactory);
2932 ParseSpecifierQualifierList(DS);
2934 // Parse the block-declarator.
2935 Declarator DeclaratorInfo(DS, DeclaratorContext::BlockLiteralContext);
2936 DeclaratorInfo.setFunctionDefinitionKind(FDK_Definition);
2937 ParseDeclarator(DeclaratorInfo);
2939 MaybeParseGNUAttributes(DeclaratorInfo);
2941 // Inform sema that we are starting a block.
2942 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2945 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2946 /// like ^(int x){ return x+1; }
2950 /// [clang] '^' block-args[opt] compound-statement
2951 /// [clang] '^' block-id compound-statement
2952 /// [clang] block-args:
2953 /// [clang] '(' parameter-list ')'
2955 ExprResult Parser::ParseBlockLiteralExpression() {
2956 assert(Tok.is(tok::caret) && "block literal starts with ^");
2957 SourceLocation CaretLoc = ConsumeToken();
2959 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2960 "block literal parsing");
2962 // Enter a scope to hold everything within the block. This includes the
2963 // argument decls, decls within the compound expression, etc. This also
2964 // allows determining whether a variable reference inside the block is
2965 // within or outside of the block.
2966 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2967 Scope::CompoundStmtScope | Scope::DeclScope);
2969 // Inform sema that we are starting a block.
2970 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2972 // Parse the return type if present.
2973 DeclSpec DS(AttrFactory);
2974 Declarator ParamInfo(DS, DeclaratorContext::BlockLiteralContext);
2975 ParamInfo.setFunctionDefinitionKind(FDK_Definition);
2976 // FIXME: Since the return type isn't actually parsed, it can't be used to
2977 // fill ParamInfo with an initial valid range, so do it manually.
2978 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2980 // If this block has arguments, parse them. There is no ambiguity here with
2981 // the expression case, because the expression case requires a parameter list.
2982 if (Tok.is(tok::l_paren)) {
2983 ParseParenDeclarator(ParamInfo);
2984 // Parse the pieces after the identifier as if we had "int(...)".
2985 // SetIdentifier sets the source range end, but in this case we're past
2987 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2988 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2989 ParamInfo.SetRangeEnd(Tmp);
2990 if (ParamInfo.isInvalidType()) {
2991 // If there was an error parsing the arguments, they may have
2992 // tried to use ^(x+y) which requires an argument list. Just
2993 // skip the whole block literal.
2994 Actions.ActOnBlockError(CaretLoc, getCurScope());
2998 MaybeParseGNUAttributes(ParamInfo);
3000 // Inform sema that we are starting a block.
3001 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3002 } else if (!Tok.is(tok::l_brace)) {
3003 ParseBlockId(CaretLoc);
3005 // Otherwise, pretend we saw (void).
3006 SourceLocation NoLoc;
3007 ParamInfo.AddTypeInfo(
3008 DeclaratorChunk::getFunction(/*HasProto=*/true,
3009 /*IsAmbiguous=*/false,
3010 /*RParenLoc=*/NoLoc,
3011 /*ArgInfo=*/nullptr,
3013 /*EllipsisLoc=*/NoLoc,
3014 /*RParenLoc=*/NoLoc,
3015 /*RefQualifierIsLvalueRef=*/true,
3016 /*RefQualifierLoc=*/NoLoc,
3017 /*MutableLoc=*/NoLoc, EST_None,
3018 /*ESpecRange=*/SourceRange(),
3019 /*Exceptions=*/nullptr,
3020 /*ExceptionRanges=*/nullptr,
3021 /*NumExceptions=*/0,
3022 /*NoexceptExpr=*/nullptr,
3023 /*ExceptionSpecTokens=*/nullptr,
3024 /*DeclsInPrototype=*/None, CaretLoc,
3025 CaretLoc, ParamInfo),
3028 MaybeParseGNUAttributes(ParamInfo);
3030 // Inform sema that we are starting a block.
3031 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3035 ExprResult Result(true);
3036 if (!Tok.is(tok::l_brace)) {
3037 // Saw something like: ^expr
3038 Diag(Tok, diag::err_expected_expression);
3039 Actions.ActOnBlockError(CaretLoc, getCurScope());
3043 StmtResult Stmt(ParseCompoundStatementBody());
3045 if (!Stmt.isInvalid())
3046 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3048 Actions.ActOnBlockError(CaretLoc, getCurScope());
3052 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3056 ExprResult Parser::ParseObjCBoolLiteral() {
3057 tok::TokenKind Kind = Tok.getKind();
3058 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3061 /// Validate availability spec list, emitting diagnostics if necessary. Returns
3062 /// true if invalid.
3063 static bool CheckAvailabilitySpecList(Parser &P,
3064 ArrayRef<AvailabilitySpec> AvailSpecs) {
3065 llvm::SmallSet<StringRef, 4> Platforms;
3066 bool HasOtherPlatformSpec = false;
3068 for (const auto &Spec : AvailSpecs) {
3069 if (Spec.isOtherPlatformSpec()) {
3070 if (HasOtherPlatformSpec) {
3071 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3075 HasOtherPlatformSpec = true;
3079 bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3081 // Rule out multiple version specs referring to the same platform.
3082 // For example, we emit an error for:
3083 // @available(macos 10.10, macos 10.11, *)
3084 StringRef Platform = Spec.getPlatform();
3085 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3086 << Spec.getEndLoc() << Platform;
3091 if (!HasOtherPlatformSpec) {
3092 SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3093 P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3094 << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3101 /// Parse availability query specification.
3103 /// availability-spec:
3105 /// identifier version-tuple
3106 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3107 if (Tok.is(tok::star)) {
3108 return AvailabilitySpec(ConsumeToken());
3110 // Parse the platform name.
3111 if (Tok.is(tok::code_completion)) {
3112 Actions.CodeCompleteAvailabilityPlatformName();
3116 if (Tok.isNot(tok::identifier)) {
3117 Diag(Tok, diag::err_avail_query_expected_platform_name);
3121 IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3122 SourceRange VersionRange;
3123 VersionTuple Version = ParseVersionTuple(VersionRange);
3125 if (Version.empty())
3128 StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3129 StringRef Platform =
3130 AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3132 if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3133 Diag(PlatformIdentifier->Loc,
3134 diag::err_avail_query_unrecognized_platform_name)
3139 return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3140 VersionRange.getEnd());
3144 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3145 assert(Tok.is(tok::kw___builtin_available) ||
3146 Tok.isObjCAtKeyword(tok::objc_available));
3148 // Eat the available or __builtin_available.
3151 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3152 if (Parens.expectAndConsume())
3155 SmallVector<AvailabilitySpec, 4> AvailSpecs;
3156 bool HasError = false;
3158 Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3162 AvailSpecs.push_back(*Spec);
3164 if (!TryConsumeToken(tok::comma))
3169 SkipUntil(tok::r_paren, StopAtSemi);
3173 CheckAvailabilitySpecList(*this, AvailSpecs);
3175 if (Parens.consumeClose())
3178 return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3179 Parens.getCloseLocation());