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 "RAIIObjectsForParser.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/Basic/PrettyStackTrace.h"
27 #include "clang/Parse/Parser.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/ParsedTemplate.h"
30 #include "clang/Sema/Scope.h"
31 #include "clang/Sema/TypoCorrection.h"
32 #include "llvm/ADT/SmallVector.h"
33 using namespace clang;
35 /// \brief Simple precedence-based parser for binary/ternary operators.
37 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
38 /// production. C99 specifies that the LHS of an assignment operator should be
39 /// parsed as a unary-expression, but consistency dictates that it be a
40 /// conditional-expession. In practice, the important thing here is that the
41 /// LHS of an assignment has to be an l-value, which productions between
42 /// unary-expression and conditional-expression don't produce. Because we want
43 /// consistency, we parse the LHS as a conditional-expression, then check for
44 /// l-value-ness in semantic analysis stages.
47 /// pm-expression: [C++ 5.5]
49 /// pm-expression '.*' cast-expression
50 /// pm-expression '->*' cast-expression
52 /// multiplicative-expression: [C99 6.5.5]
53 /// Note: in C++, apply pm-expression instead of cast-expression
55 /// multiplicative-expression '*' cast-expression
56 /// multiplicative-expression '/' cast-expression
57 /// multiplicative-expression '%' cast-expression
59 /// additive-expression: [C99 6.5.6]
60 /// multiplicative-expression
61 /// additive-expression '+' multiplicative-expression
62 /// additive-expression '-' multiplicative-expression
64 /// shift-expression: [C99 6.5.7]
65 /// additive-expression
66 /// shift-expression '<<' additive-expression
67 /// shift-expression '>>' additive-expression
69 /// relational-expression: [C99 6.5.8]
71 /// relational-expression '<' shift-expression
72 /// relational-expression '>' shift-expression
73 /// relational-expression '<=' shift-expression
74 /// relational-expression '>=' shift-expression
76 /// equality-expression: [C99 6.5.9]
77 /// relational-expression
78 /// equality-expression '==' relational-expression
79 /// equality-expression '!=' relational-expression
81 /// AND-expression: [C99 6.5.10]
82 /// equality-expression
83 /// AND-expression '&' equality-expression
85 /// exclusive-OR-expression: [C99 6.5.11]
87 /// exclusive-OR-expression '^' AND-expression
89 /// inclusive-OR-expression: [C99 6.5.12]
90 /// exclusive-OR-expression
91 /// inclusive-OR-expression '|' exclusive-OR-expression
93 /// logical-AND-expression: [C99 6.5.13]
94 /// inclusive-OR-expression
95 /// logical-AND-expression '&&' inclusive-OR-expression
97 /// logical-OR-expression: [C99 6.5.14]
98 /// logical-AND-expression
99 /// logical-OR-expression '||' logical-AND-expression
101 /// conditional-expression: [C99 6.5.15]
102 /// logical-OR-expression
103 /// logical-OR-expression '?' expression ':' conditional-expression
104 /// [GNU] logical-OR-expression '?' ':' conditional-expression
105 /// [C++] the third operand is an assignment-expression
107 /// assignment-expression: [C99 6.5.16]
108 /// conditional-expression
109 /// unary-expression assignment-operator assignment-expression
110 /// [C++] throw-expression [C++ 15]
112 /// assignment-operator: one of
113 /// = *= /= %= += -= <<= >>= &= ^= |=
115 /// expression: [C99 6.5.17]
116 /// assignment-expression ...[opt]
117 /// expression ',' assignment-expression ...[opt]
119 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
120 ExprResult LHS(ParseAssignmentExpression(isTypeCast));
121 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
124 /// This routine is called when the '@' is seen and consumed.
125 /// Current token is an Identifier and is not a 'try'. This
126 /// routine is necessary to disambiguate \@try-statement from,
127 /// for example, \@encode-expression.
130 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
131 ExprResult LHS(ParseObjCAtExpression(AtLoc));
132 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
135 /// This routine is called when a leading '__extension__' is seen and
136 /// consumed. This is necessary because the token gets consumed in the
137 /// process of disambiguating between an expression and a declaration.
139 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
140 ExprResult LHS(true);
142 // Silence extension warnings in the sub-expression
143 ExtensionRAIIObject O(Diags);
145 LHS = ParseCastExpression(false);
148 if (!LHS.isInvalid())
149 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
152 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
155 /// \brief Parse an expr that doesn't include (top-level) commas.
156 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
157 if (Tok.is(tok::code_completion)) {
158 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
163 if (Tok.is(tok::kw_throw))
164 return ParseThrowExpression();
165 if (Tok.is(tok::kw_co_yield))
166 return ParseCoyieldExpression();
168 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
169 /*isAddressOfOperand=*/false,
171 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
174 /// \brief Parse an assignment expression where part of an Objective-C message
175 /// send has already been parsed.
177 /// In this case \p LBracLoc indicates the location of the '[' of the message
178 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
179 /// the receiver of the message.
181 /// Since this handles full assignment-expression's, it handles postfix
182 /// expressions and other binary operators for these expressions as well.
184 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
185 SourceLocation SuperLoc,
186 ParsedType ReceiverType,
187 Expr *ReceiverExpr) {
189 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
190 ReceiverType, ReceiverExpr);
191 R = ParsePostfixExpressionSuffix(R);
192 return ParseRHSOfBinaryExpression(R, prec::Assignment);
196 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
197 // C++03 [basic.def.odr]p2:
198 // An expression is potentially evaluated unless it appears where an
199 // integral constant expression is required (see 5.19) [...].
200 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
201 EnterExpressionEvaluationContext Unevaluated(Actions,
202 Sema::ConstantEvaluated);
204 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
205 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
206 return Actions.ActOnConstantExpression(Res);
209 /// \brief Parse a constraint-expression.
212 /// constraint-expression: [Concepts TS temp.constr.decl p1]
213 /// logical-or-expression
215 ExprResult Parser::ParseConstraintExpression() {
216 // FIXME: this may erroneously consume a function-body as the braced
217 // initializer list of a compound literal
219 // FIXME: this may erroneously consume a parenthesized rvalue reference
220 // declarator as a parenthesized address-of-label expression
221 ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
222 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
227 bool Parser::isNotExpressionStart() {
228 tok::TokenKind K = Tok.getKind();
229 if (K == tok::l_brace || K == tok::r_brace ||
230 K == tok::kw_for || K == tok::kw_while ||
231 K == tok::kw_if || K == tok::kw_else ||
232 K == tok::kw_goto || K == tok::kw_try)
234 // If this is a decl-specifier, we can't be at the start of an expression.
235 return isKnownToBeDeclarationSpecifier();
238 static bool isFoldOperator(prec::Level Level) {
239 return Level > prec::Unknown && Level != prec::Conditional;
241 static bool isFoldOperator(tok::TokenKind Kind) {
242 return isFoldOperator(getBinOpPrecedence(Kind, false, true));
245 /// \brief Parse a binary expression that starts with \p LHS and has a
246 /// precedence of at least \p MinPrec.
248 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
249 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
250 GreaterThanIsOperator,
251 getLangOpts().CPlusPlus11);
252 SourceLocation ColonLoc;
255 // If this token has a lower precedence than we are allowed to parse (e.g.
256 // because we are called recursively, or because the token is not a binop),
258 if (NextTokPrec < MinPrec)
261 // Consume the operator, saving the operator token for error reporting.
265 if (OpToken.is(tok::caretcaret)) {
266 return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
268 // Bail out when encountering a comma followed by a token which can't
269 // possibly be the start of an expression. For instance:
270 // int f() { return 1, }
271 // We can't do this before consuming the comma, because
272 // isNotExpressionStart() looks at the token stream.
273 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
279 // If the next token is an ellipsis, then this is a fold-expression. Leave
280 // it alone so we can handle it in the paren expression.
281 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
282 // FIXME: We can't check this via lookahead before we consume the token
283 // because that tickles a lexer bug.
289 // Special case handling for the ternary operator.
290 ExprResult TernaryMiddle(true);
291 if (NextTokPrec == prec::Conditional) {
292 if (Tok.isNot(tok::colon)) {
293 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
294 ColonProtectionRAIIObject X(*this);
296 // Handle this production specially:
297 // logical-OR-expression '?' expression ':' conditional-expression
298 // In particular, the RHS of the '?' is 'expression', not
299 // 'logical-OR-expression' as we might expect.
300 TernaryMiddle = ParseExpression();
301 if (TernaryMiddle.isInvalid()) {
302 Actions.CorrectDelayedTyposInExpr(LHS);
304 TernaryMiddle = nullptr;
307 // Special case handling of "X ? Y : Z" where Y is empty:
308 // logical-OR-expression '?' ':' conditional-expression [GNU]
309 TernaryMiddle = nullptr;
310 Diag(Tok, diag::ext_gnu_conditional_expr);
313 if (!TryConsumeToken(tok::colon, ColonLoc)) {
314 // Otherwise, we're missing a ':'. Assume that this was a typo that
315 // the user forgot. If we're not in a macro expansion, we can suggest
316 // a fixit hint. If there were two spaces before the current token,
317 // suggest inserting the colon in between them, otherwise insert ": ".
318 SourceLocation FILoc = Tok.getLocation();
319 const char *FIText = ": ";
320 const SourceManager &SM = PP.getSourceManager();
321 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
322 assert(FILoc.isFileID());
323 bool IsInvalid = false;
324 const char *SourcePtr =
325 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
326 if (!IsInvalid && *SourcePtr == ' ') {
328 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
329 if (!IsInvalid && *SourcePtr == ' ') {
330 FILoc = FILoc.getLocWithOffset(-1);
336 Diag(Tok, diag::err_expected)
337 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
338 Diag(OpToken, diag::note_matching) << tok::question;
339 ColonLoc = Tok.getLocation();
343 // Code completion for the right-hand side of an assignment expression
344 // goes through a special hook that takes the left-hand side into account.
345 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
346 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
351 // Parse another leaf here for the RHS of the operator.
352 // ParseCastExpression works here because all RHS expressions in C have it
353 // as a prefix, at least. However, in C++, an assignment-expression could
354 // be a throw-expression, which is not a valid cast-expression.
355 // Therefore we need some special-casing here.
356 // Also note that the third operand of the conditional operator is
357 // an assignment-expression in C++, and in C++11, we can have a
358 // braced-init-list on the RHS of an assignment. For better diagnostics,
359 // parse as if we were allowed braced-init-lists everywhere, and check that
360 // they only appear on the RHS of assignments later.
362 bool RHSIsInitList = false;
363 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
364 RHS = ParseBraceInitializer();
365 RHSIsInitList = true;
366 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
367 RHS = ParseAssignmentExpression();
369 RHS = ParseCastExpression(false);
371 if (RHS.isInvalid()) {
372 // FIXME: Errors generated by the delayed typo correction should be
373 // printed before errors from parsing the RHS, not after.
374 Actions.CorrectDelayedTyposInExpr(LHS);
375 if (TernaryMiddle.isUsable())
376 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
380 // Remember the precedence of this operator and get the precedence of the
381 // operator immediately to the right of the RHS.
382 prec::Level ThisPrec = NextTokPrec;
383 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
384 getLangOpts().CPlusPlus11);
386 // Assignment and conditional expressions are right-associative.
387 bool isRightAssoc = ThisPrec == prec::Conditional ||
388 ThisPrec == prec::Assignment;
390 // Get the precedence of the operator to the right of the RHS. If it binds
391 // more tightly with RHS than we do, evaluate it completely first.
392 if (ThisPrec < NextTokPrec ||
393 (ThisPrec == NextTokPrec && isRightAssoc)) {
394 if (!RHS.isInvalid() && RHSIsInitList) {
395 Diag(Tok, diag::err_init_list_bin_op)
396 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
399 // If this is left-associative, only parse things on the RHS that bind
400 // more tightly than the current operator. If it is left-associative, it
401 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
402 // A=(B=(C=D)), where each paren is a level of recursion here.
403 // The function takes ownership of the RHS.
404 RHS = ParseRHSOfBinaryExpression(RHS,
405 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
406 RHSIsInitList = false;
408 if (RHS.isInvalid()) {
409 // FIXME: Errors generated by the delayed typo correction should be
410 // printed before errors from ParseRHSOfBinaryExpression, not after.
411 Actions.CorrectDelayedTyposInExpr(LHS);
412 if (TernaryMiddle.isUsable())
413 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
417 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
418 getLangOpts().CPlusPlus11);
421 if (!RHS.isInvalid() && RHSIsInitList) {
422 if (ThisPrec == prec::Assignment) {
423 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
424 << Actions.getExprRange(RHS.get());
426 Diag(OpToken, diag::err_init_list_bin_op)
427 << /*RHS*/1 << PP.getSpelling(OpToken)
428 << Actions.getExprRange(RHS.get());
433 ExprResult OrigLHS = LHS;
434 if (!LHS.isInvalid()) {
435 // Combine the LHS and RHS into the LHS (e.g. build AST).
436 if (TernaryMiddle.isInvalid()) {
437 // If we're using '>>' as an operator within a template
438 // argument list (in C++98), suggest the addition of
439 // parentheses so that the code remains well-formed in C++0x.
440 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
441 SuggestParentheses(OpToken.getLocation(),
442 diag::warn_cxx11_right_shift_in_template_arg,
443 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
444 Actions.getExprRange(RHS.get()).getEnd()));
446 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
447 OpToken.getKind(), LHS.get(), RHS.get());
450 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
451 LHS.get(), TernaryMiddle.get(),
454 // In this case, ActOnBinOp or ActOnConditionalOp performed the
455 // CorrectDelayedTyposInExpr check.
456 if (!getLangOpts().CPlusPlus)
459 // Ensure potential typos aren't left undiagnosed.
460 if (LHS.isInvalid()) {
461 Actions.CorrectDelayedTyposInExpr(OrigLHS);
462 Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
463 Actions.CorrectDelayedTyposInExpr(RHS);
468 /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
469 /// parse a unary-expression.
471 /// \p isAddressOfOperand exists because an id-expression that is the
472 /// operand of address-of gets special treatment due to member pointers.
474 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
475 bool isAddressOfOperand,
476 TypeCastState isTypeCast) {
478 ExprResult Res = ParseCastExpression(isUnaryExpression,
483 Diag(Tok, diag::err_expected_expression);
488 class CastExpressionIdValidator : public CorrectionCandidateCallback {
490 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
491 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
492 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
495 bool ValidateCandidate(const TypoCorrection &candidate) override {
496 NamedDecl *ND = candidate.getCorrectionDecl();
498 return candidate.isKeyword();
500 if (isa<TypeDecl>(ND))
501 return WantTypeSpecifiers;
503 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
506 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
509 for (auto *C : candidate) {
510 NamedDecl *ND = C->getUnderlyingDecl();
511 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
523 /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
524 /// a unary-expression.
526 /// \p isAddressOfOperand exists because an id-expression that is the operand
527 /// of address-of gets special treatment due to member pointers. NotCastExpr
528 /// is set to true if the token is not the start of a cast-expression, and no
529 /// diagnostic is emitted in this case and no tokens are consumed.
532 /// cast-expression: [C99 6.5.4]
534 /// '(' type-name ')' cast-expression
536 /// unary-expression: [C99 6.5.3]
537 /// postfix-expression
538 /// '++' unary-expression
539 /// '--' unary-expression
540 /// [Coro] 'co_await' cast-expression
541 /// unary-operator cast-expression
542 /// 'sizeof' unary-expression
543 /// 'sizeof' '(' type-name ')'
544 /// [C++11] 'sizeof' '...' '(' identifier ')'
545 /// [GNU] '__alignof' unary-expression
546 /// [GNU] '__alignof' '(' type-name ')'
547 /// [C11] '_Alignof' '(' type-name ')'
548 /// [C++11] 'alignof' '(' type-id ')'
549 /// [GNU] '&&' identifier
550 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
551 /// [C++] new-expression
552 /// [C++] delete-expression
554 /// unary-operator: one of
555 /// '&' '*' '+' '-' '~' '!'
556 /// [GNU] '__extension__' '__real' '__imag'
558 /// primary-expression: [C99 6.5.1]
560 /// [C++] id-expression
563 /// [C++] boolean-literal [C++ 2.13.5]
564 /// [C++11] 'nullptr' [C++11 2.14.7]
565 /// [C++11] user-defined-literal
566 /// '(' expression ')'
567 /// [C11] generic-selection
568 /// '__func__' [C99 6.4.2.2]
569 /// [GNU] '__FUNCTION__'
570 /// [MS] '__FUNCDNAME__'
571 /// [MS] 'L__FUNCTION__'
572 /// [GNU] '__PRETTY_FUNCTION__'
573 /// [GNU] '(' compound-statement ')'
574 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
575 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
576 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
578 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
580 /// [OBJC] '[' objc-message-expr ']'
581 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
582 /// [OBJC] '\@protocol' '(' identifier ')'
583 /// [OBJC] '\@encode' '(' type-name ')'
584 /// [OBJC] objc-string-literal
585 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
586 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
587 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
588 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
589 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
590 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
591 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
592 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
593 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
594 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
595 /// [C++] 'this' [C++ 9.3.2]
596 /// [G++] unary-type-trait '(' type-id ')'
597 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
598 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
599 /// [clang] '^' block-literal
601 /// constant: [C99 6.4.4]
603 /// floating-constant
604 /// enumeration-constant -> identifier
605 /// character-constant
607 /// id-expression: [C++ 5.1]
611 /// unqualified-id: [C++ 5.1]
613 /// operator-function-id
614 /// conversion-function-id
618 /// new-expression: [C++ 5.3.4]
619 /// '::'[opt] 'new' new-placement[opt] new-type-id
620 /// new-initializer[opt]
621 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
622 /// new-initializer[opt]
624 /// delete-expression: [C++ 5.3.5]
625 /// '::'[opt] 'delete' cast-expression
626 /// '::'[opt] 'delete' '[' ']' cast-expression
628 /// [GNU/Embarcadero] unary-type-trait:
629 /// '__is_arithmetic'
630 /// '__is_floating_point'
632 /// '__is_lvalue_expr'
633 /// '__is_rvalue_expr'
634 /// '__is_complete_type'
639 /// '__is_lvalue_reference'
640 /// '__is_rvalue_reference'
641 /// '__is_fundamental'
646 /// '__is_member_object_pointer'
647 /// '__is_member_function_pointer'
648 /// '__is_member_pointer'
652 /// '__is_standard_layout'
656 /// [GNU] unary-type-trait:
657 /// '__has_nothrow_assign'
658 /// '__has_nothrow_copy'
659 /// '__has_nothrow_constructor'
660 /// '__has_trivial_assign' [TODO]
661 /// '__has_trivial_copy' [TODO]
662 /// '__has_trivial_constructor'
663 /// '__has_trivial_destructor'
664 /// '__has_virtual_destructor'
665 /// '__is_abstract' [TODO]
667 /// '__is_empty' [TODO]
671 /// '__is_polymorphic'
672 /// '__is_sealed' [MS]
676 /// [Clang] unary-type-trait:
677 /// '__trivially_copyable'
679 /// binary-type-trait:
680 /// [GNU] '__is_base_of'
681 /// [MS] '__is_convertible_to'
682 /// '__is_convertible'
685 /// [Embarcadero] array-type-trait:
689 /// [Embarcadero] expression-trait:
690 /// '__is_lvalue_expr'
691 /// '__is_rvalue_expr'
694 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
695 bool isAddressOfOperand,
697 TypeCastState isTypeCast) {
699 tok::TokenKind SavedKind = Tok.getKind();
702 // This handles all of cast-expression, unary-expression, postfix-expression,
703 // and primary-expression. We handle them together like this for efficiency
704 // and to simplify handling of an expression starting with a '(' token: which
705 // may be one of a parenthesized expression, cast-expression, compound literal
706 // expression, or statement expression.
708 // If the parsed tokens consist of a primary-expression, the cases below
709 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
710 // to handle the postfix expression suffixes. Cases that cannot be followed
711 // by postfix exprs should return without invoking
712 // ParsePostfixExpressionSuffix.
715 // If this expression is limited to being a unary-expression, the parent can
716 // not start a cast expression.
717 ParenParseOption ParenExprType =
718 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
721 SourceLocation RParenLoc;
722 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
723 isTypeCast == IsTypeCast, CastTy, RParenLoc);
725 switch (ParenExprType) {
726 case SimpleExpr: break; // Nothing else to do.
727 case CompoundStmt: break; // Nothing else to do.
728 case CompoundLiteral:
729 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
730 // postfix-expression exist, parse them now.
733 // We have parsed the cast-expression and no postfix-expr pieces are
741 // primary-expression
742 case tok::numeric_constant:
743 // constant: integer-constant
744 // constant: floating-constant
746 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
752 return ParseCXXBoolLiteral();
754 case tok::kw___objc_yes:
755 case tok::kw___objc_no:
756 return ParseObjCBoolLiteral();
758 case tok::kw_nullptr:
759 Diag(Tok, diag::warn_cxx98_compat_nullptr);
760 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
762 case tok::annot_primary_expr:
763 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
764 Res = getExprAnnotation(Tok);
768 case tok::kw___super:
769 case tok::kw_decltype:
770 // Annotate the token and tail recurse.
771 if (TryAnnotateTypeOrScopeToken())
773 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
774 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
776 case tok::identifier: { // primary-expression: identifier
777 // unqualified-id: identifier
778 // constant: enumeration-constant
779 // Turn a potentially qualified name into a annot_typename or
780 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
781 if (getLangOpts().CPlusPlus) {
782 // Avoid the unnecessary parse-time lookup in the common case
783 // where the syntax forbids a type.
784 const Token &Next = NextToken();
786 // If this identifier was reverted from a token ID, and the next token
787 // is a parenthesis, this is likely to be a use of a type trait. Check
789 if (Next.is(tok::l_paren) &&
790 Tok.is(tok::identifier) &&
791 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
792 IdentifierInfo *II = Tok.getIdentifierInfo();
793 // Build up the mapping of revertible type traits, for future use.
794 if (RevertibleTypeTraits.empty()) {
795 #define RTT_JOIN(X,Y) X##Y
796 #define REVERTIBLE_TYPE_TRAIT(Name) \
797 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
798 = RTT_JOIN(tok::kw_,Name)
800 REVERTIBLE_TYPE_TRAIT(__is_abstract);
801 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
802 REVERTIBLE_TYPE_TRAIT(__is_array);
803 REVERTIBLE_TYPE_TRAIT(__is_assignable);
804 REVERTIBLE_TYPE_TRAIT(__is_base_of);
805 REVERTIBLE_TYPE_TRAIT(__is_class);
806 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
807 REVERTIBLE_TYPE_TRAIT(__is_compound);
808 REVERTIBLE_TYPE_TRAIT(__is_const);
809 REVERTIBLE_TYPE_TRAIT(__is_constructible);
810 REVERTIBLE_TYPE_TRAIT(__is_convertible);
811 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
812 REVERTIBLE_TYPE_TRAIT(__is_destructible);
813 REVERTIBLE_TYPE_TRAIT(__is_empty);
814 REVERTIBLE_TYPE_TRAIT(__is_enum);
815 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
816 REVERTIBLE_TYPE_TRAIT(__is_final);
817 REVERTIBLE_TYPE_TRAIT(__is_function);
818 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
819 REVERTIBLE_TYPE_TRAIT(__is_integral);
820 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
821 REVERTIBLE_TYPE_TRAIT(__is_literal);
822 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
823 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
824 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
825 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
826 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
827 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
828 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
829 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
830 REVERTIBLE_TYPE_TRAIT(__is_object);
831 REVERTIBLE_TYPE_TRAIT(__is_pod);
832 REVERTIBLE_TYPE_TRAIT(__is_pointer);
833 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
834 REVERTIBLE_TYPE_TRAIT(__is_reference);
835 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
836 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
837 REVERTIBLE_TYPE_TRAIT(__is_same);
838 REVERTIBLE_TYPE_TRAIT(__is_scalar);
839 REVERTIBLE_TYPE_TRAIT(__is_sealed);
840 REVERTIBLE_TYPE_TRAIT(__is_signed);
841 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
842 REVERTIBLE_TYPE_TRAIT(__is_trivial);
843 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
844 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
845 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
846 REVERTIBLE_TYPE_TRAIT(__is_union);
847 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
848 REVERTIBLE_TYPE_TRAIT(__is_void);
849 REVERTIBLE_TYPE_TRAIT(__is_volatile);
850 #undef REVERTIBLE_TYPE_TRAIT
854 // If we find that this is in fact the name of a type trait,
855 // update the token kind in place and parse again to treat it as
856 // the appropriate kind of type trait.
857 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
858 = RevertibleTypeTraits.find(II);
859 if (Known != RevertibleTypeTraits.end()) {
860 Tok.setKind(Known->second);
861 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
862 NotCastExpr, isTypeCast);
866 if ((!ColonIsSacred && Next.is(tok::colon)) ||
867 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
869 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
870 if (TryAnnotateTypeOrScopeToken())
872 if (!Tok.is(tok::identifier))
873 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
877 // Consume the identifier so that we can see if it is followed by a '(' or
879 IdentifierInfo &II = *Tok.getIdentifierInfo();
880 SourceLocation ILoc = ConsumeToken();
882 // Support 'Class.property' and 'super.property' notation.
883 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
884 (Actions.getTypeName(II, ILoc, getCurScope()) ||
885 // Allow the base to be 'super' if in an objc-method.
886 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
889 if (Tok.is(tok::code_completion) && &II != Ident_super) {
890 Actions.CodeCompleteObjCClassPropertyRefExpr(
891 getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
895 // Allow either an identifier or the keyword 'class' (in C++).
896 if (Tok.isNot(tok::identifier) &&
897 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
898 Diag(Tok, diag::err_expected_property_name);
901 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
902 SourceLocation PropertyLoc = ConsumeToken();
904 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
909 // In an Objective-C method, if we have "super" followed by an identifier,
910 // the token sequence is ill-formed. However, if there's a ':' or ']' after
911 // that identifier, this is probably a message send with a missing open
912 // bracket. Treat it as such.
913 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
914 getCurScope()->isInObjcMethodScope() &&
915 ((Tok.is(tok::identifier) &&
916 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
917 Tok.is(tok::code_completion))) {
918 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
923 // If we have an Objective-C class name followed by an identifier
924 // and either ':' or ']', this is an Objective-C class message
925 // send that's missing the opening '['. Recovery
926 // appropriately. Also take this path if we're performing code
927 // completion after an Objective-C class name.
928 if (getLangOpts().ObjC1 &&
929 ((Tok.is(tok::identifier) && !InMessageExpression) ||
930 Tok.is(tok::code_completion))) {
931 const Token& Next = NextToken();
932 if (Tok.is(tok::code_completion) ||
933 Next.is(tok::colon) || Next.is(tok::r_square))
934 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
935 if (Typ.get()->isObjCObjectOrInterfaceType()) {
936 // Fake up a Declarator to use with ActOnTypeName.
937 DeclSpec DS(AttrFactory);
938 DS.SetRangeStart(ILoc);
939 DS.SetRangeEnd(ILoc);
940 const char *PrevSpec = nullptr;
942 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
943 Actions.getASTContext().getPrintingPolicy());
945 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
946 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
951 Res = ParseObjCMessageExpressionBody(SourceLocation(),
958 // Make sure to pass down the right value for isAddressOfOperand.
959 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
960 isAddressOfOperand = false;
962 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
963 // need to know whether or not this identifier is a function designator or
966 CXXScopeSpec ScopeSpec;
967 SourceLocation TemplateKWLoc;
969 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
970 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
971 Validator->IsAddressOfOperand = isAddressOfOperand;
972 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
973 Validator->WantExpressionKeywords = false;
974 Validator->WantRemainingKeywords = false;
976 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
978 Name.setIdentifier(&II, ILoc);
979 Res = Actions.ActOnIdExpression(
980 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
981 isAddressOfOperand, std::move(Validator),
982 /*IsInlineAsmIdentifier=*/false,
983 Tok.is(tok::r_paren) ? nullptr : &Replacement);
984 if (!Res.isInvalid() && !Res.get()) {
985 UnconsumeToken(Replacement);
986 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
987 NotCastExpr, isTypeCast);
991 case tok::char_constant: // constant: character-constant
992 case tok::wide_char_constant:
993 case tok::utf8_char_constant:
994 case tok::utf16_char_constant:
995 case tok::utf32_char_constant:
996 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
999 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
1000 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
1001 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
1002 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
1003 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
1004 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1005 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1008 case tok::string_literal: // primary-expression: string-literal
1009 case tok::wide_string_literal:
1010 case tok::utf8_string_literal:
1011 case tok::utf16_string_literal:
1012 case tok::utf32_string_literal:
1013 Res = ParseStringLiteralExpression(true);
1015 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1016 Res = ParseGenericSelectionExpression();
1018 case tok::kw___builtin_available:
1019 return ParseAvailabilityCheckExpr(Tok.getLocation());
1020 case tok::kw___builtin_va_arg:
1021 case tok::kw___builtin_offsetof:
1022 case tok::kw___builtin_choose_expr:
1023 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1024 case tok::kw___builtin_convertvector:
1025 return ParseBuiltinPrimaryExpression();
1026 case tok::kw___null:
1027 return Actions.ActOnGNUNullExpr(ConsumeToken());
1029 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1030 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1031 // C++ [expr.unary] has:
1032 // unary-expression:
1033 // ++ cast-expression
1034 // -- cast-expression
1035 Token SavedTok = Tok;
1037 // One special case is implicitly handled here: if the preceding tokens are
1038 // an ambiguous cast expression, such as "(T())++", then we recurse to
1039 // determine whether the '++' is prefix or postfix.
1040 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1041 /*isAddressOfOperand*/false, NotCastExpr,
1044 // If we return with NotCastExpr = true, we must not consume any tokens,
1045 // so put the token back where we found it.
1046 assert(Res.isInvalid());
1047 UnconsumeToken(SavedTok);
1050 if (!Res.isInvalid())
1051 Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1052 SavedKind, Res.get());
1055 case tok::amp: { // unary-expression: '&' cast-expression
1056 // Special treatment because of member pointers
1057 SourceLocation SavedLoc = ConsumeToken();
1058 Res = ParseCastExpression(false, true);
1059 if (!Res.isInvalid())
1060 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1064 case tok::star: // unary-expression: '*' cast-expression
1065 case tok::plus: // unary-expression: '+' cast-expression
1066 case tok::minus: // unary-expression: '-' cast-expression
1067 case tok::tilde: // unary-expression: '~' cast-expression
1068 case tok::exclaim: // unary-expression: '!' cast-expression
1069 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1070 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1071 SourceLocation SavedLoc = ConsumeToken();
1072 Res = ParseCastExpression(false);
1073 if (!Res.isInvalid())
1074 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1078 case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1079 SourceLocation CoawaitLoc = ConsumeToken();
1080 Res = ParseCastExpression(false);
1081 if (!Res.isInvalid())
1082 Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1086 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1087 // __extension__ silences extension warnings in the subexpression.
1088 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1089 SourceLocation SavedLoc = ConsumeToken();
1090 Res = ParseCastExpression(false);
1091 if (!Res.isInvalid())
1092 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1095 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1096 if (!getLangOpts().C11)
1097 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1099 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1100 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1101 // unary-expression: '__alignof' '(' type-name ')'
1102 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1103 // unary-expression: 'sizeof' '(' type-name ')'
1104 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1105 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1106 case tok::kw___builtin_omp_required_simd_align:
1107 return ParseUnaryExprOrTypeTraitExpression();
1108 case tok::ampamp: { // unary-expression: '&&' identifier
1109 SourceLocation AmpAmpLoc = ConsumeToken();
1110 if (Tok.isNot(tok::identifier))
1111 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1113 if (getCurScope()->getFnParent() == nullptr)
1114 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1116 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1117 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1119 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1123 case tok::kw_const_cast:
1124 case tok::kw_dynamic_cast:
1125 case tok::kw_reinterpret_cast:
1126 case tok::kw_static_cast:
1127 Res = ParseCXXCasts();
1129 case tok::kw_typeid:
1130 Res = ParseCXXTypeid();
1132 case tok::kw___uuidof:
1133 Res = ParseCXXUuidof();
1136 Res = ParseCXXThis();
1139 case tok::annot_typename:
1140 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1141 ParsedType Type = getTypeAnnotation(Tok);
1143 // Fake up a Declarator to use with ActOnTypeName.
1144 DeclSpec DS(AttrFactory);
1145 DS.SetRangeStart(Tok.getLocation());
1146 DS.SetRangeEnd(Tok.getLastLoc());
1148 const char *PrevSpec = nullptr;
1150 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1151 PrevSpec, DiagID, Type,
1152 Actions.getASTContext().getPrintingPolicy());
1154 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1155 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1160 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1166 case tok::annot_decltype:
1168 case tok::kw_wchar_t:
1169 case tok::kw_char16_t:
1170 case tok::kw_char32_t:
1175 case tok::kw___int64:
1176 case tok::kw___int128:
1177 case tok::kw_signed:
1178 case tok::kw_unsigned:
1181 case tok::kw_double:
1182 case tok::kw___float128:
1184 case tok::kw_typename:
1185 case tok::kw_typeof:
1186 case tok::kw___vector:
1187 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1188 #include "clang/Basic/OpenCLImageTypes.def"
1190 if (!getLangOpts().CPlusPlus) {
1191 Diag(Tok, diag::err_expected_expression);
1195 if (SavedKind == tok::kw_typename) {
1196 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1197 // typename-specifier braced-init-list
1198 if (TryAnnotateTypeOrScopeToken())
1201 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1202 // We are trying to parse a simple-type-specifier but might not get such
1203 // a token after error recovery.
1207 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1208 // simple-type-specifier braced-init-list
1210 DeclSpec DS(AttrFactory);
1212 ParseCXXSimpleTypeSpecifier(DS);
1213 if (Tok.isNot(tok::l_paren) &&
1214 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1215 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1216 << DS.getSourceRange());
1218 if (Tok.is(tok::l_brace))
1219 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1221 Res = ParseCXXTypeConstructExpression(DS);
1225 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1226 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1227 // (We can end up in this situation after tentative parsing.)
1228 if (TryAnnotateTypeOrScopeToken())
1230 if (!Tok.is(tok::annot_cxxscope))
1231 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1232 NotCastExpr, isTypeCast);
1234 Token Next = NextToken();
1235 if (Next.is(tok::annot_template_id)) {
1236 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1237 if (TemplateId->Kind == TNK_Type_template) {
1238 // We have a qualified template-id that we know refers to a
1239 // type, translate it into a type and continue parsing as a
1242 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1243 /*EnteringContext=*/false);
1244 AnnotateTemplateIdTokenAsType();
1245 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1246 NotCastExpr, isTypeCast);
1250 // Parse as an id-expression.
1251 Res = ParseCXXIdExpression(isAddressOfOperand);
1255 case tok::annot_template_id: { // [C++] template-id
1256 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1257 if (TemplateId->Kind == TNK_Type_template) {
1258 // We have a template-id that we know refers to a type,
1259 // translate it into a type and continue parsing as a cast
1261 AnnotateTemplateIdTokenAsType();
1262 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1263 NotCastExpr, isTypeCast);
1266 // Fall through to treat the template-id as an id-expression.
1269 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1270 Res = ParseCXXIdExpression(isAddressOfOperand);
1273 case tok::coloncolon: {
1274 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1275 // annotates the token, tail recurse.
1276 if (TryAnnotateTypeOrScopeToken())
1278 if (!Tok.is(tok::coloncolon))
1279 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1281 // ::new -> [C++] new-expression
1282 // ::delete -> [C++] delete-expression
1283 SourceLocation CCLoc = ConsumeToken();
1284 if (Tok.is(tok::kw_new))
1285 return ParseCXXNewExpression(true, CCLoc);
1286 if (Tok.is(tok::kw_delete))
1287 return ParseCXXDeleteExpression(true, CCLoc);
1289 // This is not a type name or scope specifier, it is an invalid expression.
1290 Diag(CCLoc, diag::err_expected_expression);
1294 case tok::kw_new: // [C++] new-expression
1295 return ParseCXXNewExpression(false, Tok.getLocation());
1297 case tok::kw_delete: // [C++] delete-expression
1298 return ParseCXXDeleteExpression(false, Tok.getLocation());
1300 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1301 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1302 SourceLocation KeyLoc = ConsumeToken();
1303 BalancedDelimiterTracker T(*this, tok::l_paren);
1305 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1307 // C++11 [expr.unary.noexcept]p1:
1308 // The noexcept operator determines whether the evaluation of its operand,
1309 // which is an unevaluated operand, can throw an exception.
1310 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1311 ExprResult Result = ParseExpression();
1315 if (!Result.isInvalid())
1316 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1317 Result.get(), T.getCloseLocation());
1321 #define TYPE_TRAIT(N,Spelling,K) \
1322 case tok::kw_##Spelling:
1323 #include "clang/Basic/TokenKinds.def"
1324 return ParseTypeTrait();
1326 case tok::kw___array_rank:
1327 case tok::kw___array_extent:
1328 return ParseArrayTypeTrait();
1330 case tok::kw___is_lvalue_expr:
1331 case tok::kw___is_rvalue_expr:
1332 return ParseExpressionTrait();
1335 SourceLocation AtLoc = ConsumeToken();
1336 return ParseObjCAtExpression(AtLoc);
1339 Res = ParseBlockLiteralExpression();
1341 case tok::code_completion: {
1342 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1347 if (getLangOpts().CPlusPlus11) {
1348 if (getLangOpts().ObjC1) {
1349 // C++11 lambda expressions and Objective-C message sends both start with a
1350 // square bracket. There are three possibilities here:
1351 // we have a valid lambda expression, we have an invalid lambda
1352 // expression, or we have something that doesn't appear to be a lambda.
1353 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1354 Res = TryParseLambdaExpression();
1355 if (!Res.isInvalid() && !Res.get())
1356 Res = ParseObjCMessageExpression();
1359 Res = ParseLambdaExpression();
1362 if (getLangOpts().ObjC1) {
1363 Res = ParseObjCMessageExpression();
1372 // Check to see whether Res is a function designator only. If it is and we
1373 // are compiling for OpenCL, we need to return an error as this implies
1374 // that the address of the function is being taken, which is illegal in CL.
1376 // These can be followed by postfix-expr pieces.
1377 Res = ParsePostfixExpressionSuffix(Res);
1378 if (getLangOpts().OpenCL)
1379 if (Expr *PostfixExpr = Res.get()) {
1380 QualType Ty = PostfixExpr->getType();
1381 if (!Ty.isNull() && Ty->isFunctionType()) {
1382 Diag(PostfixExpr->getExprLoc(),
1383 diag::err_opencl_taking_function_address_parser);
1391 /// \brief Once the leading part of a postfix-expression is parsed, this
1392 /// method parses any suffixes that apply.
1395 /// postfix-expression: [C99 6.5.2]
1396 /// primary-expression
1397 /// postfix-expression '[' expression ']'
1398 /// postfix-expression '[' braced-init-list ']'
1399 /// postfix-expression '(' argument-expression-list[opt] ')'
1400 /// postfix-expression '.' identifier
1401 /// postfix-expression '->' identifier
1402 /// postfix-expression '++'
1403 /// postfix-expression '--'
1404 /// '(' type-name ')' '{' initializer-list '}'
1405 /// '(' type-name ')' '{' initializer-list ',' '}'
1407 /// argument-expression-list: [C99 6.5.2]
1408 /// argument-expression ...[opt]
1409 /// argument-expression-list ',' assignment-expression ...[opt]
1412 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1413 // Now that the primary-expression piece of the postfix-expression has been
1414 // parsed, see if there are any postfix-expression pieces here.
1417 switch (Tok.getKind()) {
1418 case tok::code_completion:
1419 if (InMessageExpression)
1422 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1426 case tok::identifier:
1427 // If we see identifier: after an expression, and we're not already in a
1428 // message send, then this is probably a message send with a missing
1429 // opening bracket '['.
1430 if (getLangOpts().ObjC1 && !InMessageExpression &&
1431 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1432 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1433 nullptr, LHS.get());
1437 // Fall through; this isn't a message send.
1439 default: // Not a postfix-expression suffix.
1441 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1442 // If we have a array postfix expression that starts on a new line and
1443 // Objective-C is enabled, it is highly likely that the user forgot a
1444 // semicolon after the base expression and that the array postfix-expr is
1445 // actually another message send. In this case, do some look-ahead to see
1446 // if the contents of the square brackets are obviously not a valid
1447 // expression and recover by pretending there is no suffix.
1448 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1449 isSimpleObjCMessageExpression())
1452 // Reject array indices starting with a lambda-expression. '[[' is
1453 // reserved for attributes.
1454 if (CheckProhibitedCXX11Attribute()) {
1455 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1459 BalancedDelimiterTracker T(*this, tok::l_square);
1461 Loc = T.getOpenLocation();
1462 ExprResult Idx, Length;
1463 SourceLocation ColonLoc;
1464 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1465 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1466 Idx = ParseBraceInitializer();
1467 } else if (getLangOpts().OpenMP) {
1468 ColonProtectionRAIIObject RAII(*this);
1469 // Parse [: or [ expr or [ expr :
1470 if (!Tok.is(tok::colon)) {
1472 Idx = ParseExpression();
1474 if (Tok.is(tok::colon)) {
1476 ColonLoc = ConsumeToken();
1477 if (Tok.isNot(tok::r_square))
1478 Length = ParseExpression();
1481 Idx = ParseExpression();
1483 SourceLocation RLoc = Tok.getLocation();
1485 ExprResult OrigLHS = LHS;
1486 if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1487 Tok.is(tok::r_square)) {
1488 if (ColonLoc.isValid()) {
1489 LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1490 ColonLoc, Length.get(), RLoc);
1492 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1498 if (LHS.isInvalid()) {
1499 (void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
1500 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1501 (void)Actions.CorrectDelayedTyposInExpr(Length);
1511 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1512 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1513 // '(' argument-expression-list[opt] ')'
1514 tok::TokenKind OpKind = Tok.getKind();
1515 InMessageExpressionRAIIObject InMessage(*this, false);
1517 Expr *ExecConfig = nullptr;
1519 BalancedDelimiterTracker PT(*this, tok::l_paren);
1521 if (OpKind == tok::lesslessless) {
1522 ExprVector ExecConfigExprs;
1523 CommaLocsTy ExecConfigCommaLocs;
1524 SourceLocation OpenLoc = ConsumeToken();
1526 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1527 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1531 SourceLocation CloseLoc;
1532 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1533 } else if (LHS.isInvalid()) {
1534 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1536 // There was an error closing the brackets
1537 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1538 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1539 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1543 if (!LHS.isInvalid()) {
1544 if (ExpectAndConsume(tok::l_paren))
1547 Loc = PrevTokLocation;
1550 if (!LHS.isInvalid()) {
1551 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1555 if (ECResult.isInvalid())
1558 ExecConfig = ECResult.get();
1562 Loc = PT.getOpenLocation();
1565 ExprVector ArgExprs;
1566 CommaLocsTy CommaLocs;
1568 if (Tok.is(tok::code_completion)) {
1569 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1574 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1575 if (Tok.isNot(tok::r_paren)) {
1576 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1577 Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1579 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1581 } else if (LHS.isInvalid()) {
1582 for (auto &E : ArgExprs)
1583 Actions.CorrectDelayedTyposInExpr(E);
1589 if (LHS.isInvalid()) {
1590 SkipUntil(tok::r_paren, StopAtSemi);
1591 } else if (Tok.isNot(tok::r_paren)) {
1592 bool HadDelayedTypo = false;
1593 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1594 HadDelayedTypo = true;
1595 for (auto &E : ArgExprs)
1596 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1597 HadDelayedTypo = true;
1598 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1599 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1600 // the unmatched l_paren.
1602 SkipUntil(tok::r_paren, StopAtSemi);
1607 assert((ArgExprs.size() == 0 ||
1608 ArgExprs.size()-1 == CommaLocs.size())&&
1609 "Unexpected number of commas!");
1610 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1611 ArgExprs, Tok.getLocation(),
1620 // postfix-expression: p-e '->' template[opt] id-expression
1621 // postfix-expression: p-e '.' template[opt] id-expression
1622 tok::TokenKind OpKind = Tok.getKind();
1623 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1626 ParsedType ObjectType;
1627 bool MayBePseudoDestructor = false;
1628 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1629 Expr *Base = LHS.get();
1630 const Type* BaseType = Base->getType().getTypePtrOrNull();
1631 if (BaseType && Tok.is(tok::l_paren) &&
1632 (BaseType->isFunctionType() ||
1633 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1634 Diag(OpLoc, diag::err_function_is_not_record)
1635 << OpKind << Base->getSourceRange()
1636 << FixItHint::CreateRemoval(OpLoc);
1637 return ParsePostfixExpressionSuffix(Base);
1640 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1641 OpLoc, OpKind, ObjectType,
1642 MayBePseudoDestructor);
1643 if (LHS.isInvalid())
1646 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1647 /*EnteringContext=*/false,
1648 &MayBePseudoDestructor);
1649 if (SS.isNotEmpty())
1650 ObjectType = nullptr;
1653 if (Tok.is(tok::code_completion)) {
1654 // Code completion for a member access expression.
1655 Actions.CodeCompleteMemberReferenceExpr(
1656 getCurScope(), LHS.get(), OpLoc, OpKind == tok::arrow,
1657 ExprStatementTokLoc == LHS.get()->getLocStart());
1663 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1664 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1669 // Either the action has told us that this cannot be a
1670 // pseudo-destructor expression (based on the type of base
1671 // expression), or we didn't see a '~' in the right place. We
1672 // can still parse a destructor name here, but in that case it
1673 // names a real destructor.
1674 // Allow explicit constructor calls in Microsoft mode.
1675 // FIXME: Add support for explicit call of template constructor.
1676 SourceLocation TemplateKWLoc;
1678 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1679 Tok.is(tok::kw_class)) {
1681 // After a '.' in a member access expression, treat the keyword
1682 // 'class' as if it were an identifier.
1684 // This hack allows property access to the 'class' method because it is
1685 // such a common method name. For other C++ keywords that are
1686 // Objective-C method names, one must use the message send syntax.
1687 IdentifierInfo *Id = Tok.getIdentifierInfo();
1688 SourceLocation Loc = ConsumeToken();
1689 Name.setIdentifier(Id, Loc);
1690 } else if (ParseUnqualifiedId(SS,
1691 /*EnteringContext=*/false,
1692 /*AllowDestructorName=*/true,
1693 /*AllowConstructorName=*/
1694 getLangOpts().MicrosoftExt,
1695 ObjectType, TemplateKWLoc, Name)) {
1696 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1700 if (!LHS.isInvalid())
1701 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1702 OpKind, SS, TemplateKWLoc, Name,
1703 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1707 case tok::plusplus: // postfix-expression: postfix-expression '++'
1708 case tok::minusminus: // postfix-expression: postfix-expression '--'
1709 if (!LHS.isInvalid()) {
1710 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1711 Tok.getKind(), LHS.get());
1719 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1720 /// vec_step and we are at the start of an expression or a parenthesized
1721 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1722 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1725 /// unary-expression: [C99 6.5.3]
1726 /// 'sizeof' unary-expression
1727 /// 'sizeof' '(' type-name ')'
1728 /// [GNU] '__alignof' unary-expression
1729 /// [GNU] '__alignof' '(' type-name ')'
1730 /// [C11] '_Alignof' '(' type-name ')'
1731 /// [C++0x] 'alignof' '(' type-id ')'
1733 /// [GNU] typeof-specifier:
1734 /// typeof ( expressions )
1735 /// typeof ( type-name )
1736 /// [GNU/C++] typeof unary-expression
1738 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1739 /// vec_step ( expressions )
1740 /// vec_step ( type-name )
1743 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1746 SourceRange &CastRange) {
1748 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1749 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1750 tok::kw___builtin_omp_required_simd_align) &&
1751 "Not a typeof/sizeof/alignof/vec_step expression!");
1755 // If the operand doesn't start with an '(', it must be an expression.
1756 if (Tok.isNot(tok::l_paren)) {
1757 // If construct allows a form without parenthesis, user may forget to put
1758 // pathenthesis around type name.
1759 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1760 tok::kw__Alignof)) {
1761 if (isTypeIdUnambiguously()) {
1762 DeclSpec DS(AttrFactory);
1763 ParseSpecifierQualifierList(DS);
1764 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1765 ParseDeclarator(DeclaratorInfo);
1767 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1768 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1769 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1771 << FixItHint::CreateInsertion(LParenLoc, "(")
1772 << FixItHint::CreateInsertion(RParenLoc, ")");
1779 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1780 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1785 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1787 // If it starts with a '(', we know that it is either a parenthesized
1788 // type-name, or it is a unary-expression that starts with a compound
1789 // literal, or starts with a primary-expression that is a parenthesized
1791 ParenParseOption ExprType = CastExpr;
1792 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1794 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1795 false, CastTy, RParenLoc);
1796 CastRange = SourceRange(LParenLoc, RParenLoc);
1798 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1800 if (ExprType == CastExpr) {
1805 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1806 // GNU typeof in C requires the expression to be parenthesized. Not so for
1807 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1808 // the start of a unary-expression, but doesn't include any postfix
1809 // pieces. Parse these now if present.
1810 if (!Operand.isInvalid())
1811 Operand = ParsePostfixExpressionSuffix(Operand.get());
1815 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1821 /// \brief Parse a sizeof or alignof expression.
1824 /// unary-expression: [C99 6.5.3]
1825 /// 'sizeof' unary-expression
1826 /// 'sizeof' '(' type-name ')'
1827 /// [C++11] 'sizeof' '...' '(' identifier ')'
1828 /// [GNU] '__alignof' unary-expression
1829 /// [GNU] '__alignof' '(' type-name ')'
1830 /// [C11] '_Alignof' '(' type-name ')'
1831 /// [C++11] 'alignof' '(' type-id ')'
1833 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1834 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1835 tok::kw__Alignof, tok::kw_vec_step,
1836 tok::kw___builtin_omp_required_simd_align) &&
1837 "Not a sizeof/alignof/vec_step expression!");
1841 // [C++11] 'sizeof' '...' '(' identifier ')'
1842 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1843 SourceLocation EllipsisLoc = ConsumeToken();
1844 SourceLocation LParenLoc, RParenLoc;
1845 IdentifierInfo *Name = nullptr;
1846 SourceLocation NameLoc;
1847 if (Tok.is(tok::l_paren)) {
1848 BalancedDelimiterTracker T(*this, tok::l_paren);
1850 LParenLoc = T.getOpenLocation();
1851 if (Tok.is(tok::identifier)) {
1852 Name = Tok.getIdentifierInfo();
1853 NameLoc = ConsumeToken();
1855 RParenLoc = T.getCloseLocation();
1856 if (RParenLoc.isInvalid())
1857 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1859 Diag(Tok, diag::err_expected_parameter_pack);
1860 SkipUntil(tok::r_paren, StopAtSemi);
1862 } else if (Tok.is(tok::identifier)) {
1863 Name = Tok.getIdentifierInfo();
1864 NameLoc = ConsumeToken();
1865 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1866 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1867 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1869 << FixItHint::CreateInsertion(LParenLoc, "(")
1870 << FixItHint::CreateInsertion(RParenLoc, ")");
1872 Diag(Tok, diag::err_sizeof_parameter_pack);
1878 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1879 Sema::ReuseLambdaContextDecl);
1881 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1882 OpTok.getLocation(),
1887 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1888 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1890 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1891 Sema::ReuseLambdaContextDecl);
1895 SourceRange CastRange;
1896 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1901 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1902 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1903 ExprKind = UETT_AlignOf;
1904 else if (OpTok.is(tok::kw_vec_step))
1905 ExprKind = UETT_VecStep;
1906 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
1907 ExprKind = UETT_OpenMPRequiredSimdAlign;
1910 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1913 CastTy.getAsOpaquePtr(),
1916 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1917 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1919 // If we get here, the operand to the sizeof/alignof was an expresion.
1920 if (!Operand.isInvalid())
1921 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1929 /// ParseBuiltinPrimaryExpression
1932 /// primary-expression: [C99 6.5.1]
1933 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1934 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1935 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1937 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1938 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1940 /// [GNU] offsetof-member-designator:
1941 /// [GNU] identifier
1942 /// [GNU] offsetof-member-designator '.' identifier
1943 /// [GNU] offsetof-member-designator '[' expression ']'
1945 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1947 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1949 tok::TokenKind T = Tok.getKind();
1950 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
1952 // All of these start with an open paren.
1953 if (Tok.isNot(tok::l_paren))
1954 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
1957 BalancedDelimiterTracker PT(*this, tok::l_paren);
1963 default: llvm_unreachable("Not a builtin primary expression!");
1964 case tok::kw___builtin_va_arg: {
1965 ExprResult Expr(ParseAssignmentExpression());
1967 if (ExpectAndConsume(tok::comma)) {
1968 SkipUntil(tok::r_paren, StopAtSemi);
1972 TypeResult Ty = ParseTypeName();
1974 if (Tok.isNot(tok::r_paren)) {
1975 Diag(Tok, diag::err_expected) << tok::r_paren;
1979 if (Expr.isInvalid() || Ty.isInvalid())
1982 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
1985 case tok::kw___builtin_offsetof: {
1986 SourceLocation TypeLoc = Tok.getLocation();
1987 TypeResult Ty = ParseTypeName();
1988 if (Ty.isInvalid()) {
1989 SkipUntil(tok::r_paren, StopAtSemi);
1993 if (ExpectAndConsume(tok::comma)) {
1994 SkipUntil(tok::r_paren, StopAtSemi);
1998 // We must have at least one identifier here.
1999 if (Tok.isNot(tok::identifier)) {
2000 Diag(Tok, diag::err_expected) << tok::identifier;
2001 SkipUntil(tok::r_paren, StopAtSemi);
2005 // Keep track of the various subcomponents we see.
2006 SmallVector<Sema::OffsetOfComponent, 4> Comps;
2008 Comps.push_back(Sema::OffsetOfComponent());
2009 Comps.back().isBrackets = false;
2010 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2011 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2013 // FIXME: This loop leaks the index expressions on error.
2015 if (Tok.is(tok::period)) {
2016 // offsetof-member-designator: offsetof-member-designator '.' identifier
2017 Comps.push_back(Sema::OffsetOfComponent());
2018 Comps.back().isBrackets = false;
2019 Comps.back().LocStart = ConsumeToken();
2021 if (Tok.isNot(tok::identifier)) {
2022 Diag(Tok, diag::err_expected) << tok::identifier;
2023 SkipUntil(tok::r_paren, StopAtSemi);
2026 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2027 Comps.back().LocEnd = ConsumeToken();
2029 } else if (Tok.is(tok::l_square)) {
2030 if (CheckProhibitedCXX11Attribute())
2033 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2034 Comps.push_back(Sema::OffsetOfComponent());
2035 Comps.back().isBrackets = true;
2036 BalancedDelimiterTracker ST(*this, tok::l_square);
2038 Comps.back().LocStart = ST.getOpenLocation();
2039 Res = ParseExpression();
2040 if (Res.isInvalid()) {
2041 SkipUntil(tok::r_paren, StopAtSemi);
2044 Comps.back().U.E = Res.get();
2047 Comps.back().LocEnd = ST.getCloseLocation();
2049 if (Tok.isNot(tok::r_paren)) {
2052 } else if (Ty.isInvalid()) {
2056 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2058 PT.getCloseLocation());
2065 case tok::kw___builtin_choose_expr: {
2066 ExprResult Cond(ParseAssignmentExpression());
2067 if (Cond.isInvalid()) {
2068 SkipUntil(tok::r_paren, StopAtSemi);
2071 if (ExpectAndConsume(tok::comma)) {
2072 SkipUntil(tok::r_paren, StopAtSemi);
2076 ExprResult Expr1(ParseAssignmentExpression());
2077 if (Expr1.isInvalid()) {
2078 SkipUntil(tok::r_paren, StopAtSemi);
2081 if (ExpectAndConsume(tok::comma)) {
2082 SkipUntil(tok::r_paren, StopAtSemi);
2086 ExprResult Expr2(ParseAssignmentExpression());
2087 if (Expr2.isInvalid()) {
2088 SkipUntil(tok::r_paren, StopAtSemi);
2091 if (Tok.isNot(tok::r_paren)) {
2092 Diag(Tok, diag::err_expected) << tok::r_paren;
2095 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2096 Expr2.get(), ConsumeParen());
2099 case tok::kw___builtin_astype: {
2100 // The first argument is an expression to be converted, followed by a comma.
2101 ExprResult Expr(ParseAssignmentExpression());
2102 if (Expr.isInvalid()) {
2103 SkipUntil(tok::r_paren, StopAtSemi);
2107 if (ExpectAndConsume(tok::comma)) {
2108 SkipUntil(tok::r_paren, StopAtSemi);
2112 // Second argument is the type to bitcast to.
2113 TypeResult DestTy = ParseTypeName();
2114 if (DestTy.isInvalid())
2117 // Attempt to consume the r-paren.
2118 if (Tok.isNot(tok::r_paren)) {
2119 Diag(Tok, diag::err_expected) << tok::r_paren;
2120 SkipUntil(tok::r_paren, StopAtSemi);
2124 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2128 case tok::kw___builtin_convertvector: {
2129 // The first argument is an expression to be converted, followed by a comma.
2130 ExprResult Expr(ParseAssignmentExpression());
2131 if (Expr.isInvalid()) {
2132 SkipUntil(tok::r_paren, StopAtSemi);
2136 if (ExpectAndConsume(tok::comma)) {
2137 SkipUntil(tok::r_paren, StopAtSemi);
2141 // Second argument is the type to bitcast to.
2142 TypeResult DestTy = ParseTypeName();
2143 if (DestTy.isInvalid())
2146 // Attempt to consume the r-paren.
2147 if (Tok.isNot(tok::r_paren)) {
2148 Diag(Tok, diag::err_expected) << tok::r_paren;
2149 SkipUntil(tok::r_paren, StopAtSemi);
2153 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2159 if (Res.isInvalid())
2162 // These can be followed by postfix-expr pieces because they are
2163 // primary-expressions.
2164 return ParsePostfixExpressionSuffix(Res.get());
2167 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2168 /// based on what is allowed by ExprType. The actual thing parsed is returned
2169 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2170 /// not the parsed cast-expression.
2173 /// primary-expression: [C99 6.5.1]
2174 /// '(' expression ')'
2175 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2176 /// postfix-expression: [C99 6.5.2]
2177 /// '(' type-name ')' '{' initializer-list '}'
2178 /// '(' type-name ')' '{' initializer-list ',' '}'
2179 /// cast-expression: [C99 6.5.4]
2180 /// '(' type-name ')' cast-expression
2181 /// [ARC] bridged-cast-expression
2182 /// [ARC] bridged-cast-expression:
2183 /// (__bridge type-name) cast-expression
2184 /// (__bridge_transfer type-name) cast-expression
2185 /// (__bridge_retained type-name) cast-expression
2186 /// fold-expression: [C++1z]
2187 /// '(' cast-expression fold-operator '...' ')'
2188 /// '(' '...' fold-operator cast-expression ')'
2189 /// '(' cast-expression fold-operator '...'
2190 /// fold-operator cast-expression ')'
2193 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2194 bool isTypeCast, ParsedType &CastTy,
2195 SourceLocation &RParenLoc) {
2196 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2197 ColonProtectionRAIIObject ColonProtection(*this, false);
2198 BalancedDelimiterTracker T(*this, tok::l_paren);
2199 if (T.consumeOpen())
2201 SourceLocation OpenLoc = T.getOpenLocation();
2203 ExprResult Result(true);
2204 bool isAmbiguousTypeId;
2207 if (Tok.is(tok::code_completion)) {
2208 Actions.CodeCompleteOrdinaryName(getCurScope(),
2209 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2210 : Sema::PCC_Expression);
2215 // Diagnose use of bridge casts in non-arc mode.
2216 bool BridgeCast = (getLangOpts().ObjC2 &&
2217 Tok.isOneOf(tok::kw___bridge,
2218 tok::kw___bridge_transfer,
2219 tok::kw___bridge_retained,
2220 tok::kw___bridge_retain));
2221 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2222 if (!TryConsumeToken(tok::kw___bridge)) {
2223 StringRef BridgeCastName = Tok.getName();
2224 SourceLocation BridgeKeywordLoc = ConsumeToken();
2225 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2226 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2228 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2233 // None of these cases should fall through with an invalid Result
2234 // unless they've already reported an error.
2235 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2236 Diag(Tok, diag::ext_gnu_statement_expr);
2238 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2239 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2241 // Find the nearest non-record decl context. Variables declared in a
2242 // statement expression behave as if they were declared in the enclosing
2243 // function, block, or other code construct.
2244 DeclContext *CodeDC = Actions.CurContext;
2245 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2246 CodeDC = CodeDC->getParent();
2247 assert(CodeDC && !CodeDC->isFileContext() &&
2248 "statement expr not in code context");
2250 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2252 Actions.ActOnStartStmtExpr();
2254 StmtResult Stmt(ParseCompoundStatement(true));
2255 ExprType = CompoundStmt;
2257 // If the substmt parsed correctly, build the AST node.
2258 if (!Stmt.isInvalid()) {
2259 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2261 Actions.ActOnStmtExprError();
2264 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2265 tok::TokenKind tokenKind = Tok.getKind();
2266 SourceLocation BridgeKeywordLoc = ConsumeToken();
2268 // Parse an Objective-C ARC ownership cast expression.
2269 ObjCBridgeCastKind Kind;
2270 if (tokenKind == tok::kw___bridge)
2272 else if (tokenKind == tok::kw___bridge_transfer)
2273 Kind = OBC_BridgeTransfer;
2274 else if (tokenKind == tok::kw___bridge_retained)
2275 Kind = OBC_BridgeRetained;
2277 // As a hopefully temporary workaround, allow __bridge_retain as
2278 // a synonym for __bridge_retained, but only in system headers.
2279 assert(tokenKind == tok::kw___bridge_retain);
2280 Kind = OBC_BridgeRetained;
2281 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2282 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2283 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2284 "__bridge_retained");
2287 TypeResult Ty = ParseTypeName();
2289 ColonProtection.restore();
2290 RParenLoc = T.getCloseLocation();
2291 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2293 if (Ty.isInvalid() || SubExpr.isInvalid())
2296 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2297 BridgeKeywordLoc, Ty.get(),
2298 RParenLoc, SubExpr.get());
2299 } else if (ExprType >= CompoundLiteral &&
2300 isTypeIdInParens(isAmbiguousTypeId)) {
2302 // Otherwise, this is a compound literal expression or cast expression.
2304 // In C++, if the type-id is ambiguous we disambiguate based on context.
2305 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2306 // in which case we should treat it as type-id.
2307 // if stopIfCastExpr is false, we need to determine the context past the
2308 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2309 if (isAmbiguousTypeId && !stopIfCastExpr) {
2310 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2312 RParenLoc = T.getCloseLocation();
2316 // Parse the type declarator.
2317 DeclSpec DS(AttrFactory);
2318 ParseSpecifierQualifierList(DS);
2319 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2320 ParseDeclarator(DeclaratorInfo);
2322 // If our type is followed by an identifier and either ':' or ']', then
2323 // this is probably an Objective-C message send where the leading '[' is
2324 // missing. Recover as if that were the case.
2325 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2326 !InMessageExpression && getLangOpts().ObjC1 &&
2327 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2330 InMessageExpressionRAIIObject InMessage(*this, false);
2331 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2333 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2339 ColonProtection.restore();
2340 RParenLoc = T.getCloseLocation();
2341 if (Tok.is(tok::l_brace)) {
2342 ExprType = CompoundLiteral;
2345 InMessageExpressionRAIIObject InMessage(*this, false);
2346 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2348 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2351 if (ExprType == CastExpr) {
2352 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2354 if (DeclaratorInfo.isInvalidType())
2357 // Note that this doesn't parse the subsequent cast-expression, it just
2358 // returns the parsed type to the callee.
2359 if (stopIfCastExpr) {
2362 InMessageExpressionRAIIObject InMessage(*this, false);
2363 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2366 return ExprResult();
2369 // Reject the cast of super idiom in ObjC.
2370 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2371 Tok.getIdentifierInfo() == Ident_super &&
2372 getCurScope()->isInObjcMethodScope() &&
2373 GetLookAheadToken(1).isNot(tok::period)) {
2374 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2375 << SourceRange(OpenLoc, RParenLoc);
2379 // Parse the cast-expression that follows it next.
2380 // TODO: For cast expression with CastTy.
2381 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2382 /*isAddressOfOperand=*/false,
2383 /*isTypeCast=*/IsTypeCast);
2384 if (!Result.isInvalid()) {
2385 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2386 DeclaratorInfo, CastTy,
2387 RParenLoc, Result.get());
2392 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2395 } else if (Tok.is(tok::ellipsis) &&
2396 isFoldOperator(NextToken().getKind())) {
2397 return ParseFoldExpression(ExprResult(), T);
2398 } else if (isTypeCast) {
2399 // Parse the expression-list.
2400 InMessageExpressionRAIIObject InMessage(*this, false);
2402 ExprVector ArgExprs;
2403 CommaLocsTy CommaLocs;
2405 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2406 // FIXME: If we ever support comma expressions as operands to
2407 // fold-expressions, we'll need to allow multiple ArgExprs here.
2408 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2409 NextToken().is(tok::ellipsis))
2410 return ParseFoldExpression(Result, T);
2412 ExprType = SimpleExpr;
2413 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2417 InMessageExpressionRAIIObject InMessage(*this, false);
2419 Result = ParseExpression(MaybeTypeCast);
2420 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2421 // Correct typos in non-C++ code earlier so that implicit-cast-like
2422 // expressions are parsed correctly.
2423 Result = Actions.CorrectDelayedTyposInExpr(Result);
2425 ExprType = SimpleExpr;
2427 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2428 return ParseFoldExpression(Result, T);
2430 // Don't build a paren expression unless we actually match a ')'.
2431 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2433 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2437 if (Result.isInvalid()) {
2438 SkipUntil(tok::r_paren, StopAtSemi);
2443 RParenLoc = T.getCloseLocation();
2447 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2448 /// and we are at the left brace.
2451 /// postfix-expression: [C99 6.5.2]
2452 /// '(' type-name ')' '{' initializer-list '}'
2453 /// '(' type-name ')' '{' initializer-list ',' '}'
2456 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2457 SourceLocation LParenLoc,
2458 SourceLocation RParenLoc) {
2459 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2460 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2461 Diag(LParenLoc, diag::ext_c99_compound_literal);
2462 ExprResult Result = ParseInitializer();
2463 if (!Result.isInvalid() && Ty)
2464 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2468 /// ParseStringLiteralExpression - This handles the various token types that
2469 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2470 /// translation phase #6].
2473 /// primary-expression: [C99 6.5.1]
2476 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2477 assert(isTokenStringLiteral() && "Not a string literal!");
2479 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2480 // considered to be strings for concatenation purposes.
2481 SmallVector<Token, 4> StringToks;
2484 StringToks.push_back(Tok);
2485 ConsumeStringToken();
2486 } while (isTokenStringLiteral());
2488 // Pass the set of string tokens, ready for concatenation, to the actions.
2489 return Actions.ActOnStringLiteral(StringToks,
2490 AllowUserDefinedLiteral ? getCurScope()
2494 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2498 /// generic-selection:
2499 /// _Generic ( assignment-expression , generic-assoc-list )
2500 /// generic-assoc-list:
2501 /// generic-association
2502 /// generic-assoc-list , generic-association
2503 /// generic-association:
2504 /// type-name : assignment-expression
2505 /// default : assignment-expression
2507 ExprResult Parser::ParseGenericSelectionExpression() {
2508 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2509 SourceLocation KeyLoc = ConsumeToken();
2511 if (!getLangOpts().C11)
2512 Diag(KeyLoc, diag::ext_c11_generic_selection);
2514 BalancedDelimiterTracker T(*this, tok::l_paren);
2515 if (T.expectAndConsume())
2518 ExprResult ControllingExpr;
2520 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2522 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2524 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2525 if (ControllingExpr.isInvalid()) {
2526 SkipUntil(tok::r_paren, StopAtSemi);
2531 if (ExpectAndConsume(tok::comma)) {
2532 SkipUntil(tok::r_paren, StopAtSemi);
2536 SourceLocation DefaultLoc;
2541 if (Tok.is(tok::kw_default)) {
2542 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2543 // generic association."
2544 if (!DefaultLoc.isInvalid()) {
2545 Diag(Tok, diag::err_duplicate_default_assoc);
2546 Diag(DefaultLoc, diag::note_previous_default_assoc);
2547 SkipUntil(tok::r_paren, StopAtSemi);
2550 DefaultLoc = ConsumeToken();
2553 ColonProtectionRAIIObject X(*this);
2554 TypeResult TR = ParseTypeName();
2555 if (TR.isInvalid()) {
2556 SkipUntil(tok::r_paren, StopAtSemi);
2561 Types.push_back(Ty);
2563 if (ExpectAndConsume(tok::colon)) {
2564 SkipUntil(tok::r_paren, StopAtSemi);
2568 // FIXME: These expressions should be parsed in a potentially potentially
2569 // evaluated context.
2571 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2572 if (ER.isInvalid()) {
2573 SkipUntil(tok::r_paren, StopAtSemi);
2576 Exprs.push_back(ER.get());
2577 } while (TryConsumeToken(tok::comma));
2580 if (T.getCloseLocation().isInvalid())
2583 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2584 T.getCloseLocation(),
2585 ControllingExpr.get(),
2589 /// \brief Parse A C++1z fold-expression after the opening paren and optional
2590 /// left-hand-side expression.
2593 /// fold-expression:
2594 /// ( cast-expression fold-operator ... )
2595 /// ( ... fold-operator cast-expression )
2596 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2597 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2598 BalancedDelimiterTracker &T) {
2599 if (LHS.isInvalid()) {
2604 tok::TokenKind Kind = tok::unknown;
2605 SourceLocation FirstOpLoc;
2606 if (LHS.isUsable()) {
2607 Kind = Tok.getKind();
2608 assert(isFoldOperator(Kind) && "missing fold-operator");
2609 FirstOpLoc = ConsumeToken();
2612 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2613 SourceLocation EllipsisLoc = ConsumeToken();
2616 if (Tok.isNot(tok::r_paren)) {
2617 if (!isFoldOperator(Tok.getKind()))
2618 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2620 if (Kind != tok::unknown && Tok.getKind() != Kind)
2621 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2622 << SourceRange(FirstOpLoc);
2623 Kind = Tok.getKind();
2626 RHS = ParseExpression();
2627 if (RHS.isInvalid()) {
2633 Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
2634 ? diag::warn_cxx14_compat_fold_expression
2635 : diag::ext_fold_expression);
2638 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2639 EllipsisLoc, RHS.get(), T.getCloseLocation());
2642 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2645 /// argument-expression-list:
2646 /// assignment-expression
2647 /// argument-expression-list , assignment-expression
2649 /// [C++] expression-list:
2650 /// [C++] assignment-expression
2651 /// [C++] expression-list , assignment-expression
2653 /// [C++0x] expression-list:
2654 /// [C++0x] initializer-list
2656 /// [C++0x] initializer-list
2657 /// [C++0x] initializer-clause ...[opt]
2658 /// [C++0x] initializer-list , initializer-clause ...[opt]
2660 /// [C++0x] initializer-clause:
2661 /// [C++0x] assignment-expression
2662 /// [C++0x] braced-init-list
2664 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2665 SmallVectorImpl<SourceLocation> &CommaLocs,
2666 std::function<void()> Completer) {
2667 bool SawError = false;
2669 if (Tok.is(tok::code_completion)) {
2673 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2679 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2680 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2681 Expr = ParseBraceInitializer();
2683 Expr = ParseAssignmentExpression();
2685 if (Tok.is(tok::ellipsis))
2686 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2687 if (Expr.isInvalid()) {
2688 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2691 Exprs.push_back(Expr.get());
2694 if (Tok.isNot(tok::comma))
2696 // Move to the next argument, remember where the comma was.
2697 CommaLocs.push_back(ConsumeToken());
2700 // Ensure typos get diagnosed when errors were encountered while parsing the
2702 for (auto &E : Exprs) {
2703 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2704 if (Expr.isUsable()) E = Expr.get();
2710 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2711 /// used for misc language extensions.
2714 /// simple-expression-list:
2715 /// assignment-expression
2716 /// simple-expression-list , assignment-expression
2719 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2720 SmallVectorImpl<SourceLocation> &CommaLocs) {
2722 ExprResult Expr = ParseAssignmentExpression();
2723 if (Expr.isInvalid())
2726 Exprs.push_back(Expr.get());
2728 if (Tok.isNot(tok::comma))
2731 // Move to the next argument, remember where the comma was.
2732 CommaLocs.push_back(ConsumeToken());
2736 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2739 /// [clang] block-id:
2740 /// [clang] specifier-qualifier-list block-declarator
2742 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2743 if (Tok.is(tok::code_completion)) {
2744 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2745 return cutOffParsing();
2748 // Parse the specifier-qualifier-list piece.
2749 DeclSpec DS(AttrFactory);
2750 ParseSpecifierQualifierList(DS);
2752 // Parse the block-declarator.
2753 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2754 DeclaratorInfo.setFunctionDefinitionKind(FDK_Definition);
2755 ParseDeclarator(DeclaratorInfo);
2757 MaybeParseGNUAttributes(DeclaratorInfo);
2759 // Inform sema that we are starting a block.
2760 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2763 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2764 /// like ^(int x){ return x+1; }
2768 /// [clang] '^' block-args[opt] compound-statement
2769 /// [clang] '^' block-id compound-statement
2770 /// [clang] block-args:
2771 /// [clang] '(' parameter-list ')'
2773 ExprResult Parser::ParseBlockLiteralExpression() {
2774 assert(Tok.is(tok::caret) && "block literal starts with ^");
2775 SourceLocation CaretLoc = ConsumeToken();
2777 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2778 "block literal parsing");
2780 // Enter a scope to hold everything within the block. This includes the
2781 // argument decls, decls within the compound expression, etc. This also
2782 // allows determining whether a variable reference inside the block is
2783 // within or outside of the block.
2784 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2787 // Inform sema that we are starting a block.
2788 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2790 // Parse the return type if present.
2791 DeclSpec DS(AttrFactory);
2792 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2793 ParamInfo.setFunctionDefinitionKind(FDK_Definition);
2794 // FIXME: Since the return type isn't actually parsed, it can't be used to
2795 // fill ParamInfo with an initial valid range, so do it manually.
2796 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2798 // If this block has arguments, parse them. There is no ambiguity here with
2799 // the expression case, because the expression case requires a parameter list.
2800 if (Tok.is(tok::l_paren)) {
2801 ParseParenDeclarator(ParamInfo);
2802 // Parse the pieces after the identifier as if we had "int(...)".
2803 // SetIdentifier sets the source range end, but in this case we're past
2805 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2806 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2807 ParamInfo.SetRangeEnd(Tmp);
2808 if (ParamInfo.isInvalidType()) {
2809 // If there was an error parsing the arguments, they may have
2810 // tried to use ^(x+y) which requires an argument list. Just
2811 // skip the whole block literal.
2812 Actions.ActOnBlockError(CaretLoc, getCurScope());
2816 MaybeParseGNUAttributes(ParamInfo);
2818 // Inform sema that we are starting a block.
2819 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2820 } else if (!Tok.is(tok::l_brace)) {
2821 ParseBlockId(CaretLoc);
2823 // Otherwise, pretend we saw (void).
2824 ParsedAttributes attrs(AttrFactory);
2825 SourceLocation NoLoc;
2826 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2827 /*IsAmbiguous=*/false,
2828 /*RParenLoc=*/NoLoc,
2829 /*ArgInfo=*/nullptr,
2831 /*EllipsisLoc=*/NoLoc,
2832 /*RParenLoc=*/NoLoc,
2834 /*RefQualifierIsLvalueRef=*/true,
2835 /*RefQualifierLoc=*/NoLoc,
2836 /*ConstQualifierLoc=*/NoLoc,
2837 /*VolatileQualifierLoc=*/NoLoc,
2838 /*RestrictQualifierLoc=*/NoLoc,
2839 /*MutableLoc=*/NoLoc,
2841 /*ESpecRange=*/SourceRange(),
2842 /*Exceptions=*/nullptr,
2843 /*ExceptionRanges=*/nullptr,
2844 /*NumExceptions=*/0,
2845 /*NoexceptExpr=*/nullptr,
2846 /*ExceptionSpecTokens=*/nullptr,
2847 /*DeclsInPrototype=*/None,
2852 MaybeParseGNUAttributes(ParamInfo);
2854 // Inform sema that we are starting a block.
2855 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2859 ExprResult Result(true);
2860 if (!Tok.is(tok::l_brace)) {
2861 // Saw something like: ^expr
2862 Diag(Tok, diag::err_expected_expression);
2863 Actions.ActOnBlockError(CaretLoc, getCurScope());
2867 StmtResult Stmt(ParseCompoundStatementBody());
2869 if (!Stmt.isInvalid())
2870 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2872 Actions.ActOnBlockError(CaretLoc, getCurScope());
2876 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2880 ExprResult Parser::ParseObjCBoolLiteral() {
2881 tok::TokenKind Kind = Tok.getKind();
2882 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
2885 /// Validate availability spec list, emitting diagnostics if necessary. Returns
2886 /// true if invalid.
2887 static bool CheckAvailabilitySpecList(Parser &P,
2888 ArrayRef<AvailabilitySpec> AvailSpecs) {
2889 llvm::SmallSet<StringRef, 4> Platforms;
2890 bool HasOtherPlatformSpec = false;
2892 for (const auto &Spec : AvailSpecs) {
2893 if (Spec.isOtherPlatformSpec()) {
2894 if (HasOtherPlatformSpec) {
2895 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
2899 HasOtherPlatformSpec = true;
2903 bool Inserted = Platforms.insert(Spec.getPlatform()).second;
2905 // Rule out multiple version specs referring to the same platform.
2906 // For example, we emit an error for:
2907 // @available(macos 10.10, macos 10.11, *)
2908 StringRef Platform = Spec.getPlatform();
2909 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
2910 << Spec.getEndLoc() << Platform;
2915 if (!HasOtherPlatformSpec) {
2916 SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
2917 P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
2918 << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
2925 /// Parse availability query specification.
2927 /// availability-spec:
2929 /// identifier version-tuple
2930 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
2931 if (Tok.is(tok::star)) {
2932 return AvailabilitySpec(ConsumeToken());
2934 // Parse the platform name.
2935 if (Tok.isNot(tok::identifier)) {
2936 Diag(Tok, diag::err_avail_query_expected_platform_name);
2940 IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
2941 SourceRange VersionRange;
2942 VersionTuple Version = ParseVersionTuple(VersionRange);
2944 if (Version.empty())
2947 StringRef Platform = PlatformIdentifier->Ident->getName();
2949 if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
2950 Diag(PlatformIdentifier->Loc,
2951 diag::err_avail_query_unrecognized_platform_name)
2956 return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
2957 VersionRange.getEnd());
2961 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
2962 assert(Tok.is(tok::kw___builtin_available) ||
2963 Tok.isObjCAtKeyword(tok::objc_available));
2965 // Eat the available or __builtin_available.
2968 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2969 if (Parens.expectAndConsume())
2972 SmallVector<AvailabilitySpec, 4> AvailSpecs;
2973 bool HasError = false;
2975 Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
2979 AvailSpecs.push_back(*Spec);
2981 if (!TryConsumeToken(tok::comma))
2986 SkipUntil(tok::r_paren, StopAtSemi);
2990 CheckAvailabilitySpecList(*this, AvailSpecs);
2992 if (Parens.consumeClose())
2995 return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
2996 Parens.getCloseLocation());