1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Provides the Expression parsing implementation.
13 /// Expressions in C99 basically consist of a bunch of binary operators with
14 /// unary operators and other random stuff at the leaves.
16 /// In the C99 grammar, these unary operators bind tightest and are represented
17 /// as the 'cast-expression' production. Everything else is either a binary
18 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
19 /// handled by ParseCastExpression, the higher level pieces are handled by
20 /// ParseBinaryExpression.
22 //===----------------------------------------------------------------------===//
24 #include "clang/Parse/Parser.h"
25 #include "RAIIObjectsForParser.h"
26 #include "clang/AST/ASTContext.h"
27 #include "clang/Basic/PrettyStackTrace.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/SmallString.h"
33 #include "llvm/ADT/SmallVector.h"
34 using namespace clang;
36 /// \brief Simple precedence-based parser for binary/ternary operators.
38 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
39 /// production. C99 specifies that the LHS of an assignment operator should be
40 /// parsed as a unary-expression, but consistency dictates that it be a
41 /// conditional-expession. In practice, the important thing here is that the
42 /// LHS of an assignment has to be an l-value, which productions between
43 /// unary-expression and conditional-expression don't produce. Because we want
44 /// consistency, we parse the LHS as a conditional-expression, then check for
45 /// l-value-ness in semantic analysis stages.
48 /// pm-expression: [C++ 5.5]
50 /// pm-expression '.*' cast-expression
51 /// pm-expression '->*' cast-expression
53 /// multiplicative-expression: [C99 6.5.5]
54 /// Note: in C++, apply pm-expression instead of cast-expression
56 /// multiplicative-expression '*' cast-expression
57 /// multiplicative-expression '/' cast-expression
58 /// multiplicative-expression '%' cast-expression
60 /// additive-expression: [C99 6.5.6]
61 /// multiplicative-expression
62 /// additive-expression '+' multiplicative-expression
63 /// additive-expression '-' multiplicative-expression
65 /// shift-expression: [C99 6.5.7]
66 /// additive-expression
67 /// shift-expression '<<' additive-expression
68 /// shift-expression '>>' additive-expression
70 /// relational-expression: [C99 6.5.8]
72 /// relational-expression '<' shift-expression
73 /// relational-expression '>' shift-expression
74 /// relational-expression '<=' shift-expression
75 /// relational-expression '>=' shift-expression
77 /// equality-expression: [C99 6.5.9]
78 /// relational-expression
79 /// equality-expression '==' relational-expression
80 /// equality-expression '!=' relational-expression
82 /// AND-expression: [C99 6.5.10]
83 /// equality-expression
84 /// AND-expression '&' equality-expression
86 /// exclusive-OR-expression: [C99 6.5.11]
88 /// exclusive-OR-expression '^' AND-expression
90 /// inclusive-OR-expression: [C99 6.5.12]
91 /// exclusive-OR-expression
92 /// inclusive-OR-expression '|' exclusive-OR-expression
94 /// logical-AND-expression: [C99 6.5.13]
95 /// inclusive-OR-expression
96 /// logical-AND-expression '&&' inclusive-OR-expression
98 /// logical-OR-expression: [C99 6.5.14]
99 /// logical-AND-expression
100 /// logical-OR-expression '||' logical-AND-expression
102 /// conditional-expression: [C99 6.5.15]
103 /// logical-OR-expression
104 /// logical-OR-expression '?' expression ':' conditional-expression
105 /// [GNU] logical-OR-expression '?' ':' conditional-expression
106 /// [C++] the third operand is an assignment-expression
108 /// assignment-expression: [C99 6.5.16]
109 /// conditional-expression
110 /// unary-expression assignment-operator assignment-expression
111 /// [C++] throw-expression [C++ 15]
113 /// assignment-operator: one of
114 /// = *= /= %= += -= <<= >>= &= ^= |=
116 /// expression: [C99 6.5.17]
117 /// assignment-expression ...[opt]
118 /// expression ',' assignment-expression ...[opt]
120 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
121 ExprResult LHS(ParseAssignmentExpression(isTypeCast));
122 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
125 /// This routine is called when the '@' is seen and consumed.
126 /// Current token is an Identifier and is not a 'try'. This
127 /// routine is necessary to disambiguate \@try-statement from,
128 /// for example, \@encode-expression.
131 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
132 ExprResult LHS(ParseObjCAtExpression(AtLoc));
133 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
136 /// This routine is called when a leading '__extension__' is seen and
137 /// consumed. This is necessary because the token gets consumed in the
138 /// process of disambiguating between an expression and a declaration.
140 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
141 ExprResult LHS(true);
143 // Silence extension warnings in the sub-expression
144 ExtensionRAIIObject O(Diags);
146 LHS = ParseCastExpression(false);
149 if (!LHS.isInvalid())
150 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
153 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
156 /// \brief Parse an expr that doesn't include (top-level) commas.
157 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
158 if (Tok.is(tok::code_completion)) {
159 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
164 if (Tok.is(tok::kw_throw))
165 return ParseThrowExpression();
166 if (Tok.is(tok::kw_co_yield))
167 return ParseCoyieldExpression();
169 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
170 /*isAddressOfOperand=*/false,
172 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
175 /// \brief Parse an assignment expression where part of an Objective-C message
176 /// send has already been parsed.
178 /// In this case \p LBracLoc indicates the location of the '[' of the message
179 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
180 /// the receiver of the message.
182 /// Since this handles full assignment-expression's, it handles postfix
183 /// expressions and other binary operators for these expressions as well.
185 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
186 SourceLocation SuperLoc,
187 ParsedType ReceiverType,
188 Expr *ReceiverExpr) {
190 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
191 ReceiverType, ReceiverExpr);
192 R = ParsePostfixExpressionSuffix(R);
193 return ParseRHSOfBinaryExpression(R, prec::Assignment);
197 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
198 // C++03 [basic.def.odr]p2:
199 // An expression is potentially evaluated unless it appears where an
200 // integral constant expression is required (see 5.19) [...].
201 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
202 EnterExpressionEvaluationContext Unevaluated(Actions,
203 Sema::ConstantEvaluated);
205 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
206 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
207 return Actions.ActOnConstantExpression(Res);
210 /// \brief Parse a constraint-expression.
213 /// constraint-expression: [Concepts TS temp.constr.decl p1]
214 /// logical-or-expression
216 ExprResult Parser::ParseConstraintExpression() {
217 // FIXME: this may erroneously consume a function-body as the braced
218 // initializer list of a compound literal
220 // FIXME: this may erroneously consume a parenthesized rvalue reference
221 // declarator as a parenthesized address-of-label expression
222 ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
223 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
228 bool Parser::isNotExpressionStart() {
229 tok::TokenKind K = Tok.getKind();
230 if (K == tok::l_brace || K == tok::r_brace ||
231 K == tok::kw_for || K == tok::kw_while ||
232 K == tok::kw_if || K == tok::kw_else ||
233 K == tok::kw_goto || K == tok::kw_try)
235 // If this is a decl-specifier, we can't be at the start of an expression.
236 return isKnownToBeDeclarationSpecifier();
239 static bool isFoldOperator(prec::Level Level) {
240 return Level > prec::Unknown && Level != prec::Conditional;
242 static bool isFoldOperator(tok::TokenKind Kind) {
243 return isFoldOperator(getBinOpPrecedence(Kind, false, true));
246 /// \brief Parse a binary expression that starts with \p LHS and has a
247 /// precedence of at least \p MinPrec.
249 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
250 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
251 GreaterThanIsOperator,
252 getLangOpts().CPlusPlus11);
253 SourceLocation ColonLoc;
256 // If this token has a lower precedence than we are allowed to parse (e.g.
257 // because we are called recursively, or because the token is not a binop),
259 if (NextTokPrec < MinPrec)
262 // Consume the operator, saving the operator token for error reporting.
266 if (OpToken.is(tok::caretcaret)) {
267 return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
269 // Bail out when encountering a comma followed by a token which can't
270 // possibly be the start of an expression. For instance:
271 // int f() { return 1, }
272 // We can't do this before consuming the comma, because
273 // isNotExpressionStart() looks at the token stream.
274 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
280 // If the next token is an ellipsis, then this is a fold-expression. Leave
281 // it alone so we can handle it in the paren expression.
282 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
283 // FIXME: We can't check this via lookahead before we consume the token
284 // because that tickles a lexer bug.
290 // Special case handling for the ternary operator.
291 ExprResult TernaryMiddle(true);
292 if (NextTokPrec == prec::Conditional) {
293 if (Tok.isNot(tok::colon)) {
294 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
295 ColonProtectionRAIIObject X(*this);
297 // Handle this production specially:
298 // logical-OR-expression '?' expression ':' conditional-expression
299 // In particular, the RHS of the '?' is 'expression', not
300 // 'logical-OR-expression' as we might expect.
301 TernaryMiddle = ParseExpression();
302 if (TernaryMiddle.isInvalid()) {
303 Actions.CorrectDelayedTyposInExpr(LHS);
305 TernaryMiddle = nullptr;
308 // Special case handling of "X ? Y : Z" where Y is empty:
309 // logical-OR-expression '?' ':' conditional-expression [GNU]
310 TernaryMiddle = nullptr;
311 Diag(Tok, diag::ext_gnu_conditional_expr);
314 if (!TryConsumeToken(tok::colon, ColonLoc)) {
315 // Otherwise, we're missing a ':'. Assume that this was a typo that
316 // the user forgot. If we're not in a macro expansion, we can suggest
317 // a fixit hint. If there were two spaces before the current token,
318 // suggest inserting the colon in between them, otherwise insert ": ".
319 SourceLocation FILoc = Tok.getLocation();
320 const char *FIText = ": ";
321 const SourceManager &SM = PP.getSourceManager();
322 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
323 assert(FILoc.isFileID());
324 bool IsInvalid = false;
325 const char *SourcePtr =
326 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
327 if (!IsInvalid && *SourcePtr == ' ') {
329 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
330 if (!IsInvalid && *SourcePtr == ' ') {
331 FILoc = FILoc.getLocWithOffset(-1);
337 Diag(Tok, diag::err_expected)
338 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
339 Diag(OpToken, diag::note_matching) << tok::question;
340 ColonLoc = Tok.getLocation();
344 // Code completion for the right-hand side of an assignment expression
345 // goes through a special hook that takes the left-hand side into account.
346 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
347 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
352 // Parse another leaf here for the RHS of the operator.
353 // ParseCastExpression works here because all RHS expressions in C have it
354 // as a prefix, at least. However, in C++, an assignment-expression could
355 // be a throw-expression, which is not a valid cast-expression.
356 // Therefore we need some special-casing here.
357 // Also note that the third operand of the conditional operator is
358 // an assignment-expression in C++, and in C++11, we can have a
359 // braced-init-list on the RHS of an assignment. For better diagnostics,
360 // parse as if we were allowed braced-init-lists everywhere, and check that
361 // they only appear on the RHS of assignments later.
363 bool RHSIsInitList = false;
364 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
365 RHS = ParseBraceInitializer();
366 RHSIsInitList = true;
367 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
368 RHS = ParseAssignmentExpression();
370 RHS = ParseCastExpression(false);
372 if (RHS.isInvalid()) {
373 // FIXME: Errors generated by the delayed typo correction should be
374 // printed before errors from parsing the RHS, not after.
375 Actions.CorrectDelayedTyposInExpr(LHS);
376 if (TernaryMiddle.isUsable())
377 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
381 // Remember the precedence of this operator and get the precedence of the
382 // operator immediately to the right of the RHS.
383 prec::Level ThisPrec = NextTokPrec;
384 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
385 getLangOpts().CPlusPlus11);
387 // Assignment and conditional expressions are right-associative.
388 bool isRightAssoc = ThisPrec == prec::Conditional ||
389 ThisPrec == prec::Assignment;
391 // Get the precedence of the operator to the right of the RHS. If it binds
392 // more tightly with RHS than we do, evaluate it completely first.
393 if (ThisPrec < NextTokPrec ||
394 (ThisPrec == NextTokPrec && isRightAssoc)) {
395 if (!RHS.isInvalid() && RHSIsInitList) {
396 Diag(Tok, diag::err_init_list_bin_op)
397 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
400 // If this is left-associative, only parse things on the RHS that bind
401 // more tightly than the current operator. If it is left-associative, it
402 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
403 // A=(B=(C=D)), where each paren is a level of recursion here.
404 // The function takes ownership of the RHS.
405 RHS = ParseRHSOfBinaryExpression(RHS,
406 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
407 RHSIsInitList = false;
409 if (RHS.isInvalid()) {
410 // FIXME: Errors generated by the delayed typo correction should be
411 // printed before errors from ParseRHSOfBinaryExpression, not after.
412 Actions.CorrectDelayedTyposInExpr(LHS);
413 if (TernaryMiddle.isUsable())
414 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
418 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
419 getLangOpts().CPlusPlus11);
422 if (!RHS.isInvalid() && RHSIsInitList) {
423 if (ThisPrec == prec::Assignment) {
424 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
425 << Actions.getExprRange(RHS.get());
427 Diag(OpToken, diag::err_init_list_bin_op)
428 << /*RHS*/1 << PP.getSpelling(OpToken)
429 << Actions.getExprRange(RHS.get());
434 ExprResult OrigLHS = LHS;
435 if (!LHS.isInvalid()) {
436 // Combine the LHS and RHS into the LHS (e.g. build AST).
437 if (TernaryMiddle.isInvalid()) {
438 // If we're using '>>' as an operator within a template
439 // argument list (in C++98), suggest the addition of
440 // parentheses so that the code remains well-formed in C++0x.
441 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
442 SuggestParentheses(OpToken.getLocation(),
443 diag::warn_cxx11_right_shift_in_template_arg,
444 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
445 Actions.getExprRange(RHS.get()).getEnd()));
447 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
448 OpToken.getKind(), LHS.get(), RHS.get());
451 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
452 LHS.get(), TernaryMiddle.get(),
455 // In this case, ActOnBinOp or ActOnConditionalOp performed the
456 // CorrectDelayedTyposInExpr check.
457 if (!getLangOpts().CPlusPlus)
460 // Ensure potential typos aren't left undiagnosed.
461 if (LHS.isInvalid()) {
462 Actions.CorrectDelayedTyposInExpr(OrigLHS);
463 Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
464 Actions.CorrectDelayedTyposInExpr(RHS);
469 /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
470 /// parse a unary-expression.
472 /// \p isAddressOfOperand exists because an id-expression that is the
473 /// operand of address-of gets special treatment due to member pointers.
475 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
476 bool isAddressOfOperand,
477 TypeCastState isTypeCast) {
479 ExprResult Res = ParseCastExpression(isUnaryExpression,
484 Diag(Tok, diag::err_expected_expression);
489 class CastExpressionIdValidator : public CorrectionCandidateCallback {
491 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
492 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
493 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
496 bool ValidateCandidate(const TypoCorrection &candidate) override {
497 NamedDecl *ND = candidate.getCorrectionDecl();
499 return candidate.isKeyword();
501 if (isa<TypeDecl>(ND))
502 return WantTypeSpecifiers;
504 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
507 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
510 for (auto *C : candidate) {
511 NamedDecl *ND = C->getUnderlyingDecl();
512 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
524 /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
525 /// a unary-expression.
527 /// \p isAddressOfOperand exists because an id-expression that is the operand
528 /// of address-of gets special treatment due to member pointers. NotCastExpr
529 /// is set to true if the token is not the start of a cast-expression, and no
530 /// diagnostic is emitted in this case and no tokens are consumed.
533 /// cast-expression: [C99 6.5.4]
535 /// '(' type-name ')' cast-expression
537 /// unary-expression: [C99 6.5.3]
538 /// postfix-expression
539 /// '++' unary-expression
540 /// '--' unary-expression
541 /// [Coro] 'co_await' cast-expression
542 /// unary-operator cast-expression
543 /// 'sizeof' unary-expression
544 /// 'sizeof' '(' type-name ')'
545 /// [C++11] 'sizeof' '...' '(' identifier ')'
546 /// [GNU] '__alignof' unary-expression
547 /// [GNU] '__alignof' '(' type-name ')'
548 /// [C11] '_Alignof' '(' type-name ')'
549 /// [C++11] 'alignof' '(' type-id ')'
550 /// [GNU] '&&' identifier
551 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
552 /// [C++] new-expression
553 /// [C++] delete-expression
555 /// unary-operator: one of
556 /// '&' '*' '+' '-' '~' '!'
557 /// [GNU] '__extension__' '__real' '__imag'
559 /// primary-expression: [C99 6.5.1]
561 /// [C++] id-expression
564 /// [C++] boolean-literal [C++ 2.13.5]
565 /// [C++11] 'nullptr' [C++11 2.14.7]
566 /// [C++11] user-defined-literal
567 /// '(' expression ')'
568 /// [C11] generic-selection
569 /// '__func__' [C99 6.4.2.2]
570 /// [GNU] '__FUNCTION__'
571 /// [MS] '__FUNCDNAME__'
572 /// [MS] 'L__FUNCTION__'
573 /// [GNU] '__PRETTY_FUNCTION__'
574 /// [GNU] '(' compound-statement ')'
575 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
576 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
577 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
579 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
581 /// [OBJC] '[' objc-message-expr ']'
582 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
583 /// [OBJC] '\@protocol' '(' identifier ')'
584 /// [OBJC] '\@encode' '(' type-name ')'
585 /// [OBJC] objc-string-literal
586 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
587 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
588 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
589 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
590 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
591 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
592 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
593 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
594 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
595 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
596 /// [C++] 'this' [C++ 9.3.2]
597 /// [G++] unary-type-trait '(' type-id ')'
598 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
599 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
600 /// [clang] '^' block-literal
602 /// constant: [C99 6.4.4]
604 /// floating-constant
605 /// enumeration-constant -> identifier
606 /// character-constant
608 /// id-expression: [C++ 5.1]
612 /// unqualified-id: [C++ 5.1]
614 /// operator-function-id
615 /// conversion-function-id
619 /// new-expression: [C++ 5.3.4]
620 /// '::'[opt] 'new' new-placement[opt] new-type-id
621 /// new-initializer[opt]
622 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
623 /// new-initializer[opt]
625 /// delete-expression: [C++ 5.3.5]
626 /// '::'[opt] 'delete' cast-expression
627 /// '::'[opt] 'delete' '[' ']' cast-expression
629 /// [GNU/Embarcadero] unary-type-trait:
630 /// '__is_arithmetic'
631 /// '__is_floating_point'
633 /// '__is_lvalue_expr'
634 /// '__is_rvalue_expr'
635 /// '__is_complete_type'
640 /// '__is_lvalue_reference'
641 /// '__is_rvalue_reference'
642 /// '__is_fundamental'
647 /// '__is_member_object_pointer'
648 /// '__is_member_function_pointer'
649 /// '__is_member_pointer'
653 /// '__is_standard_layout'
657 /// [GNU] unary-type-trait:
658 /// '__has_nothrow_assign'
659 /// '__has_nothrow_copy'
660 /// '__has_nothrow_constructor'
661 /// '__has_trivial_assign' [TODO]
662 /// '__has_trivial_copy' [TODO]
663 /// '__has_trivial_constructor'
664 /// '__has_trivial_destructor'
665 /// '__has_virtual_destructor'
666 /// '__is_abstract' [TODO]
668 /// '__is_empty' [TODO]
672 /// '__is_polymorphic'
673 /// '__is_sealed' [MS]
677 /// [Clang] unary-type-trait:
678 /// '__trivially_copyable'
680 /// binary-type-trait:
681 /// [GNU] '__is_base_of'
682 /// [MS] '__is_convertible_to'
683 /// '__is_convertible'
686 /// [Embarcadero] array-type-trait:
690 /// [Embarcadero] expression-trait:
691 /// '__is_lvalue_expr'
692 /// '__is_rvalue_expr'
695 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
696 bool isAddressOfOperand,
698 TypeCastState isTypeCast) {
700 tok::TokenKind SavedKind = Tok.getKind();
703 // This handles all of cast-expression, unary-expression, postfix-expression,
704 // and primary-expression. We handle them together like this for efficiency
705 // and to simplify handling of an expression starting with a '(' token: which
706 // may be one of a parenthesized expression, cast-expression, compound literal
707 // expression, or statement expression.
709 // If the parsed tokens consist of a primary-expression, the cases below
710 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
711 // to handle the postfix expression suffixes. Cases that cannot be followed
712 // by postfix exprs should return without invoking
713 // ParsePostfixExpressionSuffix.
716 // If this expression is limited to being a unary-expression, the parent can
717 // not start a cast expression.
718 ParenParseOption ParenExprType =
719 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
722 SourceLocation RParenLoc;
723 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
724 isTypeCast == IsTypeCast, CastTy, RParenLoc);
726 switch (ParenExprType) {
727 case SimpleExpr: break; // Nothing else to do.
728 case CompoundStmt: break; // Nothing else to do.
729 case CompoundLiteral:
730 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
731 // postfix-expression exist, parse them now.
734 // We have parsed the cast-expression and no postfix-expr pieces are
742 // primary-expression
743 case tok::numeric_constant:
744 // constant: integer-constant
745 // constant: floating-constant
747 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
753 return ParseCXXBoolLiteral();
755 case tok::kw___objc_yes:
756 case tok::kw___objc_no:
757 return ParseObjCBoolLiteral();
759 case tok::kw_nullptr:
760 Diag(Tok, diag::warn_cxx98_compat_nullptr);
761 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
763 case tok::annot_primary_expr:
764 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
765 Res = getExprAnnotation(Tok);
769 case tok::kw___super:
770 case tok::kw_decltype:
771 // Annotate the token and tail recurse.
772 if (TryAnnotateTypeOrScopeToken())
774 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
775 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
777 case tok::identifier: { // primary-expression: identifier
778 // unqualified-id: identifier
779 // constant: enumeration-constant
780 // Turn a potentially qualified name into a annot_typename or
781 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
782 if (getLangOpts().CPlusPlus) {
783 // Avoid the unnecessary parse-time lookup in the common case
784 // where the syntax forbids a type.
785 const Token &Next = NextToken();
787 // If this identifier was reverted from a token ID, and the next token
788 // is a parenthesis, this is likely to be a use of a type trait. Check
790 if (Next.is(tok::l_paren) &&
791 Tok.is(tok::identifier) &&
792 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
793 IdentifierInfo *II = Tok.getIdentifierInfo();
794 // Build up the mapping of revertible type traits, for future use.
795 if (RevertibleTypeTraits.empty()) {
796 #define RTT_JOIN(X,Y) X##Y
797 #define REVERTIBLE_TYPE_TRAIT(Name) \
798 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
799 = RTT_JOIN(tok::kw_,Name)
801 REVERTIBLE_TYPE_TRAIT(__is_abstract);
802 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
803 REVERTIBLE_TYPE_TRAIT(__is_array);
804 REVERTIBLE_TYPE_TRAIT(__is_assignable);
805 REVERTIBLE_TYPE_TRAIT(__is_base_of);
806 REVERTIBLE_TYPE_TRAIT(__is_class);
807 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
808 REVERTIBLE_TYPE_TRAIT(__is_compound);
809 REVERTIBLE_TYPE_TRAIT(__is_const);
810 REVERTIBLE_TYPE_TRAIT(__is_constructible);
811 REVERTIBLE_TYPE_TRAIT(__is_convertible);
812 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
813 REVERTIBLE_TYPE_TRAIT(__is_destructible);
814 REVERTIBLE_TYPE_TRAIT(__is_empty);
815 REVERTIBLE_TYPE_TRAIT(__is_enum);
816 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
817 REVERTIBLE_TYPE_TRAIT(__is_final);
818 REVERTIBLE_TYPE_TRAIT(__is_function);
819 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
820 REVERTIBLE_TYPE_TRAIT(__is_integral);
821 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
822 REVERTIBLE_TYPE_TRAIT(__is_literal);
823 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
824 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
825 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
826 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
827 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
828 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
829 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
830 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
831 REVERTIBLE_TYPE_TRAIT(__is_object);
832 REVERTIBLE_TYPE_TRAIT(__is_pod);
833 REVERTIBLE_TYPE_TRAIT(__is_pointer);
834 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
835 REVERTIBLE_TYPE_TRAIT(__is_reference);
836 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
837 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
838 REVERTIBLE_TYPE_TRAIT(__is_same);
839 REVERTIBLE_TYPE_TRAIT(__is_scalar);
840 REVERTIBLE_TYPE_TRAIT(__is_sealed);
841 REVERTIBLE_TYPE_TRAIT(__is_signed);
842 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
843 REVERTIBLE_TYPE_TRAIT(__is_trivial);
844 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
845 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
846 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
847 REVERTIBLE_TYPE_TRAIT(__is_union);
848 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
849 REVERTIBLE_TYPE_TRAIT(__is_void);
850 REVERTIBLE_TYPE_TRAIT(__is_volatile);
851 #undef REVERTIBLE_TYPE_TRAIT
855 // If we find that this is in fact the name of a type trait,
856 // update the token kind in place and parse again to treat it as
857 // the appropriate kind of type trait.
858 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
859 = RevertibleTypeTraits.find(II);
860 if (Known != RevertibleTypeTraits.end()) {
861 Tok.setKind(Known->second);
862 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
863 NotCastExpr, isTypeCast);
867 if ((!ColonIsSacred && Next.is(tok::colon)) ||
868 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
870 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
871 if (TryAnnotateTypeOrScopeToken())
873 if (!Tok.is(tok::identifier))
874 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
878 // Consume the identifier so that we can see if it is followed by a '(' or
880 IdentifierInfo &II = *Tok.getIdentifierInfo();
881 SourceLocation ILoc = ConsumeToken();
883 // Support 'Class.property' and 'super.property' notation.
884 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
885 (Actions.getTypeName(II, ILoc, getCurScope()) ||
886 // Allow the base to be 'super' if in an objc-method.
887 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
890 // Allow either an identifier or the keyword 'class' (in C++).
891 if (Tok.isNot(tok::identifier) &&
892 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
893 Diag(Tok, diag::err_expected_property_name);
896 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
897 SourceLocation PropertyLoc = ConsumeToken();
899 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
904 // In an Objective-C method, if we have "super" followed by an identifier,
905 // the token sequence is ill-formed. However, if there's a ':' or ']' after
906 // that identifier, this is probably a message send with a missing open
907 // bracket. Treat it as such.
908 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
909 getCurScope()->isInObjcMethodScope() &&
910 ((Tok.is(tok::identifier) &&
911 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
912 Tok.is(tok::code_completion))) {
913 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
918 // If we have an Objective-C class name followed by an identifier
919 // and either ':' or ']', this is an Objective-C class message
920 // send that's missing the opening '['. Recovery
921 // appropriately. Also take this path if we're performing code
922 // completion after an Objective-C class name.
923 if (getLangOpts().ObjC1 &&
924 ((Tok.is(tok::identifier) && !InMessageExpression) ||
925 Tok.is(tok::code_completion))) {
926 const Token& Next = NextToken();
927 if (Tok.is(tok::code_completion) ||
928 Next.is(tok::colon) || Next.is(tok::r_square))
929 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
930 if (Typ.get()->isObjCObjectOrInterfaceType()) {
931 // Fake up a Declarator to use with ActOnTypeName.
932 DeclSpec DS(AttrFactory);
933 DS.SetRangeStart(ILoc);
934 DS.SetRangeEnd(ILoc);
935 const char *PrevSpec = nullptr;
937 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
938 Actions.getASTContext().getPrintingPolicy());
940 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
941 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
946 Res = ParseObjCMessageExpressionBody(SourceLocation(),
953 // Make sure to pass down the right value for isAddressOfOperand.
954 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
955 isAddressOfOperand = false;
957 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
958 // need to know whether or not this identifier is a function designator or
961 CXXScopeSpec ScopeSpec;
962 SourceLocation TemplateKWLoc;
964 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
965 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
966 Validator->IsAddressOfOperand = isAddressOfOperand;
967 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
968 Validator->WantExpressionKeywords = false;
969 Validator->WantRemainingKeywords = false;
971 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
973 Name.setIdentifier(&II, ILoc);
974 Res = Actions.ActOnIdExpression(
975 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
976 isAddressOfOperand, std::move(Validator),
977 /*IsInlineAsmIdentifier=*/false,
978 Tok.is(tok::r_paren) ? nullptr : &Replacement);
979 if (!Res.isInvalid() && !Res.get()) {
980 UnconsumeToken(Replacement);
981 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
982 NotCastExpr, isTypeCast);
986 case tok::char_constant: // constant: character-constant
987 case tok::wide_char_constant:
988 case tok::utf8_char_constant:
989 case tok::utf16_char_constant:
990 case tok::utf32_char_constant:
991 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
994 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
995 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
996 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
997 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
998 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
999 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1000 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1003 case tok::string_literal: // primary-expression: string-literal
1004 case tok::wide_string_literal:
1005 case tok::utf8_string_literal:
1006 case tok::utf16_string_literal:
1007 case tok::utf32_string_literal:
1008 Res = ParseStringLiteralExpression(true);
1010 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1011 Res = ParseGenericSelectionExpression();
1013 case tok::kw___builtin_available:
1014 return ParseAvailabilityCheckExpr(Tok.getLocation());
1015 case tok::kw___builtin_va_arg:
1016 case tok::kw___builtin_offsetof:
1017 case tok::kw___builtin_choose_expr:
1018 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1019 case tok::kw___builtin_convertvector:
1020 return ParseBuiltinPrimaryExpression();
1021 case tok::kw___null:
1022 return Actions.ActOnGNUNullExpr(ConsumeToken());
1024 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1025 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1026 // C++ [expr.unary] has:
1027 // unary-expression:
1028 // ++ cast-expression
1029 // -- cast-expression
1030 Token SavedTok = Tok;
1032 // One special case is implicitly handled here: if the preceding tokens are
1033 // an ambiguous cast expression, such as "(T())++", then we recurse to
1034 // determine whether the '++' is prefix or postfix.
1035 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1036 /*isAddressOfOperand*/false, NotCastExpr,
1039 // If we return with NotCastExpr = true, we must not consume any tokens,
1040 // so put the token back where we found it.
1041 assert(Res.isInvalid());
1042 UnconsumeToken(SavedTok);
1045 if (!Res.isInvalid())
1046 Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1047 SavedKind, Res.get());
1050 case tok::amp: { // unary-expression: '&' cast-expression
1051 // Special treatment because of member pointers
1052 SourceLocation SavedLoc = ConsumeToken();
1053 Res = ParseCastExpression(false, true);
1054 if (!Res.isInvalid())
1055 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1059 case tok::star: // unary-expression: '*' cast-expression
1060 case tok::plus: // unary-expression: '+' cast-expression
1061 case tok::minus: // unary-expression: '-' cast-expression
1062 case tok::tilde: // unary-expression: '~' cast-expression
1063 case tok::exclaim: // unary-expression: '!' cast-expression
1064 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1065 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1066 SourceLocation SavedLoc = ConsumeToken();
1067 Res = ParseCastExpression(false);
1068 if (!Res.isInvalid())
1069 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1073 case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1074 SourceLocation CoawaitLoc = ConsumeToken();
1075 Res = ParseCastExpression(false);
1076 if (!Res.isInvalid())
1077 Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1081 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1082 // __extension__ silences extension warnings in the subexpression.
1083 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1084 SourceLocation SavedLoc = ConsumeToken();
1085 Res = ParseCastExpression(false);
1086 if (!Res.isInvalid())
1087 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1090 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1091 if (!getLangOpts().C11)
1092 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1094 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1095 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1096 // unary-expression: '__alignof' '(' type-name ')'
1097 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1098 // unary-expression: 'sizeof' '(' type-name ')'
1099 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1100 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1101 case tok::kw___builtin_omp_required_simd_align:
1102 return ParseUnaryExprOrTypeTraitExpression();
1103 case tok::ampamp: { // unary-expression: '&&' identifier
1104 SourceLocation AmpAmpLoc = ConsumeToken();
1105 if (Tok.isNot(tok::identifier))
1106 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1108 if (getCurScope()->getFnParent() == nullptr)
1109 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1111 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1112 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1114 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1118 case tok::kw_const_cast:
1119 case tok::kw_dynamic_cast:
1120 case tok::kw_reinterpret_cast:
1121 case tok::kw_static_cast:
1122 Res = ParseCXXCasts();
1124 case tok::kw_typeid:
1125 Res = ParseCXXTypeid();
1127 case tok::kw___uuidof:
1128 Res = ParseCXXUuidof();
1131 Res = ParseCXXThis();
1134 case tok::annot_typename:
1135 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1136 ParsedType Type = getTypeAnnotation(Tok);
1138 // Fake up a Declarator to use with ActOnTypeName.
1139 DeclSpec DS(AttrFactory);
1140 DS.SetRangeStart(Tok.getLocation());
1141 DS.SetRangeEnd(Tok.getLastLoc());
1143 const char *PrevSpec = nullptr;
1145 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1146 PrevSpec, DiagID, Type,
1147 Actions.getASTContext().getPrintingPolicy());
1149 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1150 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1155 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1161 case tok::annot_decltype:
1163 case tok::kw_wchar_t:
1164 case tok::kw_char16_t:
1165 case tok::kw_char32_t:
1170 case tok::kw___int64:
1171 case tok::kw___int128:
1172 case tok::kw_signed:
1173 case tok::kw_unsigned:
1176 case tok::kw_double:
1177 case tok::kw___float128:
1179 case tok::kw_typename:
1180 case tok::kw_typeof:
1181 case tok::kw___vector:
1182 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1183 #include "clang/Basic/OpenCLImageTypes.def"
1185 if (!getLangOpts().CPlusPlus) {
1186 Diag(Tok, diag::err_expected_expression);
1190 if (SavedKind == tok::kw_typename) {
1191 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1192 // typename-specifier braced-init-list
1193 if (TryAnnotateTypeOrScopeToken())
1196 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1197 // We are trying to parse a simple-type-specifier but might not get such
1198 // a token after error recovery.
1202 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1203 // simple-type-specifier braced-init-list
1205 DeclSpec DS(AttrFactory);
1207 ParseCXXSimpleTypeSpecifier(DS);
1208 if (Tok.isNot(tok::l_paren) &&
1209 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1210 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1211 << DS.getSourceRange());
1213 if (Tok.is(tok::l_brace))
1214 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1216 Res = ParseCXXTypeConstructExpression(DS);
1220 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1221 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1222 // (We can end up in this situation after tentative parsing.)
1223 if (TryAnnotateTypeOrScopeToken())
1225 if (!Tok.is(tok::annot_cxxscope))
1226 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1227 NotCastExpr, isTypeCast);
1229 Token Next = NextToken();
1230 if (Next.is(tok::annot_template_id)) {
1231 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1232 if (TemplateId->Kind == TNK_Type_template) {
1233 // We have a qualified template-id that we know refers to a
1234 // type, translate it into a type and continue parsing as a
1237 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1238 /*EnteringContext=*/false);
1239 AnnotateTemplateIdTokenAsType();
1240 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1241 NotCastExpr, isTypeCast);
1245 // Parse as an id-expression.
1246 Res = ParseCXXIdExpression(isAddressOfOperand);
1250 case tok::annot_template_id: { // [C++] template-id
1251 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1252 if (TemplateId->Kind == TNK_Type_template) {
1253 // We have a template-id that we know refers to a type,
1254 // translate it into a type and continue parsing as a cast
1256 AnnotateTemplateIdTokenAsType();
1257 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1258 NotCastExpr, isTypeCast);
1261 // Fall through to treat the template-id as an id-expression.
1264 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1265 Res = ParseCXXIdExpression(isAddressOfOperand);
1268 case tok::coloncolon: {
1269 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1270 // annotates the token, tail recurse.
1271 if (TryAnnotateTypeOrScopeToken())
1273 if (!Tok.is(tok::coloncolon))
1274 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1276 // ::new -> [C++] new-expression
1277 // ::delete -> [C++] delete-expression
1278 SourceLocation CCLoc = ConsumeToken();
1279 if (Tok.is(tok::kw_new))
1280 return ParseCXXNewExpression(true, CCLoc);
1281 if (Tok.is(tok::kw_delete))
1282 return ParseCXXDeleteExpression(true, CCLoc);
1284 // This is not a type name or scope specifier, it is an invalid expression.
1285 Diag(CCLoc, diag::err_expected_expression);
1289 case tok::kw_new: // [C++] new-expression
1290 return ParseCXXNewExpression(false, Tok.getLocation());
1292 case tok::kw_delete: // [C++] delete-expression
1293 return ParseCXXDeleteExpression(false, Tok.getLocation());
1295 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1296 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1297 SourceLocation KeyLoc = ConsumeToken();
1298 BalancedDelimiterTracker T(*this, tok::l_paren);
1300 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1302 // C++11 [expr.unary.noexcept]p1:
1303 // The noexcept operator determines whether the evaluation of its operand,
1304 // which is an unevaluated operand, can throw an exception.
1305 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1306 ExprResult Result = ParseExpression();
1310 if (!Result.isInvalid())
1311 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1312 Result.get(), T.getCloseLocation());
1316 #define TYPE_TRAIT(N,Spelling,K) \
1317 case tok::kw_##Spelling:
1318 #include "clang/Basic/TokenKinds.def"
1319 return ParseTypeTrait();
1321 case tok::kw___array_rank:
1322 case tok::kw___array_extent:
1323 return ParseArrayTypeTrait();
1325 case tok::kw___is_lvalue_expr:
1326 case tok::kw___is_rvalue_expr:
1327 return ParseExpressionTrait();
1330 SourceLocation AtLoc = ConsumeToken();
1331 return ParseObjCAtExpression(AtLoc);
1334 Res = ParseBlockLiteralExpression();
1336 case tok::code_completion: {
1337 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1342 if (getLangOpts().CPlusPlus11) {
1343 if (getLangOpts().ObjC1) {
1344 // C++11 lambda expressions and Objective-C message sends both start with a
1345 // square bracket. There are three possibilities here:
1346 // we have a valid lambda expression, we have an invalid lambda
1347 // expression, or we have something that doesn't appear to be a lambda.
1348 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1349 Res = TryParseLambdaExpression();
1350 if (!Res.isInvalid() && !Res.get())
1351 Res = ParseObjCMessageExpression();
1354 Res = ParseLambdaExpression();
1357 if (getLangOpts().ObjC1) {
1358 Res = ParseObjCMessageExpression();
1367 // Check to see whether Res is a function designator only. If it is and we
1368 // are compiling for OpenCL, we need to return an error as this implies
1369 // that the address of the function is being taken, which is illegal in CL.
1371 // These can be followed by postfix-expr pieces.
1372 Res = ParsePostfixExpressionSuffix(Res);
1373 if (getLangOpts().OpenCL)
1374 if (Expr *PostfixExpr = Res.get()) {
1375 QualType Ty = PostfixExpr->getType();
1376 if (!Ty.isNull() && Ty->isFunctionType()) {
1377 Diag(PostfixExpr->getExprLoc(),
1378 diag::err_opencl_taking_function_address_parser);
1386 /// \brief Once the leading part of a postfix-expression is parsed, this
1387 /// method parses any suffixes that apply.
1390 /// postfix-expression: [C99 6.5.2]
1391 /// primary-expression
1392 /// postfix-expression '[' expression ']'
1393 /// postfix-expression '[' braced-init-list ']'
1394 /// postfix-expression '(' argument-expression-list[opt] ')'
1395 /// postfix-expression '.' identifier
1396 /// postfix-expression '->' identifier
1397 /// postfix-expression '++'
1398 /// postfix-expression '--'
1399 /// '(' type-name ')' '{' initializer-list '}'
1400 /// '(' type-name ')' '{' initializer-list ',' '}'
1402 /// argument-expression-list: [C99 6.5.2]
1403 /// argument-expression ...[opt]
1404 /// argument-expression-list ',' assignment-expression ...[opt]
1407 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1408 // Now that the primary-expression piece of the postfix-expression has been
1409 // parsed, see if there are any postfix-expression pieces here.
1412 switch (Tok.getKind()) {
1413 case tok::code_completion:
1414 if (InMessageExpression)
1417 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1421 case tok::identifier:
1422 // If we see identifier: after an expression, and we're not already in a
1423 // message send, then this is probably a message send with a missing
1424 // opening bracket '['.
1425 if (getLangOpts().ObjC1 && !InMessageExpression &&
1426 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1427 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1428 nullptr, LHS.get());
1432 // Fall through; this isn't a message send.
1434 default: // Not a postfix-expression suffix.
1436 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1437 // If we have a array postfix expression that starts on a new line and
1438 // Objective-C is enabled, it is highly likely that the user forgot a
1439 // semicolon after the base expression and that the array postfix-expr is
1440 // actually another message send. In this case, do some look-ahead to see
1441 // if the contents of the square brackets are obviously not a valid
1442 // expression and recover by pretending there is no suffix.
1443 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1444 isSimpleObjCMessageExpression())
1447 // Reject array indices starting with a lambda-expression. '[[' is
1448 // reserved for attributes.
1449 if (CheckProhibitedCXX11Attribute()) {
1450 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1454 BalancedDelimiterTracker T(*this, tok::l_square);
1456 Loc = T.getOpenLocation();
1457 ExprResult Idx, Length;
1458 SourceLocation ColonLoc;
1459 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1460 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1461 Idx = ParseBraceInitializer();
1462 } else if (getLangOpts().OpenMP) {
1463 ColonProtectionRAIIObject RAII(*this);
1464 // Parse [: or [ expr or [ expr :
1465 if (!Tok.is(tok::colon)) {
1467 Idx = ParseExpression();
1469 if (Tok.is(tok::colon)) {
1471 ColonLoc = ConsumeToken();
1472 if (Tok.isNot(tok::r_square))
1473 Length = ParseExpression();
1476 Idx = ParseExpression();
1478 SourceLocation RLoc = Tok.getLocation();
1480 ExprResult OrigLHS = LHS;
1481 if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1482 Tok.is(tok::r_square)) {
1483 if (ColonLoc.isValid()) {
1484 LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1485 ColonLoc, Length.get(), RLoc);
1487 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1493 if (LHS.isInvalid()) {
1494 (void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
1495 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1496 (void)Actions.CorrectDelayedTyposInExpr(Length);
1506 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1507 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1508 // '(' argument-expression-list[opt] ')'
1509 tok::TokenKind OpKind = Tok.getKind();
1510 InMessageExpressionRAIIObject InMessage(*this, false);
1512 Expr *ExecConfig = nullptr;
1514 BalancedDelimiterTracker PT(*this, tok::l_paren);
1516 if (OpKind == tok::lesslessless) {
1517 ExprVector ExecConfigExprs;
1518 CommaLocsTy ExecConfigCommaLocs;
1519 SourceLocation OpenLoc = ConsumeToken();
1521 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1522 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1526 SourceLocation CloseLoc;
1527 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1528 } else if (LHS.isInvalid()) {
1529 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1531 // There was an error closing the brackets
1532 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1533 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1534 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1538 if (!LHS.isInvalid()) {
1539 if (ExpectAndConsume(tok::l_paren))
1542 Loc = PrevTokLocation;
1545 if (!LHS.isInvalid()) {
1546 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1550 if (ECResult.isInvalid())
1553 ExecConfig = ECResult.get();
1557 Loc = PT.getOpenLocation();
1560 ExprVector ArgExprs;
1561 CommaLocsTy CommaLocs;
1563 if (Tok.is(tok::code_completion)) {
1564 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1569 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1570 if (Tok.isNot(tok::r_paren)) {
1571 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1572 Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1574 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1576 } else if (LHS.isInvalid()) {
1577 for (auto &E : ArgExprs)
1578 Actions.CorrectDelayedTyposInExpr(E);
1584 if (LHS.isInvalid()) {
1585 SkipUntil(tok::r_paren, StopAtSemi);
1586 } else if (Tok.isNot(tok::r_paren)) {
1587 bool HadDelayedTypo = false;
1588 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1589 HadDelayedTypo = true;
1590 for (auto &E : ArgExprs)
1591 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1592 HadDelayedTypo = true;
1593 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1594 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1595 // the unmatched l_paren.
1597 SkipUntil(tok::r_paren, StopAtSemi);
1602 assert((ArgExprs.size() == 0 ||
1603 ArgExprs.size()-1 == CommaLocs.size())&&
1604 "Unexpected number of commas!");
1605 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1606 ArgExprs, Tok.getLocation(),
1615 // postfix-expression: p-e '->' template[opt] id-expression
1616 // postfix-expression: p-e '.' template[opt] id-expression
1617 tok::TokenKind OpKind = Tok.getKind();
1618 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1621 ParsedType ObjectType;
1622 bool MayBePseudoDestructor = false;
1623 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1624 Expr *Base = LHS.get();
1625 const Type* BaseType = Base->getType().getTypePtrOrNull();
1626 if (BaseType && Tok.is(tok::l_paren) &&
1627 (BaseType->isFunctionType() ||
1628 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1629 Diag(OpLoc, diag::err_function_is_not_record)
1630 << OpKind << Base->getSourceRange()
1631 << FixItHint::CreateRemoval(OpLoc);
1632 return ParsePostfixExpressionSuffix(Base);
1635 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1636 OpLoc, OpKind, ObjectType,
1637 MayBePseudoDestructor);
1638 if (LHS.isInvalid())
1641 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1642 /*EnteringContext=*/false,
1643 &MayBePseudoDestructor);
1644 if (SS.isNotEmpty())
1645 ObjectType = nullptr;
1648 if (Tok.is(tok::code_completion)) {
1649 // Code completion for a member access expression.
1650 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1651 OpLoc, OpKind == tok::arrow);
1657 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1658 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1663 // Either the action has told us that this cannot be a
1664 // pseudo-destructor expression (based on the type of base
1665 // expression), or we didn't see a '~' in the right place. We
1666 // can still parse a destructor name here, but in that case it
1667 // names a real destructor.
1668 // Allow explicit constructor calls in Microsoft mode.
1669 // FIXME: Add support for explicit call of template constructor.
1670 SourceLocation TemplateKWLoc;
1672 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1673 Tok.is(tok::kw_class)) {
1675 // After a '.' in a member access expression, treat the keyword
1676 // 'class' as if it were an identifier.
1678 // This hack allows property access to the 'class' method because it is
1679 // such a common method name. For other C++ keywords that are
1680 // Objective-C method names, one must use the message send syntax.
1681 IdentifierInfo *Id = Tok.getIdentifierInfo();
1682 SourceLocation Loc = ConsumeToken();
1683 Name.setIdentifier(Id, Loc);
1684 } else if (ParseUnqualifiedId(SS,
1685 /*EnteringContext=*/false,
1686 /*AllowDestructorName=*/true,
1687 /*AllowConstructorName=*/
1688 getLangOpts().MicrosoftExt,
1689 ObjectType, TemplateKWLoc, Name)) {
1690 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1694 if (!LHS.isInvalid())
1695 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1696 OpKind, SS, TemplateKWLoc, Name,
1697 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1701 case tok::plusplus: // postfix-expression: postfix-expression '++'
1702 case tok::minusminus: // postfix-expression: postfix-expression '--'
1703 if (!LHS.isInvalid()) {
1704 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1705 Tok.getKind(), LHS.get());
1713 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1714 /// vec_step and we are at the start of an expression or a parenthesized
1715 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1716 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1719 /// unary-expression: [C99 6.5.3]
1720 /// 'sizeof' unary-expression
1721 /// 'sizeof' '(' type-name ')'
1722 /// [GNU] '__alignof' unary-expression
1723 /// [GNU] '__alignof' '(' type-name ')'
1724 /// [C11] '_Alignof' '(' type-name ')'
1725 /// [C++0x] 'alignof' '(' type-id ')'
1727 /// [GNU] typeof-specifier:
1728 /// typeof ( expressions )
1729 /// typeof ( type-name )
1730 /// [GNU/C++] typeof unary-expression
1732 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1733 /// vec_step ( expressions )
1734 /// vec_step ( type-name )
1737 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1740 SourceRange &CastRange) {
1742 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1743 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1744 tok::kw___builtin_omp_required_simd_align) &&
1745 "Not a typeof/sizeof/alignof/vec_step expression!");
1749 // If the operand doesn't start with an '(', it must be an expression.
1750 if (Tok.isNot(tok::l_paren)) {
1751 // If construct allows a form without parenthesis, user may forget to put
1752 // pathenthesis around type name.
1753 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1754 tok::kw__Alignof)) {
1755 if (isTypeIdUnambiguously()) {
1756 DeclSpec DS(AttrFactory);
1757 ParseSpecifierQualifierList(DS);
1758 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1759 ParseDeclarator(DeclaratorInfo);
1761 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1762 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1763 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1765 << FixItHint::CreateInsertion(LParenLoc, "(")
1766 << FixItHint::CreateInsertion(RParenLoc, ")");
1773 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1774 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1779 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1781 // If it starts with a '(', we know that it is either a parenthesized
1782 // type-name, or it is a unary-expression that starts with a compound
1783 // literal, or starts with a primary-expression that is a parenthesized
1785 ParenParseOption ExprType = CastExpr;
1786 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1788 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1789 false, CastTy, RParenLoc);
1790 CastRange = SourceRange(LParenLoc, RParenLoc);
1792 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1794 if (ExprType == CastExpr) {
1799 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1800 // GNU typeof in C requires the expression to be parenthesized. Not so for
1801 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1802 // the start of a unary-expression, but doesn't include any postfix
1803 // pieces. Parse these now if present.
1804 if (!Operand.isInvalid())
1805 Operand = ParsePostfixExpressionSuffix(Operand.get());
1809 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1815 /// \brief Parse a sizeof or alignof expression.
1818 /// unary-expression: [C99 6.5.3]
1819 /// 'sizeof' unary-expression
1820 /// 'sizeof' '(' type-name ')'
1821 /// [C++11] 'sizeof' '...' '(' identifier ')'
1822 /// [GNU] '__alignof' unary-expression
1823 /// [GNU] '__alignof' '(' type-name ')'
1824 /// [C11] '_Alignof' '(' type-name ')'
1825 /// [C++11] 'alignof' '(' type-id ')'
1827 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1828 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1829 tok::kw__Alignof, tok::kw_vec_step,
1830 tok::kw___builtin_omp_required_simd_align) &&
1831 "Not a sizeof/alignof/vec_step expression!");
1835 // [C++11] 'sizeof' '...' '(' identifier ')'
1836 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1837 SourceLocation EllipsisLoc = ConsumeToken();
1838 SourceLocation LParenLoc, RParenLoc;
1839 IdentifierInfo *Name = nullptr;
1840 SourceLocation NameLoc;
1841 if (Tok.is(tok::l_paren)) {
1842 BalancedDelimiterTracker T(*this, tok::l_paren);
1844 LParenLoc = T.getOpenLocation();
1845 if (Tok.is(tok::identifier)) {
1846 Name = Tok.getIdentifierInfo();
1847 NameLoc = ConsumeToken();
1849 RParenLoc = T.getCloseLocation();
1850 if (RParenLoc.isInvalid())
1851 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1853 Diag(Tok, diag::err_expected_parameter_pack);
1854 SkipUntil(tok::r_paren, StopAtSemi);
1856 } else if (Tok.is(tok::identifier)) {
1857 Name = Tok.getIdentifierInfo();
1858 NameLoc = ConsumeToken();
1859 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1860 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1861 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1863 << FixItHint::CreateInsertion(LParenLoc, "(")
1864 << FixItHint::CreateInsertion(RParenLoc, ")");
1866 Diag(Tok, diag::err_sizeof_parameter_pack);
1872 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1873 Sema::ReuseLambdaContextDecl);
1875 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1876 OpTok.getLocation(),
1881 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1882 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1884 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1885 Sema::ReuseLambdaContextDecl);
1889 SourceRange CastRange;
1890 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1895 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1896 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1897 ExprKind = UETT_AlignOf;
1898 else if (OpTok.is(tok::kw_vec_step))
1899 ExprKind = UETT_VecStep;
1900 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
1901 ExprKind = UETT_OpenMPRequiredSimdAlign;
1904 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1907 CastTy.getAsOpaquePtr(),
1910 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1911 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1913 // If we get here, the operand to the sizeof/alignof was an expresion.
1914 if (!Operand.isInvalid())
1915 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1923 /// ParseBuiltinPrimaryExpression
1926 /// primary-expression: [C99 6.5.1]
1927 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1928 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1929 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1931 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1932 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1934 /// [GNU] offsetof-member-designator:
1935 /// [GNU] identifier
1936 /// [GNU] offsetof-member-designator '.' identifier
1937 /// [GNU] offsetof-member-designator '[' expression ']'
1939 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1941 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1943 tok::TokenKind T = Tok.getKind();
1944 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
1946 // All of these start with an open paren.
1947 if (Tok.isNot(tok::l_paren))
1948 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
1951 BalancedDelimiterTracker PT(*this, tok::l_paren);
1957 default: llvm_unreachable("Not a builtin primary expression!");
1958 case tok::kw___builtin_va_arg: {
1959 ExprResult Expr(ParseAssignmentExpression());
1961 if (ExpectAndConsume(tok::comma)) {
1962 SkipUntil(tok::r_paren, StopAtSemi);
1966 TypeResult Ty = ParseTypeName();
1968 if (Tok.isNot(tok::r_paren)) {
1969 Diag(Tok, diag::err_expected) << tok::r_paren;
1973 if (Expr.isInvalid() || Ty.isInvalid())
1976 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
1979 case tok::kw___builtin_offsetof: {
1980 SourceLocation TypeLoc = Tok.getLocation();
1981 TypeResult Ty = ParseTypeName();
1982 if (Ty.isInvalid()) {
1983 SkipUntil(tok::r_paren, StopAtSemi);
1987 if (ExpectAndConsume(tok::comma)) {
1988 SkipUntil(tok::r_paren, StopAtSemi);
1992 // We must have at least one identifier here.
1993 if (Tok.isNot(tok::identifier)) {
1994 Diag(Tok, diag::err_expected) << tok::identifier;
1995 SkipUntil(tok::r_paren, StopAtSemi);
1999 // Keep track of the various subcomponents we see.
2000 SmallVector<Sema::OffsetOfComponent, 4> Comps;
2002 Comps.push_back(Sema::OffsetOfComponent());
2003 Comps.back().isBrackets = false;
2004 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2005 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2007 // FIXME: This loop leaks the index expressions on error.
2009 if (Tok.is(tok::period)) {
2010 // offsetof-member-designator: offsetof-member-designator '.' identifier
2011 Comps.push_back(Sema::OffsetOfComponent());
2012 Comps.back().isBrackets = false;
2013 Comps.back().LocStart = ConsumeToken();
2015 if (Tok.isNot(tok::identifier)) {
2016 Diag(Tok, diag::err_expected) << tok::identifier;
2017 SkipUntil(tok::r_paren, StopAtSemi);
2020 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2021 Comps.back().LocEnd = ConsumeToken();
2023 } else if (Tok.is(tok::l_square)) {
2024 if (CheckProhibitedCXX11Attribute())
2027 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2028 Comps.push_back(Sema::OffsetOfComponent());
2029 Comps.back().isBrackets = true;
2030 BalancedDelimiterTracker ST(*this, tok::l_square);
2032 Comps.back().LocStart = ST.getOpenLocation();
2033 Res = ParseExpression();
2034 if (Res.isInvalid()) {
2035 SkipUntil(tok::r_paren, StopAtSemi);
2038 Comps.back().U.E = Res.get();
2041 Comps.back().LocEnd = ST.getCloseLocation();
2043 if (Tok.isNot(tok::r_paren)) {
2046 } else if (Ty.isInvalid()) {
2050 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2052 PT.getCloseLocation());
2059 case tok::kw___builtin_choose_expr: {
2060 ExprResult Cond(ParseAssignmentExpression());
2061 if (Cond.isInvalid()) {
2062 SkipUntil(tok::r_paren, StopAtSemi);
2065 if (ExpectAndConsume(tok::comma)) {
2066 SkipUntil(tok::r_paren, StopAtSemi);
2070 ExprResult Expr1(ParseAssignmentExpression());
2071 if (Expr1.isInvalid()) {
2072 SkipUntil(tok::r_paren, StopAtSemi);
2075 if (ExpectAndConsume(tok::comma)) {
2076 SkipUntil(tok::r_paren, StopAtSemi);
2080 ExprResult Expr2(ParseAssignmentExpression());
2081 if (Expr2.isInvalid()) {
2082 SkipUntil(tok::r_paren, StopAtSemi);
2085 if (Tok.isNot(tok::r_paren)) {
2086 Diag(Tok, diag::err_expected) << tok::r_paren;
2089 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2090 Expr2.get(), ConsumeParen());
2093 case tok::kw___builtin_astype: {
2094 // The first argument is an expression to be converted, followed by a comma.
2095 ExprResult Expr(ParseAssignmentExpression());
2096 if (Expr.isInvalid()) {
2097 SkipUntil(tok::r_paren, StopAtSemi);
2101 if (ExpectAndConsume(tok::comma)) {
2102 SkipUntil(tok::r_paren, StopAtSemi);
2106 // Second argument is the type to bitcast to.
2107 TypeResult DestTy = ParseTypeName();
2108 if (DestTy.isInvalid())
2111 // Attempt to consume the r-paren.
2112 if (Tok.isNot(tok::r_paren)) {
2113 Diag(Tok, diag::err_expected) << tok::r_paren;
2114 SkipUntil(tok::r_paren, StopAtSemi);
2118 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2122 case tok::kw___builtin_convertvector: {
2123 // The first argument is an expression to be converted, followed by a comma.
2124 ExprResult Expr(ParseAssignmentExpression());
2125 if (Expr.isInvalid()) {
2126 SkipUntil(tok::r_paren, StopAtSemi);
2130 if (ExpectAndConsume(tok::comma)) {
2131 SkipUntil(tok::r_paren, StopAtSemi);
2135 // Second argument is the type to bitcast to.
2136 TypeResult DestTy = ParseTypeName();
2137 if (DestTy.isInvalid())
2140 // Attempt to consume the r-paren.
2141 if (Tok.isNot(tok::r_paren)) {
2142 Diag(Tok, diag::err_expected) << tok::r_paren;
2143 SkipUntil(tok::r_paren, StopAtSemi);
2147 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2153 if (Res.isInvalid())
2156 // These can be followed by postfix-expr pieces because they are
2157 // primary-expressions.
2158 return ParsePostfixExpressionSuffix(Res.get());
2161 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2162 /// based on what is allowed by ExprType. The actual thing parsed is returned
2163 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2164 /// not the parsed cast-expression.
2167 /// primary-expression: [C99 6.5.1]
2168 /// '(' expression ')'
2169 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2170 /// postfix-expression: [C99 6.5.2]
2171 /// '(' type-name ')' '{' initializer-list '}'
2172 /// '(' type-name ')' '{' initializer-list ',' '}'
2173 /// cast-expression: [C99 6.5.4]
2174 /// '(' type-name ')' cast-expression
2175 /// [ARC] bridged-cast-expression
2176 /// [ARC] bridged-cast-expression:
2177 /// (__bridge type-name) cast-expression
2178 /// (__bridge_transfer type-name) cast-expression
2179 /// (__bridge_retained type-name) cast-expression
2180 /// fold-expression: [C++1z]
2181 /// '(' cast-expression fold-operator '...' ')'
2182 /// '(' '...' fold-operator cast-expression ')'
2183 /// '(' cast-expression fold-operator '...'
2184 /// fold-operator cast-expression ')'
2187 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2188 bool isTypeCast, ParsedType &CastTy,
2189 SourceLocation &RParenLoc) {
2190 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2191 ColonProtectionRAIIObject ColonProtection(*this, false);
2192 BalancedDelimiterTracker T(*this, tok::l_paren);
2193 if (T.consumeOpen())
2195 SourceLocation OpenLoc = T.getOpenLocation();
2197 ExprResult Result(true);
2198 bool isAmbiguousTypeId;
2201 if (Tok.is(tok::code_completion)) {
2202 Actions.CodeCompleteOrdinaryName(getCurScope(),
2203 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2204 : Sema::PCC_Expression);
2209 // Diagnose use of bridge casts in non-arc mode.
2210 bool BridgeCast = (getLangOpts().ObjC2 &&
2211 Tok.isOneOf(tok::kw___bridge,
2212 tok::kw___bridge_transfer,
2213 tok::kw___bridge_retained,
2214 tok::kw___bridge_retain));
2215 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2216 if (!TryConsumeToken(tok::kw___bridge)) {
2217 StringRef BridgeCastName = Tok.getName();
2218 SourceLocation BridgeKeywordLoc = ConsumeToken();
2219 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2220 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2222 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2227 // None of these cases should fall through with an invalid Result
2228 // unless they've already reported an error.
2229 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2230 Diag(Tok, diag::ext_gnu_statement_expr);
2232 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2233 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2235 // Find the nearest non-record decl context. Variables declared in a
2236 // statement expression behave as if they were declared in the enclosing
2237 // function, block, or other code construct.
2238 DeclContext *CodeDC = Actions.CurContext;
2239 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2240 CodeDC = CodeDC->getParent();
2241 assert(CodeDC && !CodeDC->isFileContext() &&
2242 "statement expr not in code context");
2244 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2246 Actions.ActOnStartStmtExpr();
2248 StmtResult Stmt(ParseCompoundStatement(true));
2249 ExprType = CompoundStmt;
2251 // If the substmt parsed correctly, build the AST node.
2252 if (!Stmt.isInvalid()) {
2253 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2255 Actions.ActOnStmtExprError();
2258 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2259 tok::TokenKind tokenKind = Tok.getKind();
2260 SourceLocation BridgeKeywordLoc = ConsumeToken();
2262 // Parse an Objective-C ARC ownership cast expression.
2263 ObjCBridgeCastKind Kind;
2264 if (tokenKind == tok::kw___bridge)
2266 else if (tokenKind == tok::kw___bridge_transfer)
2267 Kind = OBC_BridgeTransfer;
2268 else if (tokenKind == tok::kw___bridge_retained)
2269 Kind = OBC_BridgeRetained;
2271 // As a hopefully temporary workaround, allow __bridge_retain as
2272 // a synonym for __bridge_retained, but only in system headers.
2273 assert(tokenKind == tok::kw___bridge_retain);
2274 Kind = OBC_BridgeRetained;
2275 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2276 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2277 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2278 "__bridge_retained");
2281 TypeResult Ty = ParseTypeName();
2283 ColonProtection.restore();
2284 RParenLoc = T.getCloseLocation();
2285 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2287 if (Ty.isInvalid() || SubExpr.isInvalid())
2290 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2291 BridgeKeywordLoc, Ty.get(),
2292 RParenLoc, SubExpr.get());
2293 } else if (ExprType >= CompoundLiteral &&
2294 isTypeIdInParens(isAmbiguousTypeId)) {
2296 // Otherwise, this is a compound literal expression or cast expression.
2298 // In C++, if the type-id is ambiguous we disambiguate based on context.
2299 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2300 // in which case we should treat it as type-id.
2301 // if stopIfCastExpr is false, we need to determine the context past the
2302 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2303 if (isAmbiguousTypeId && !stopIfCastExpr) {
2304 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2306 RParenLoc = T.getCloseLocation();
2310 // Parse the type declarator.
2311 DeclSpec DS(AttrFactory);
2312 ParseSpecifierQualifierList(DS);
2313 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2314 ParseDeclarator(DeclaratorInfo);
2316 // If our type is followed by an identifier and either ':' or ']', then
2317 // this is probably an Objective-C message send where the leading '[' is
2318 // missing. Recover as if that were the case.
2319 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2320 !InMessageExpression && getLangOpts().ObjC1 &&
2321 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2324 InMessageExpressionRAIIObject InMessage(*this, false);
2325 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2327 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2333 ColonProtection.restore();
2334 RParenLoc = T.getCloseLocation();
2335 if (Tok.is(tok::l_brace)) {
2336 ExprType = CompoundLiteral;
2339 InMessageExpressionRAIIObject InMessage(*this, false);
2340 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2342 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2345 if (ExprType == CastExpr) {
2346 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2348 if (DeclaratorInfo.isInvalidType())
2351 // Note that this doesn't parse the subsequent cast-expression, it just
2352 // returns the parsed type to the callee.
2353 if (stopIfCastExpr) {
2356 InMessageExpressionRAIIObject InMessage(*this, false);
2357 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2360 return ExprResult();
2363 // Reject the cast of super idiom in ObjC.
2364 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2365 Tok.getIdentifierInfo() == Ident_super &&
2366 getCurScope()->isInObjcMethodScope() &&
2367 GetLookAheadToken(1).isNot(tok::period)) {
2368 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2369 << SourceRange(OpenLoc, RParenLoc);
2373 // Parse the cast-expression that follows it next.
2374 // TODO: For cast expression with CastTy.
2375 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2376 /*isAddressOfOperand=*/false,
2377 /*isTypeCast=*/IsTypeCast);
2378 if (!Result.isInvalid()) {
2379 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2380 DeclaratorInfo, CastTy,
2381 RParenLoc, Result.get());
2386 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2389 } else if (Tok.is(tok::ellipsis) &&
2390 isFoldOperator(NextToken().getKind())) {
2391 return ParseFoldExpression(ExprResult(), T);
2392 } else if (isTypeCast) {
2393 // Parse the expression-list.
2394 InMessageExpressionRAIIObject InMessage(*this, false);
2396 ExprVector ArgExprs;
2397 CommaLocsTy CommaLocs;
2399 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2400 // FIXME: If we ever support comma expressions as operands to
2401 // fold-expressions, we'll need to allow multiple ArgExprs here.
2402 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2403 NextToken().is(tok::ellipsis))
2404 return ParseFoldExpression(Result, T);
2406 ExprType = SimpleExpr;
2407 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2411 InMessageExpressionRAIIObject InMessage(*this, false);
2413 Result = ParseExpression(MaybeTypeCast);
2414 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2415 // Correct typos in non-C++ code earlier so that implicit-cast-like
2416 // expressions are parsed correctly.
2417 Result = Actions.CorrectDelayedTyposInExpr(Result);
2419 ExprType = SimpleExpr;
2421 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2422 return ParseFoldExpression(Result, T);
2424 // Don't build a paren expression unless we actually match a ')'.
2425 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2427 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2431 if (Result.isInvalid()) {
2432 SkipUntil(tok::r_paren, StopAtSemi);
2437 RParenLoc = T.getCloseLocation();
2441 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2442 /// and we are at the left brace.
2445 /// postfix-expression: [C99 6.5.2]
2446 /// '(' type-name ')' '{' initializer-list '}'
2447 /// '(' type-name ')' '{' initializer-list ',' '}'
2450 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2451 SourceLocation LParenLoc,
2452 SourceLocation RParenLoc) {
2453 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2454 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2455 Diag(LParenLoc, diag::ext_c99_compound_literal);
2456 ExprResult Result = ParseInitializer();
2457 if (!Result.isInvalid() && Ty)
2458 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2462 /// ParseStringLiteralExpression - This handles the various token types that
2463 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2464 /// translation phase #6].
2467 /// primary-expression: [C99 6.5.1]
2470 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2471 assert(isTokenStringLiteral() && "Not a string literal!");
2473 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2474 // considered to be strings for concatenation purposes.
2475 SmallVector<Token, 4> StringToks;
2478 StringToks.push_back(Tok);
2479 ConsumeStringToken();
2480 } while (isTokenStringLiteral());
2482 // Pass the set of string tokens, ready for concatenation, to the actions.
2483 return Actions.ActOnStringLiteral(StringToks,
2484 AllowUserDefinedLiteral ? getCurScope()
2488 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2492 /// generic-selection:
2493 /// _Generic ( assignment-expression , generic-assoc-list )
2494 /// generic-assoc-list:
2495 /// generic-association
2496 /// generic-assoc-list , generic-association
2497 /// generic-association:
2498 /// type-name : assignment-expression
2499 /// default : assignment-expression
2501 ExprResult Parser::ParseGenericSelectionExpression() {
2502 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2503 SourceLocation KeyLoc = ConsumeToken();
2505 if (!getLangOpts().C11)
2506 Diag(KeyLoc, diag::ext_c11_generic_selection);
2508 BalancedDelimiterTracker T(*this, tok::l_paren);
2509 if (T.expectAndConsume())
2512 ExprResult ControllingExpr;
2514 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2516 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2518 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2519 if (ControllingExpr.isInvalid()) {
2520 SkipUntil(tok::r_paren, StopAtSemi);
2525 if (ExpectAndConsume(tok::comma)) {
2526 SkipUntil(tok::r_paren, StopAtSemi);
2530 SourceLocation DefaultLoc;
2535 if (Tok.is(tok::kw_default)) {
2536 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2537 // generic association."
2538 if (!DefaultLoc.isInvalid()) {
2539 Diag(Tok, diag::err_duplicate_default_assoc);
2540 Diag(DefaultLoc, diag::note_previous_default_assoc);
2541 SkipUntil(tok::r_paren, StopAtSemi);
2544 DefaultLoc = ConsumeToken();
2547 ColonProtectionRAIIObject X(*this);
2548 TypeResult TR = ParseTypeName();
2549 if (TR.isInvalid()) {
2550 SkipUntil(tok::r_paren, StopAtSemi);
2555 Types.push_back(Ty);
2557 if (ExpectAndConsume(tok::colon)) {
2558 SkipUntil(tok::r_paren, StopAtSemi);
2562 // FIXME: These expressions should be parsed in a potentially potentially
2563 // evaluated context.
2565 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2566 if (ER.isInvalid()) {
2567 SkipUntil(tok::r_paren, StopAtSemi);
2570 Exprs.push_back(ER.get());
2571 } while (TryConsumeToken(tok::comma));
2574 if (T.getCloseLocation().isInvalid())
2577 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2578 T.getCloseLocation(),
2579 ControllingExpr.get(),
2583 /// \brief Parse A C++1z fold-expression after the opening paren and optional
2584 /// left-hand-side expression.
2587 /// fold-expression:
2588 /// ( cast-expression fold-operator ... )
2589 /// ( ... fold-operator cast-expression )
2590 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2591 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2592 BalancedDelimiterTracker &T) {
2593 if (LHS.isInvalid()) {
2598 tok::TokenKind Kind = tok::unknown;
2599 SourceLocation FirstOpLoc;
2600 if (LHS.isUsable()) {
2601 Kind = Tok.getKind();
2602 assert(isFoldOperator(Kind) && "missing fold-operator");
2603 FirstOpLoc = ConsumeToken();
2606 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2607 SourceLocation EllipsisLoc = ConsumeToken();
2610 if (Tok.isNot(tok::r_paren)) {
2611 if (!isFoldOperator(Tok.getKind()))
2612 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2614 if (Kind != tok::unknown && Tok.getKind() != Kind)
2615 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2616 << SourceRange(FirstOpLoc);
2617 Kind = Tok.getKind();
2620 RHS = ParseExpression();
2621 if (RHS.isInvalid()) {
2627 Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
2628 ? diag::warn_cxx14_compat_fold_expression
2629 : diag::ext_fold_expression);
2632 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2633 EllipsisLoc, RHS.get(), T.getCloseLocation());
2636 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2639 /// argument-expression-list:
2640 /// assignment-expression
2641 /// argument-expression-list , assignment-expression
2643 /// [C++] expression-list:
2644 /// [C++] assignment-expression
2645 /// [C++] expression-list , assignment-expression
2647 /// [C++0x] expression-list:
2648 /// [C++0x] initializer-list
2650 /// [C++0x] initializer-list
2651 /// [C++0x] initializer-clause ...[opt]
2652 /// [C++0x] initializer-list , initializer-clause ...[opt]
2654 /// [C++0x] initializer-clause:
2655 /// [C++0x] assignment-expression
2656 /// [C++0x] braced-init-list
2658 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2659 SmallVectorImpl<SourceLocation> &CommaLocs,
2660 std::function<void()> Completer) {
2661 bool SawError = false;
2663 if (Tok.is(tok::code_completion)) {
2667 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2673 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2674 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2675 Expr = ParseBraceInitializer();
2677 Expr = ParseAssignmentExpression();
2679 if (Tok.is(tok::ellipsis))
2680 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2681 if (Expr.isInvalid()) {
2682 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2685 Exprs.push_back(Expr.get());
2688 if (Tok.isNot(tok::comma))
2690 // Move to the next argument, remember where the comma was.
2691 CommaLocs.push_back(ConsumeToken());
2694 // Ensure typos get diagnosed when errors were encountered while parsing the
2696 for (auto &E : Exprs) {
2697 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2698 if (Expr.isUsable()) E = Expr.get();
2704 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2705 /// used for misc language extensions.
2708 /// simple-expression-list:
2709 /// assignment-expression
2710 /// simple-expression-list , assignment-expression
2713 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2714 SmallVectorImpl<SourceLocation> &CommaLocs) {
2716 ExprResult Expr = ParseAssignmentExpression();
2717 if (Expr.isInvalid())
2720 Exprs.push_back(Expr.get());
2722 if (Tok.isNot(tok::comma))
2725 // Move to the next argument, remember where the comma was.
2726 CommaLocs.push_back(ConsumeToken());
2730 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2733 /// [clang] block-id:
2734 /// [clang] specifier-qualifier-list block-declarator
2736 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2737 if (Tok.is(tok::code_completion)) {
2738 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2739 return cutOffParsing();
2742 // Parse the specifier-qualifier-list piece.
2743 DeclSpec DS(AttrFactory);
2744 ParseSpecifierQualifierList(DS);
2746 // Parse the block-declarator.
2747 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2748 ParseDeclarator(DeclaratorInfo);
2750 MaybeParseGNUAttributes(DeclaratorInfo);
2752 // Inform sema that we are starting a block.
2753 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2756 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2757 /// like ^(int x){ return x+1; }
2761 /// [clang] '^' block-args[opt] compound-statement
2762 /// [clang] '^' block-id compound-statement
2763 /// [clang] block-args:
2764 /// [clang] '(' parameter-list ')'
2766 ExprResult Parser::ParseBlockLiteralExpression() {
2767 assert(Tok.is(tok::caret) && "block literal starts with ^");
2768 SourceLocation CaretLoc = ConsumeToken();
2770 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2771 "block literal parsing");
2773 // Enter a scope to hold everything within the block. This includes the
2774 // argument decls, decls within the compound expression, etc. This also
2775 // allows determining whether a variable reference inside the block is
2776 // within or outside of the block.
2777 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2780 // Inform sema that we are starting a block.
2781 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2783 // Parse the return type if present.
2784 DeclSpec DS(AttrFactory);
2785 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2786 // FIXME: Since the return type isn't actually parsed, it can't be used to
2787 // fill ParamInfo with an initial valid range, so do it manually.
2788 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2790 // If this block has arguments, parse them. There is no ambiguity here with
2791 // the expression case, because the expression case requires a parameter list.
2792 if (Tok.is(tok::l_paren)) {
2793 ParseParenDeclarator(ParamInfo);
2794 // Parse the pieces after the identifier as if we had "int(...)".
2795 // SetIdentifier sets the source range end, but in this case we're past
2797 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2798 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2799 ParamInfo.SetRangeEnd(Tmp);
2800 if (ParamInfo.isInvalidType()) {
2801 // If there was an error parsing the arguments, they may have
2802 // tried to use ^(x+y) which requires an argument list. Just
2803 // skip the whole block literal.
2804 Actions.ActOnBlockError(CaretLoc, getCurScope());
2808 MaybeParseGNUAttributes(ParamInfo);
2810 // Inform sema that we are starting a block.
2811 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2812 } else if (!Tok.is(tok::l_brace)) {
2813 ParseBlockId(CaretLoc);
2815 // Otherwise, pretend we saw (void).
2816 ParsedAttributes attrs(AttrFactory);
2817 SourceLocation NoLoc;
2818 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2819 /*IsAmbiguous=*/false,
2820 /*RParenLoc=*/NoLoc,
2821 /*ArgInfo=*/nullptr,
2823 /*EllipsisLoc=*/NoLoc,
2824 /*RParenLoc=*/NoLoc,
2826 /*RefQualifierIsLvalueRef=*/true,
2827 /*RefQualifierLoc=*/NoLoc,
2828 /*ConstQualifierLoc=*/NoLoc,
2829 /*VolatileQualifierLoc=*/NoLoc,
2830 /*RestrictQualifierLoc=*/NoLoc,
2831 /*MutableLoc=*/NoLoc,
2833 /*ESpecRange=*/SourceRange(),
2834 /*Exceptions=*/nullptr,
2835 /*ExceptionRanges=*/nullptr,
2836 /*NumExceptions=*/0,
2837 /*NoexceptExpr=*/nullptr,
2838 /*ExceptionSpecTokens=*/nullptr,
2843 MaybeParseGNUAttributes(ParamInfo);
2845 // Inform sema that we are starting a block.
2846 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2850 ExprResult Result(true);
2851 if (!Tok.is(tok::l_brace)) {
2852 // Saw something like: ^expr
2853 Diag(Tok, diag::err_expected_expression);
2854 Actions.ActOnBlockError(CaretLoc, getCurScope());
2858 StmtResult Stmt(ParseCompoundStatementBody());
2860 if (!Stmt.isInvalid())
2861 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2863 Actions.ActOnBlockError(CaretLoc, getCurScope());
2867 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2871 ExprResult Parser::ParseObjCBoolLiteral() {
2872 tok::TokenKind Kind = Tok.getKind();
2873 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
2876 /// Validate availability spec list, emitting diagnostics if necessary. Returns
2877 /// true if invalid.
2878 static bool CheckAvailabilitySpecList(Parser &P,
2879 ArrayRef<AvailabilitySpec> AvailSpecs) {
2880 llvm::SmallSet<StringRef, 4> Platforms;
2881 bool HasOtherPlatformSpec = false;
2883 for (const auto &Spec : AvailSpecs) {
2884 if (Spec.isOtherPlatformSpec()) {
2885 if (HasOtherPlatformSpec) {
2886 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
2890 HasOtherPlatformSpec = true;
2894 bool Inserted = Platforms.insert(Spec.getPlatform()).second;
2896 // Rule out multiple version specs referring to the same platform.
2897 // For example, we emit an error for:
2898 // @available(macos 10.10, macos 10.11, *)
2899 StringRef Platform = Spec.getPlatform();
2900 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
2901 << Spec.getEndLoc() << Platform;
2906 if (!HasOtherPlatformSpec) {
2907 SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
2908 P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
2909 << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
2916 /// Parse availability query specification.
2918 /// availability-spec:
2920 /// identifier version-tuple
2921 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
2922 if (Tok.is(tok::star)) {
2923 return AvailabilitySpec(ConsumeToken());
2925 // Parse the platform name.
2926 if (Tok.isNot(tok::identifier)) {
2927 Diag(Tok, diag::err_avail_query_expected_platform_name);
2931 IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
2932 SourceRange VersionRange;
2933 VersionTuple Version = ParseVersionTuple(VersionRange);
2935 if (Version.empty())
2938 StringRef Platform = PlatformIdentifier->Ident->getName();
2940 if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
2941 Diag(PlatformIdentifier->Loc,
2942 diag::err_avail_query_unrecognized_platform_name)
2947 return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
2948 VersionRange.getEnd());
2952 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
2953 assert(Tok.is(tok::kw___builtin_available) ||
2954 Tok.isObjCAtKeyword(tok::objc_available));
2956 // Eat the available or __builtin_available.
2959 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2960 if (Parens.expectAndConsume())
2963 SmallVector<AvailabilitySpec, 4> AvailSpecs;
2964 bool HasError = false;
2966 Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
2970 AvailSpecs.push_back(*Spec);
2972 if (!TryConsumeToken(tok::comma))
2977 SkipUntil(tok::r_paren, StopAtSemi);
2981 CheckAvailabilitySpecList(*this, AvailSpecs);
2983 if (Parens.consumeClose())
2986 return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
2987 Parens.getCloseLocation());