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 ConstantEvaluated(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 if (Expr *Base = LHS.get())
1656 Actions.CodeCompleteMemberReferenceExpr(
1657 getCurScope(), Base, OpLoc, OpKind == tok::arrow,
1658 ExprStatementTokLoc == Base->getLocStart());
1664 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1665 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1670 // Either the action has told us that this cannot be a
1671 // pseudo-destructor expression (based on the type of base
1672 // expression), or we didn't see a '~' in the right place. We
1673 // can still parse a destructor name here, but in that case it
1674 // names a real destructor.
1675 // Allow explicit constructor calls in Microsoft mode.
1676 // FIXME: Add support for explicit call of template constructor.
1677 SourceLocation TemplateKWLoc;
1679 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1680 Tok.is(tok::kw_class)) {
1682 // After a '.' in a member access expression, treat the keyword
1683 // 'class' as if it were an identifier.
1685 // This hack allows property access to the 'class' method because it is
1686 // such a common method name. For other C++ keywords that are
1687 // Objective-C method names, one must use the message send syntax.
1688 IdentifierInfo *Id = Tok.getIdentifierInfo();
1689 SourceLocation Loc = ConsumeToken();
1690 Name.setIdentifier(Id, Loc);
1691 } else if (ParseUnqualifiedId(SS,
1692 /*EnteringContext=*/false,
1693 /*AllowDestructorName=*/true,
1694 /*AllowConstructorName=*/
1695 getLangOpts().MicrosoftExt,
1696 ObjectType, TemplateKWLoc, Name)) {
1697 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1701 if (!LHS.isInvalid())
1702 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1703 OpKind, SS, TemplateKWLoc, Name,
1704 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1708 case tok::plusplus: // postfix-expression: postfix-expression '++'
1709 case tok::minusminus: // postfix-expression: postfix-expression '--'
1710 if (!LHS.isInvalid()) {
1711 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1712 Tok.getKind(), LHS.get());
1720 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1721 /// vec_step and we are at the start of an expression or a parenthesized
1722 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1723 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1726 /// unary-expression: [C99 6.5.3]
1727 /// 'sizeof' unary-expression
1728 /// 'sizeof' '(' type-name ')'
1729 /// [GNU] '__alignof' unary-expression
1730 /// [GNU] '__alignof' '(' type-name ')'
1731 /// [C11] '_Alignof' '(' type-name ')'
1732 /// [C++0x] 'alignof' '(' type-id ')'
1734 /// [GNU] typeof-specifier:
1735 /// typeof ( expressions )
1736 /// typeof ( type-name )
1737 /// [GNU/C++] typeof unary-expression
1739 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1740 /// vec_step ( expressions )
1741 /// vec_step ( type-name )
1744 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1747 SourceRange &CastRange) {
1749 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1750 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1751 tok::kw___builtin_omp_required_simd_align) &&
1752 "Not a typeof/sizeof/alignof/vec_step expression!");
1756 // If the operand doesn't start with an '(', it must be an expression.
1757 if (Tok.isNot(tok::l_paren)) {
1758 // If construct allows a form without parenthesis, user may forget to put
1759 // pathenthesis around type name.
1760 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1761 tok::kw__Alignof)) {
1762 if (isTypeIdUnambiguously()) {
1763 DeclSpec DS(AttrFactory);
1764 ParseSpecifierQualifierList(DS);
1765 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1766 ParseDeclarator(DeclaratorInfo);
1768 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1769 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1770 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1772 << FixItHint::CreateInsertion(LParenLoc, "(")
1773 << FixItHint::CreateInsertion(RParenLoc, ")");
1780 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1781 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1786 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1788 // If it starts with a '(', we know that it is either a parenthesized
1789 // type-name, or it is a unary-expression that starts with a compound
1790 // literal, or starts with a primary-expression that is a parenthesized
1792 ParenParseOption ExprType = CastExpr;
1793 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1795 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1796 false, CastTy, RParenLoc);
1797 CastRange = SourceRange(LParenLoc, RParenLoc);
1799 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1801 if (ExprType == CastExpr) {
1806 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1807 // GNU typeof in C requires the expression to be parenthesized. Not so for
1808 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1809 // the start of a unary-expression, but doesn't include any postfix
1810 // pieces. Parse these now if present.
1811 if (!Operand.isInvalid())
1812 Operand = ParsePostfixExpressionSuffix(Operand.get());
1816 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1822 /// \brief Parse a sizeof or alignof expression.
1825 /// unary-expression: [C99 6.5.3]
1826 /// 'sizeof' unary-expression
1827 /// 'sizeof' '(' type-name ')'
1828 /// [C++11] 'sizeof' '...' '(' identifier ')'
1829 /// [GNU] '__alignof' unary-expression
1830 /// [GNU] '__alignof' '(' type-name ')'
1831 /// [C11] '_Alignof' '(' type-name ')'
1832 /// [C++11] 'alignof' '(' type-id ')'
1834 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1835 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1836 tok::kw__Alignof, tok::kw_vec_step,
1837 tok::kw___builtin_omp_required_simd_align) &&
1838 "Not a sizeof/alignof/vec_step expression!");
1842 // [C++11] 'sizeof' '...' '(' identifier ')'
1843 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1844 SourceLocation EllipsisLoc = ConsumeToken();
1845 SourceLocation LParenLoc, RParenLoc;
1846 IdentifierInfo *Name = nullptr;
1847 SourceLocation NameLoc;
1848 if (Tok.is(tok::l_paren)) {
1849 BalancedDelimiterTracker T(*this, tok::l_paren);
1851 LParenLoc = T.getOpenLocation();
1852 if (Tok.is(tok::identifier)) {
1853 Name = Tok.getIdentifierInfo();
1854 NameLoc = ConsumeToken();
1856 RParenLoc = T.getCloseLocation();
1857 if (RParenLoc.isInvalid())
1858 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1860 Diag(Tok, diag::err_expected_parameter_pack);
1861 SkipUntil(tok::r_paren, StopAtSemi);
1863 } else if (Tok.is(tok::identifier)) {
1864 Name = Tok.getIdentifierInfo();
1865 NameLoc = ConsumeToken();
1866 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1867 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1868 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1870 << FixItHint::CreateInsertion(LParenLoc, "(")
1871 << FixItHint::CreateInsertion(RParenLoc, ")");
1873 Diag(Tok, diag::err_sizeof_parameter_pack);
1879 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1880 Sema::ReuseLambdaContextDecl);
1882 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1883 OpTok.getLocation(),
1888 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1889 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1891 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1892 Sema::ReuseLambdaContextDecl);
1896 SourceRange CastRange;
1897 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1902 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1903 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1904 ExprKind = UETT_AlignOf;
1905 else if (OpTok.is(tok::kw_vec_step))
1906 ExprKind = UETT_VecStep;
1907 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
1908 ExprKind = UETT_OpenMPRequiredSimdAlign;
1911 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1914 CastTy.getAsOpaquePtr(),
1917 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1918 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1920 // If we get here, the operand to the sizeof/alignof was an expresion.
1921 if (!Operand.isInvalid())
1922 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1930 /// ParseBuiltinPrimaryExpression
1933 /// primary-expression: [C99 6.5.1]
1934 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1935 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1936 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1938 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1939 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1941 /// [GNU] offsetof-member-designator:
1942 /// [GNU] identifier
1943 /// [GNU] offsetof-member-designator '.' identifier
1944 /// [GNU] offsetof-member-designator '[' expression ']'
1946 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1948 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1950 tok::TokenKind T = Tok.getKind();
1951 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
1953 // All of these start with an open paren.
1954 if (Tok.isNot(tok::l_paren))
1955 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
1958 BalancedDelimiterTracker PT(*this, tok::l_paren);
1964 default: llvm_unreachable("Not a builtin primary expression!");
1965 case tok::kw___builtin_va_arg: {
1966 ExprResult Expr(ParseAssignmentExpression());
1968 if (ExpectAndConsume(tok::comma)) {
1969 SkipUntil(tok::r_paren, StopAtSemi);
1973 TypeResult Ty = ParseTypeName();
1975 if (Tok.isNot(tok::r_paren)) {
1976 Diag(Tok, diag::err_expected) << tok::r_paren;
1980 if (Expr.isInvalid() || Ty.isInvalid())
1983 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
1986 case tok::kw___builtin_offsetof: {
1987 SourceLocation TypeLoc = Tok.getLocation();
1988 TypeResult Ty = ParseTypeName();
1989 if (Ty.isInvalid()) {
1990 SkipUntil(tok::r_paren, StopAtSemi);
1994 if (ExpectAndConsume(tok::comma)) {
1995 SkipUntil(tok::r_paren, StopAtSemi);
1999 // We must have at least one identifier here.
2000 if (Tok.isNot(tok::identifier)) {
2001 Diag(Tok, diag::err_expected) << tok::identifier;
2002 SkipUntil(tok::r_paren, StopAtSemi);
2006 // Keep track of the various subcomponents we see.
2007 SmallVector<Sema::OffsetOfComponent, 4> Comps;
2009 Comps.push_back(Sema::OffsetOfComponent());
2010 Comps.back().isBrackets = false;
2011 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2012 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2014 // FIXME: This loop leaks the index expressions on error.
2016 if (Tok.is(tok::period)) {
2017 // offsetof-member-designator: offsetof-member-designator '.' identifier
2018 Comps.push_back(Sema::OffsetOfComponent());
2019 Comps.back().isBrackets = false;
2020 Comps.back().LocStart = ConsumeToken();
2022 if (Tok.isNot(tok::identifier)) {
2023 Diag(Tok, diag::err_expected) << tok::identifier;
2024 SkipUntil(tok::r_paren, StopAtSemi);
2027 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2028 Comps.back().LocEnd = ConsumeToken();
2030 } else if (Tok.is(tok::l_square)) {
2031 if (CheckProhibitedCXX11Attribute())
2034 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2035 Comps.push_back(Sema::OffsetOfComponent());
2036 Comps.back().isBrackets = true;
2037 BalancedDelimiterTracker ST(*this, tok::l_square);
2039 Comps.back().LocStart = ST.getOpenLocation();
2040 Res = ParseExpression();
2041 if (Res.isInvalid()) {
2042 SkipUntil(tok::r_paren, StopAtSemi);
2045 Comps.back().U.E = Res.get();
2048 Comps.back().LocEnd = ST.getCloseLocation();
2050 if (Tok.isNot(tok::r_paren)) {
2053 } else if (Ty.isInvalid()) {
2057 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2059 PT.getCloseLocation());
2066 case tok::kw___builtin_choose_expr: {
2067 ExprResult Cond(ParseAssignmentExpression());
2068 if (Cond.isInvalid()) {
2069 SkipUntil(tok::r_paren, StopAtSemi);
2072 if (ExpectAndConsume(tok::comma)) {
2073 SkipUntil(tok::r_paren, StopAtSemi);
2077 ExprResult Expr1(ParseAssignmentExpression());
2078 if (Expr1.isInvalid()) {
2079 SkipUntil(tok::r_paren, StopAtSemi);
2082 if (ExpectAndConsume(tok::comma)) {
2083 SkipUntil(tok::r_paren, StopAtSemi);
2087 ExprResult Expr2(ParseAssignmentExpression());
2088 if (Expr2.isInvalid()) {
2089 SkipUntil(tok::r_paren, StopAtSemi);
2092 if (Tok.isNot(tok::r_paren)) {
2093 Diag(Tok, diag::err_expected) << tok::r_paren;
2096 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2097 Expr2.get(), ConsumeParen());
2100 case tok::kw___builtin_astype: {
2101 // The first argument is an expression to be converted, followed by a comma.
2102 ExprResult Expr(ParseAssignmentExpression());
2103 if (Expr.isInvalid()) {
2104 SkipUntil(tok::r_paren, StopAtSemi);
2108 if (ExpectAndConsume(tok::comma)) {
2109 SkipUntil(tok::r_paren, StopAtSemi);
2113 // Second argument is the type to bitcast to.
2114 TypeResult DestTy = ParseTypeName();
2115 if (DestTy.isInvalid())
2118 // Attempt to consume the r-paren.
2119 if (Tok.isNot(tok::r_paren)) {
2120 Diag(Tok, diag::err_expected) << tok::r_paren;
2121 SkipUntil(tok::r_paren, StopAtSemi);
2125 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2129 case tok::kw___builtin_convertvector: {
2130 // The first argument is an expression to be converted, followed by a comma.
2131 ExprResult Expr(ParseAssignmentExpression());
2132 if (Expr.isInvalid()) {
2133 SkipUntil(tok::r_paren, StopAtSemi);
2137 if (ExpectAndConsume(tok::comma)) {
2138 SkipUntil(tok::r_paren, StopAtSemi);
2142 // Second argument is the type to bitcast to.
2143 TypeResult DestTy = ParseTypeName();
2144 if (DestTy.isInvalid())
2147 // Attempt to consume the r-paren.
2148 if (Tok.isNot(tok::r_paren)) {
2149 Diag(Tok, diag::err_expected) << tok::r_paren;
2150 SkipUntil(tok::r_paren, StopAtSemi);
2154 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2160 if (Res.isInvalid())
2163 // These can be followed by postfix-expr pieces because they are
2164 // primary-expressions.
2165 return ParsePostfixExpressionSuffix(Res.get());
2168 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2169 /// based on what is allowed by ExprType. The actual thing parsed is returned
2170 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2171 /// not the parsed cast-expression.
2174 /// primary-expression: [C99 6.5.1]
2175 /// '(' expression ')'
2176 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2177 /// postfix-expression: [C99 6.5.2]
2178 /// '(' type-name ')' '{' initializer-list '}'
2179 /// '(' type-name ')' '{' initializer-list ',' '}'
2180 /// cast-expression: [C99 6.5.4]
2181 /// '(' type-name ')' cast-expression
2182 /// [ARC] bridged-cast-expression
2183 /// [ARC] bridged-cast-expression:
2184 /// (__bridge type-name) cast-expression
2185 /// (__bridge_transfer type-name) cast-expression
2186 /// (__bridge_retained type-name) cast-expression
2187 /// fold-expression: [C++1z]
2188 /// '(' cast-expression fold-operator '...' ')'
2189 /// '(' '...' fold-operator cast-expression ')'
2190 /// '(' cast-expression fold-operator '...'
2191 /// fold-operator cast-expression ')'
2194 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2195 bool isTypeCast, ParsedType &CastTy,
2196 SourceLocation &RParenLoc) {
2197 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2198 ColonProtectionRAIIObject ColonProtection(*this, false);
2199 BalancedDelimiterTracker T(*this, tok::l_paren);
2200 if (T.consumeOpen())
2202 SourceLocation OpenLoc = T.getOpenLocation();
2204 ExprResult Result(true);
2205 bool isAmbiguousTypeId;
2208 if (Tok.is(tok::code_completion)) {
2209 Actions.CodeCompleteOrdinaryName(getCurScope(),
2210 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2211 : Sema::PCC_Expression);
2216 // Diagnose use of bridge casts in non-arc mode.
2217 bool BridgeCast = (getLangOpts().ObjC2 &&
2218 Tok.isOneOf(tok::kw___bridge,
2219 tok::kw___bridge_transfer,
2220 tok::kw___bridge_retained,
2221 tok::kw___bridge_retain));
2222 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2223 if (!TryConsumeToken(tok::kw___bridge)) {
2224 StringRef BridgeCastName = Tok.getName();
2225 SourceLocation BridgeKeywordLoc = ConsumeToken();
2226 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2227 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2229 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2234 // None of these cases should fall through with an invalid Result
2235 // unless they've already reported an error.
2236 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2237 Diag(Tok, diag::ext_gnu_statement_expr);
2239 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2240 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2242 // Find the nearest non-record decl context. Variables declared in a
2243 // statement expression behave as if they were declared in the enclosing
2244 // function, block, or other code construct.
2245 DeclContext *CodeDC = Actions.CurContext;
2246 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2247 CodeDC = CodeDC->getParent();
2248 assert(CodeDC && !CodeDC->isFileContext() &&
2249 "statement expr not in code context");
2251 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2253 Actions.ActOnStartStmtExpr();
2255 StmtResult Stmt(ParseCompoundStatement(true));
2256 ExprType = CompoundStmt;
2258 // If the substmt parsed correctly, build the AST node.
2259 if (!Stmt.isInvalid()) {
2260 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2262 Actions.ActOnStmtExprError();
2265 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2266 tok::TokenKind tokenKind = Tok.getKind();
2267 SourceLocation BridgeKeywordLoc = ConsumeToken();
2269 // Parse an Objective-C ARC ownership cast expression.
2270 ObjCBridgeCastKind Kind;
2271 if (tokenKind == tok::kw___bridge)
2273 else if (tokenKind == tok::kw___bridge_transfer)
2274 Kind = OBC_BridgeTransfer;
2275 else if (tokenKind == tok::kw___bridge_retained)
2276 Kind = OBC_BridgeRetained;
2278 // As a hopefully temporary workaround, allow __bridge_retain as
2279 // a synonym for __bridge_retained, but only in system headers.
2280 assert(tokenKind == tok::kw___bridge_retain);
2281 Kind = OBC_BridgeRetained;
2282 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2283 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2284 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2285 "__bridge_retained");
2288 TypeResult Ty = ParseTypeName();
2290 ColonProtection.restore();
2291 RParenLoc = T.getCloseLocation();
2292 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2294 if (Ty.isInvalid() || SubExpr.isInvalid())
2297 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2298 BridgeKeywordLoc, Ty.get(),
2299 RParenLoc, SubExpr.get());
2300 } else if (ExprType >= CompoundLiteral &&
2301 isTypeIdInParens(isAmbiguousTypeId)) {
2303 // Otherwise, this is a compound literal expression or cast expression.
2305 // In C++, if the type-id is ambiguous we disambiguate based on context.
2306 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2307 // in which case we should treat it as type-id.
2308 // if stopIfCastExpr is false, we need to determine the context past the
2309 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2310 if (isAmbiguousTypeId && !stopIfCastExpr) {
2311 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2313 RParenLoc = T.getCloseLocation();
2317 // Parse the type declarator.
2318 DeclSpec DS(AttrFactory);
2319 ParseSpecifierQualifierList(DS);
2320 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2321 ParseDeclarator(DeclaratorInfo);
2323 // If our type is followed by an identifier and either ':' or ']', then
2324 // this is probably an Objective-C message send where the leading '[' is
2325 // missing. Recover as if that were the case.
2326 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2327 !InMessageExpression && getLangOpts().ObjC1 &&
2328 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2331 InMessageExpressionRAIIObject InMessage(*this, false);
2332 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2334 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2340 ColonProtection.restore();
2341 RParenLoc = T.getCloseLocation();
2342 if (Tok.is(tok::l_brace)) {
2343 ExprType = CompoundLiteral;
2346 InMessageExpressionRAIIObject InMessage(*this, false);
2347 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2349 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2352 if (ExprType == CastExpr) {
2353 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2355 if (DeclaratorInfo.isInvalidType())
2358 // Note that this doesn't parse the subsequent cast-expression, it just
2359 // returns the parsed type to the callee.
2360 if (stopIfCastExpr) {
2363 InMessageExpressionRAIIObject InMessage(*this, false);
2364 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2367 return ExprResult();
2370 // Reject the cast of super idiom in ObjC.
2371 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2372 Tok.getIdentifierInfo() == Ident_super &&
2373 getCurScope()->isInObjcMethodScope() &&
2374 GetLookAheadToken(1).isNot(tok::period)) {
2375 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2376 << SourceRange(OpenLoc, RParenLoc);
2380 // Parse the cast-expression that follows it next.
2381 // TODO: For cast expression with CastTy.
2382 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2383 /*isAddressOfOperand=*/false,
2384 /*isTypeCast=*/IsTypeCast);
2385 if (!Result.isInvalid()) {
2386 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2387 DeclaratorInfo, CastTy,
2388 RParenLoc, Result.get());
2393 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2396 } else if (Tok.is(tok::ellipsis) &&
2397 isFoldOperator(NextToken().getKind())) {
2398 return ParseFoldExpression(ExprResult(), T);
2399 } else if (isTypeCast) {
2400 // Parse the expression-list.
2401 InMessageExpressionRAIIObject InMessage(*this, false);
2403 ExprVector ArgExprs;
2404 CommaLocsTy CommaLocs;
2406 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2407 // FIXME: If we ever support comma expressions as operands to
2408 // fold-expressions, we'll need to allow multiple ArgExprs here.
2409 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2410 NextToken().is(tok::ellipsis))
2411 return ParseFoldExpression(ArgExprs[0], T);
2413 ExprType = SimpleExpr;
2414 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2418 InMessageExpressionRAIIObject InMessage(*this, false);
2420 Result = ParseExpression(MaybeTypeCast);
2421 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2422 // Correct typos in non-C++ code earlier so that implicit-cast-like
2423 // expressions are parsed correctly.
2424 Result = Actions.CorrectDelayedTyposInExpr(Result);
2426 ExprType = SimpleExpr;
2428 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2429 return ParseFoldExpression(Result, T);
2431 // Don't build a paren expression unless we actually match a ')'.
2432 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2434 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2438 if (Result.isInvalid()) {
2439 SkipUntil(tok::r_paren, StopAtSemi);
2444 RParenLoc = T.getCloseLocation();
2448 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2449 /// and we are at the left brace.
2452 /// postfix-expression: [C99 6.5.2]
2453 /// '(' type-name ')' '{' initializer-list '}'
2454 /// '(' type-name ')' '{' initializer-list ',' '}'
2457 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2458 SourceLocation LParenLoc,
2459 SourceLocation RParenLoc) {
2460 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2461 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2462 Diag(LParenLoc, diag::ext_c99_compound_literal);
2463 ExprResult Result = ParseInitializer();
2464 if (!Result.isInvalid() && Ty)
2465 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2469 /// ParseStringLiteralExpression - This handles the various token types that
2470 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2471 /// translation phase #6].
2474 /// primary-expression: [C99 6.5.1]
2477 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2478 assert(isTokenStringLiteral() && "Not a string literal!");
2480 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2481 // considered to be strings for concatenation purposes.
2482 SmallVector<Token, 4> StringToks;
2485 StringToks.push_back(Tok);
2486 ConsumeStringToken();
2487 } while (isTokenStringLiteral());
2489 // Pass the set of string tokens, ready for concatenation, to the actions.
2490 return Actions.ActOnStringLiteral(StringToks,
2491 AllowUserDefinedLiteral ? getCurScope()
2495 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2499 /// generic-selection:
2500 /// _Generic ( assignment-expression , generic-assoc-list )
2501 /// generic-assoc-list:
2502 /// generic-association
2503 /// generic-assoc-list , generic-association
2504 /// generic-association:
2505 /// type-name : assignment-expression
2506 /// default : assignment-expression
2508 ExprResult Parser::ParseGenericSelectionExpression() {
2509 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2510 SourceLocation KeyLoc = ConsumeToken();
2512 if (!getLangOpts().C11)
2513 Diag(KeyLoc, diag::ext_c11_generic_selection);
2515 BalancedDelimiterTracker T(*this, tok::l_paren);
2516 if (T.expectAndConsume())
2519 ExprResult ControllingExpr;
2521 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2523 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2525 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2526 if (ControllingExpr.isInvalid()) {
2527 SkipUntil(tok::r_paren, StopAtSemi);
2532 if (ExpectAndConsume(tok::comma)) {
2533 SkipUntil(tok::r_paren, StopAtSemi);
2537 SourceLocation DefaultLoc;
2542 if (Tok.is(tok::kw_default)) {
2543 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2544 // generic association."
2545 if (!DefaultLoc.isInvalid()) {
2546 Diag(Tok, diag::err_duplicate_default_assoc);
2547 Diag(DefaultLoc, diag::note_previous_default_assoc);
2548 SkipUntil(tok::r_paren, StopAtSemi);
2551 DefaultLoc = ConsumeToken();
2554 ColonProtectionRAIIObject X(*this);
2555 TypeResult TR = ParseTypeName();
2556 if (TR.isInvalid()) {
2557 SkipUntil(tok::r_paren, StopAtSemi);
2562 Types.push_back(Ty);
2564 if (ExpectAndConsume(tok::colon)) {
2565 SkipUntil(tok::r_paren, StopAtSemi);
2569 // FIXME: These expressions should be parsed in a potentially potentially
2570 // evaluated context.
2572 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2573 if (ER.isInvalid()) {
2574 SkipUntil(tok::r_paren, StopAtSemi);
2577 Exprs.push_back(ER.get());
2578 } while (TryConsumeToken(tok::comma));
2581 if (T.getCloseLocation().isInvalid())
2584 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2585 T.getCloseLocation(),
2586 ControllingExpr.get(),
2590 /// \brief Parse A C++1z fold-expression after the opening paren and optional
2591 /// left-hand-side expression.
2594 /// fold-expression:
2595 /// ( cast-expression fold-operator ... )
2596 /// ( ... fold-operator cast-expression )
2597 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2598 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2599 BalancedDelimiterTracker &T) {
2600 if (LHS.isInvalid()) {
2605 tok::TokenKind Kind = tok::unknown;
2606 SourceLocation FirstOpLoc;
2607 if (LHS.isUsable()) {
2608 Kind = Tok.getKind();
2609 assert(isFoldOperator(Kind) && "missing fold-operator");
2610 FirstOpLoc = ConsumeToken();
2613 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2614 SourceLocation EllipsisLoc = ConsumeToken();
2617 if (Tok.isNot(tok::r_paren)) {
2618 if (!isFoldOperator(Tok.getKind()))
2619 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2621 if (Kind != tok::unknown && Tok.getKind() != Kind)
2622 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2623 << SourceRange(FirstOpLoc);
2624 Kind = Tok.getKind();
2627 RHS = ParseExpression();
2628 if (RHS.isInvalid()) {
2634 Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
2635 ? diag::warn_cxx14_compat_fold_expression
2636 : diag::ext_fold_expression);
2639 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2640 EllipsisLoc, RHS.get(), T.getCloseLocation());
2643 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2646 /// argument-expression-list:
2647 /// assignment-expression
2648 /// argument-expression-list , assignment-expression
2650 /// [C++] expression-list:
2651 /// [C++] assignment-expression
2652 /// [C++] expression-list , assignment-expression
2654 /// [C++0x] expression-list:
2655 /// [C++0x] initializer-list
2657 /// [C++0x] initializer-list
2658 /// [C++0x] initializer-clause ...[opt]
2659 /// [C++0x] initializer-list , initializer-clause ...[opt]
2661 /// [C++0x] initializer-clause:
2662 /// [C++0x] assignment-expression
2663 /// [C++0x] braced-init-list
2665 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2666 SmallVectorImpl<SourceLocation> &CommaLocs,
2667 std::function<void()> Completer) {
2668 bool SawError = false;
2670 if (Tok.is(tok::code_completion)) {
2674 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2680 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2681 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2682 Expr = ParseBraceInitializer();
2684 Expr = ParseAssignmentExpression();
2686 if (Tok.is(tok::ellipsis))
2687 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2688 if (Expr.isInvalid()) {
2689 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2692 Exprs.push_back(Expr.get());
2695 if (Tok.isNot(tok::comma))
2697 // Move to the next argument, remember where the comma was.
2698 CommaLocs.push_back(ConsumeToken());
2701 // Ensure typos get diagnosed when errors were encountered while parsing the
2703 for (auto &E : Exprs) {
2704 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2705 if (Expr.isUsable()) E = Expr.get();
2711 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2712 /// used for misc language extensions.
2715 /// simple-expression-list:
2716 /// assignment-expression
2717 /// simple-expression-list , assignment-expression
2720 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2721 SmallVectorImpl<SourceLocation> &CommaLocs) {
2723 ExprResult Expr = ParseAssignmentExpression();
2724 if (Expr.isInvalid())
2727 Exprs.push_back(Expr.get());
2729 if (Tok.isNot(tok::comma))
2732 // Move to the next argument, remember where the comma was.
2733 CommaLocs.push_back(ConsumeToken());
2737 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2740 /// [clang] block-id:
2741 /// [clang] specifier-qualifier-list block-declarator
2743 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2744 if (Tok.is(tok::code_completion)) {
2745 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2746 return cutOffParsing();
2749 // Parse the specifier-qualifier-list piece.
2750 DeclSpec DS(AttrFactory);
2751 ParseSpecifierQualifierList(DS);
2753 // Parse the block-declarator.
2754 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2755 DeclaratorInfo.setFunctionDefinitionKind(FDK_Definition);
2756 ParseDeclarator(DeclaratorInfo);
2758 MaybeParseGNUAttributes(DeclaratorInfo);
2760 // Inform sema that we are starting a block.
2761 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2764 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2765 /// like ^(int x){ return x+1; }
2769 /// [clang] '^' block-args[opt] compound-statement
2770 /// [clang] '^' block-id compound-statement
2771 /// [clang] block-args:
2772 /// [clang] '(' parameter-list ')'
2774 ExprResult Parser::ParseBlockLiteralExpression() {
2775 assert(Tok.is(tok::caret) && "block literal starts with ^");
2776 SourceLocation CaretLoc = ConsumeToken();
2778 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2779 "block literal parsing");
2781 // Enter a scope to hold everything within the block. This includes the
2782 // argument decls, decls within the compound expression, etc. This also
2783 // allows determining whether a variable reference inside the block is
2784 // within or outside of the block.
2785 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2788 // Inform sema that we are starting a block.
2789 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2791 // Parse the return type if present.
2792 DeclSpec DS(AttrFactory);
2793 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2794 ParamInfo.setFunctionDefinitionKind(FDK_Definition);
2795 // FIXME: Since the return type isn't actually parsed, it can't be used to
2796 // fill ParamInfo with an initial valid range, so do it manually.
2797 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2799 // If this block has arguments, parse them. There is no ambiguity here with
2800 // the expression case, because the expression case requires a parameter list.
2801 if (Tok.is(tok::l_paren)) {
2802 ParseParenDeclarator(ParamInfo);
2803 // Parse the pieces after the identifier as if we had "int(...)".
2804 // SetIdentifier sets the source range end, but in this case we're past
2806 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2807 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2808 ParamInfo.SetRangeEnd(Tmp);
2809 if (ParamInfo.isInvalidType()) {
2810 // If there was an error parsing the arguments, they may have
2811 // tried to use ^(x+y) which requires an argument list. Just
2812 // skip the whole block literal.
2813 Actions.ActOnBlockError(CaretLoc, getCurScope());
2817 MaybeParseGNUAttributes(ParamInfo);
2819 // Inform sema that we are starting a block.
2820 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2821 } else if (!Tok.is(tok::l_brace)) {
2822 ParseBlockId(CaretLoc);
2824 // Otherwise, pretend we saw (void).
2825 ParsedAttributes attrs(AttrFactory);
2826 SourceLocation NoLoc;
2827 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2828 /*IsAmbiguous=*/false,
2829 /*RParenLoc=*/NoLoc,
2830 /*ArgInfo=*/nullptr,
2832 /*EllipsisLoc=*/NoLoc,
2833 /*RParenLoc=*/NoLoc,
2835 /*RefQualifierIsLvalueRef=*/true,
2836 /*RefQualifierLoc=*/NoLoc,
2837 /*ConstQualifierLoc=*/NoLoc,
2838 /*VolatileQualifierLoc=*/NoLoc,
2839 /*RestrictQualifierLoc=*/NoLoc,
2840 /*MutableLoc=*/NoLoc,
2842 /*ESpecRange=*/SourceRange(),
2843 /*Exceptions=*/nullptr,
2844 /*ExceptionRanges=*/nullptr,
2845 /*NumExceptions=*/0,
2846 /*NoexceptExpr=*/nullptr,
2847 /*ExceptionSpecTokens=*/nullptr,
2848 /*DeclsInPrototype=*/None,
2853 MaybeParseGNUAttributes(ParamInfo);
2855 // Inform sema that we are starting a block.
2856 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2860 ExprResult Result(true);
2861 if (!Tok.is(tok::l_brace)) {
2862 // Saw something like: ^expr
2863 Diag(Tok, diag::err_expected_expression);
2864 Actions.ActOnBlockError(CaretLoc, getCurScope());
2868 StmtResult Stmt(ParseCompoundStatementBody());
2870 if (!Stmt.isInvalid())
2871 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2873 Actions.ActOnBlockError(CaretLoc, getCurScope());
2877 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2881 ExprResult Parser::ParseObjCBoolLiteral() {
2882 tok::TokenKind Kind = Tok.getKind();
2883 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
2886 /// Validate availability spec list, emitting diagnostics if necessary. Returns
2887 /// true if invalid.
2888 static bool CheckAvailabilitySpecList(Parser &P,
2889 ArrayRef<AvailabilitySpec> AvailSpecs) {
2890 llvm::SmallSet<StringRef, 4> Platforms;
2891 bool HasOtherPlatformSpec = false;
2893 for (const auto &Spec : AvailSpecs) {
2894 if (Spec.isOtherPlatformSpec()) {
2895 if (HasOtherPlatformSpec) {
2896 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
2900 HasOtherPlatformSpec = true;
2904 bool Inserted = Platforms.insert(Spec.getPlatform()).second;
2906 // Rule out multiple version specs referring to the same platform.
2907 // For example, we emit an error for:
2908 // @available(macos 10.10, macos 10.11, *)
2909 StringRef Platform = Spec.getPlatform();
2910 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
2911 << Spec.getEndLoc() << Platform;
2916 if (!HasOtherPlatformSpec) {
2917 SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
2918 P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
2919 << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
2926 /// Parse availability query specification.
2928 /// availability-spec:
2930 /// identifier version-tuple
2931 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
2932 if (Tok.is(tok::star)) {
2933 return AvailabilitySpec(ConsumeToken());
2935 // Parse the platform name.
2936 if (Tok.isNot(tok::identifier)) {
2937 Diag(Tok, diag::err_avail_query_expected_platform_name);
2941 IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
2942 SourceRange VersionRange;
2943 VersionTuple Version = ParseVersionTuple(VersionRange);
2945 if (Version.empty())
2948 StringRef Platform = PlatformIdentifier->Ident->getName();
2950 if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
2951 Diag(PlatformIdentifier->Loc,
2952 diag::err_avail_query_unrecognized_platform_name)
2957 return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
2958 VersionRange.getEnd());
2962 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
2963 assert(Tok.is(tok::kw___builtin_available) ||
2964 Tok.isObjCAtKeyword(tok::objc_available));
2966 // Eat the available or __builtin_available.
2969 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2970 if (Parens.expectAndConsume())
2973 SmallVector<AvailabilitySpec, 4> AvailSpecs;
2974 bool HasError = false;
2976 Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
2980 AvailSpecs.push_back(*Spec);
2982 if (!TryConsumeToken(tok::comma))
2987 SkipUntil(tok::r_paren, StopAtSemi);
2991 CheckAvailabilitySpecList(*this, AvailSpecs);
2993 if (Parens.consumeClose())
2996 return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
2997 Parens.getCloseLocation());