1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Provides the Expression parsing implementation.
13 /// Expressions in C99 basically consist of a bunch of binary operators with
14 /// unary operators and other random stuff at the leaves.
16 /// In the C99 grammar, these unary operators bind tightest and are represented
17 /// as the 'cast-expression' production. Everything else is either a binary
18 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
19 /// handled by ParseCastExpression, the higher level pieces are handled by
20 /// ParseBinaryExpression.
22 //===----------------------------------------------------------------------===//
24 #include "clang/Parse/Parser.h"
25 #include "RAIIObjectsForParser.h"
26 #include "clang/AST/ASTContext.h"
27 #include "clang/Basic/PrettyStackTrace.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/ParsedTemplate.h"
30 #include "clang/Sema/Scope.h"
31 #include "clang/Sema/TypoCorrection.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/SmallVector.h"
34 using namespace clang;
36 /// \brief Simple precedence-based parser for binary/ternary operators.
38 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
39 /// production. C99 specifies that the LHS of an assignment operator should be
40 /// parsed as a unary-expression, but consistency dictates that it be a
41 /// conditional-expession. In practice, the important thing here is that the
42 /// LHS of an assignment has to be an l-value, which productions between
43 /// unary-expression and conditional-expression don't produce. Because we want
44 /// consistency, we parse the LHS as a conditional-expression, then check for
45 /// l-value-ness in semantic analysis stages.
48 /// pm-expression: [C++ 5.5]
50 /// pm-expression '.*' cast-expression
51 /// pm-expression '->*' cast-expression
53 /// multiplicative-expression: [C99 6.5.5]
54 /// Note: in C++, apply pm-expression instead of cast-expression
56 /// multiplicative-expression '*' cast-expression
57 /// multiplicative-expression '/' cast-expression
58 /// multiplicative-expression '%' cast-expression
60 /// additive-expression: [C99 6.5.6]
61 /// multiplicative-expression
62 /// additive-expression '+' multiplicative-expression
63 /// additive-expression '-' multiplicative-expression
65 /// shift-expression: [C99 6.5.7]
66 /// additive-expression
67 /// shift-expression '<<' additive-expression
68 /// shift-expression '>>' additive-expression
70 /// relational-expression: [C99 6.5.8]
72 /// relational-expression '<' shift-expression
73 /// relational-expression '>' shift-expression
74 /// relational-expression '<=' shift-expression
75 /// relational-expression '>=' shift-expression
77 /// equality-expression: [C99 6.5.9]
78 /// relational-expression
79 /// equality-expression '==' relational-expression
80 /// equality-expression '!=' relational-expression
82 /// AND-expression: [C99 6.5.10]
83 /// equality-expression
84 /// AND-expression '&' equality-expression
86 /// exclusive-OR-expression: [C99 6.5.11]
88 /// exclusive-OR-expression '^' AND-expression
90 /// inclusive-OR-expression: [C99 6.5.12]
91 /// exclusive-OR-expression
92 /// inclusive-OR-expression '|' exclusive-OR-expression
94 /// logical-AND-expression: [C99 6.5.13]
95 /// inclusive-OR-expression
96 /// logical-AND-expression '&&' inclusive-OR-expression
98 /// logical-OR-expression: [C99 6.5.14]
99 /// logical-AND-expression
100 /// logical-OR-expression '||' logical-AND-expression
102 /// conditional-expression: [C99 6.5.15]
103 /// logical-OR-expression
104 /// logical-OR-expression '?' expression ':' conditional-expression
105 /// [GNU] logical-OR-expression '?' ':' conditional-expression
106 /// [C++] the third operand is an assignment-expression
108 /// assignment-expression: [C99 6.5.16]
109 /// conditional-expression
110 /// unary-expression assignment-operator assignment-expression
111 /// [C++] throw-expression [C++ 15]
113 /// assignment-operator: one of
114 /// = *= /= %= += -= <<= >>= &= ^= |=
116 /// expression: [C99 6.5.17]
117 /// assignment-expression ...[opt]
118 /// expression ',' assignment-expression ...[opt]
120 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
121 ExprResult LHS(ParseAssignmentExpression(isTypeCast));
122 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
125 /// This routine is called when the '@' is seen and consumed.
126 /// Current token is an Identifier and is not a 'try'. This
127 /// routine is necessary to disambiguate \@try-statement from,
128 /// for example, \@encode-expression.
131 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
132 ExprResult LHS(ParseObjCAtExpression(AtLoc));
133 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
136 /// This routine is called when a leading '__extension__' is seen and
137 /// consumed. This is necessary because the token gets consumed in the
138 /// process of disambiguating between an expression and a declaration.
140 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
141 ExprResult LHS(true);
143 // Silence extension warnings in the sub-expression
144 ExtensionRAIIObject O(Diags);
146 LHS = ParseCastExpression(false);
149 if (!LHS.isInvalid())
150 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
153 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
156 /// \brief Parse an expr that doesn't include (top-level) commas.
157 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
158 if (Tok.is(tok::code_completion)) {
159 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
164 if (Tok.is(tok::kw_throw))
165 return ParseThrowExpression();
166 if (Tok.is(tok::kw_co_yield))
167 return ParseCoyieldExpression();
169 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
170 /*isAddressOfOperand=*/false,
172 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
175 /// \brief Parse an assignment expression where part of an Objective-C message
176 /// send has already been parsed.
178 /// In this case \p LBracLoc indicates the location of the '[' of the message
179 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
180 /// the receiver of the message.
182 /// Since this handles full assignment-expression's, it handles postfix
183 /// expressions and other binary operators for these expressions as well.
185 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
186 SourceLocation SuperLoc,
187 ParsedType ReceiverType,
188 Expr *ReceiverExpr) {
190 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
191 ReceiverType, ReceiverExpr);
192 R = ParsePostfixExpressionSuffix(R);
193 return ParseRHSOfBinaryExpression(R, prec::Assignment);
197 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
198 // C++03 [basic.def.odr]p2:
199 // An expression is potentially evaluated unless it appears where an
200 // integral constant expression is required (see 5.19) [...].
201 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
202 EnterExpressionEvaluationContext Unevaluated(Actions,
203 Sema::ConstantEvaluated);
205 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
206 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
207 return Actions.ActOnConstantExpression(Res);
210 /// \brief Parse a constraint-expression.
213 /// constraint-expression: [Concepts TS temp.constr.decl p1]
214 /// logical-or-expression
216 ExprResult Parser::ParseConstraintExpression() {
217 // FIXME: this may erroneously consume a function-body as the braced
218 // initializer list of a compound literal
220 // FIXME: this may erroneously consume a parenthesized rvalue reference
221 // declarator as a parenthesized address-of-label expression
222 ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
223 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
228 bool Parser::isNotExpressionStart() {
229 tok::TokenKind K = Tok.getKind();
230 if (K == tok::l_brace || K == tok::r_brace ||
231 K == tok::kw_for || K == tok::kw_while ||
232 K == tok::kw_if || K == tok::kw_else ||
233 K == tok::kw_goto || K == tok::kw_try)
235 // If this is a decl-specifier, we can't be at the start of an expression.
236 return isKnownToBeDeclarationSpecifier();
239 static bool isFoldOperator(prec::Level Level) {
240 return Level > prec::Unknown && Level != prec::Conditional;
242 static bool isFoldOperator(tok::TokenKind Kind) {
243 return isFoldOperator(getBinOpPrecedence(Kind, false, true));
246 /// \brief Parse a binary expression that starts with \p LHS and has a
247 /// precedence of at least \p MinPrec.
249 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
250 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
251 GreaterThanIsOperator,
252 getLangOpts().CPlusPlus11);
253 SourceLocation ColonLoc;
256 // If this token has a lower precedence than we are allowed to parse (e.g.
257 // because we are called recursively, or because the token is not a binop),
259 if (NextTokPrec < MinPrec)
262 // Consume the operator, saving the operator token for error reporting.
266 if (OpToken.is(tok::caretcaret)) {
267 return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
269 // Bail out when encountering a comma followed by a token which can't
270 // possibly be the start of an expression. For instance:
271 // int f() { return 1, }
272 // We can't do this before consuming the comma, because
273 // isNotExpressionStart() looks at the token stream.
274 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
280 // If the next token is an ellipsis, then this is a fold-expression. Leave
281 // it alone so we can handle it in the paren expression.
282 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
283 // FIXME: We can't check this via lookahead before we consume the token
284 // because that tickles a lexer bug.
290 // Special case handling for the ternary operator.
291 ExprResult TernaryMiddle(true);
292 if (NextTokPrec == prec::Conditional) {
293 if (Tok.isNot(tok::colon)) {
294 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
295 ColonProtectionRAIIObject X(*this);
297 // Handle this production specially:
298 // logical-OR-expression '?' expression ':' conditional-expression
299 // In particular, the RHS of the '?' is 'expression', not
300 // 'logical-OR-expression' as we might expect.
301 TernaryMiddle = ParseExpression();
302 if (TernaryMiddle.isInvalid()) {
303 Actions.CorrectDelayedTyposInExpr(LHS);
305 TernaryMiddle = nullptr;
308 // Special case handling of "X ? Y : Z" where Y is empty:
309 // logical-OR-expression '?' ':' conditional-expression [GNU]
310 TernaryMiddle = nullptr;
311 Diag(Tok, diag::ext_gnu_conditional_expr);
314 if (!TryConsumeToken(tok::colon, ColonLoc)) {
315 // Otherwise, we're missing a ':'. Assume that this was a typo that
316 // the user forgot. If we're not in a macro expansion, we can suggest
317 // a fixit hint. If there were two spaces before the current token,
318 // suggest inserting the colon in between them, otherwise insert ": ".
319 SourceLocation FILoc = Tok.getLocation();
320 const char *FIText = ": ";
321 const SourceManager &SM = PP.getSourceManager();
322 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
323 assert(FILoc.isFileID());
324 bool IsInvalid = false;
325 const char *SourcePtr =
326 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
327 if (!IsInvalid && *SourcePtr == ' ') {
329 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
330 if (!IsInvalid && *SourcePtr == ' ') {
331 FILoc = FILoc.getLocWithOffset(-1);
337 Diag(Tok, diag::err_expected)
338 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
339 Diag(OpToken, diag::note_matching) << tok::question;
340 ColonLoc = Tok.getLocation();
344 // Code completion for the right-hand side of an assignment expression
345 // goes through a special hook that takes the left-hand side into account.
346 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
347 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
352 // Parse another leaf here for the RHS of the operator.
353 // ParseCastExpression works here because all RHS expressions in C have it
354 // as a prefix, at least. However, in C++, an assignment-expression could
355 // be a throw-expression, which is not a valid cast-expression.
356 // Therefore we need some special-casing here.
357 // Also note that the third operand of the conditional operator is
358 // an assignment-expression in C++, and in C++11, we can have a
359 // braced-init-list on the RHS of an assignment. For better diagnostics,
360 // parse as if we were allowed braced-init-lists everywhere, and check that
361 // they only appear on the RHS of assignments later.
363 bool RHSIsInitList = false;
364 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
365 RHS = ParseBraceInitializer();
366 RHSIsInitList = true;
367 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
368 RHS = ParseAssignmentExpression();
370 RHS = ParseCastExpression(false);
372 if (RHS.isInvalid()) {
373 // FIXME: Errors generated by the delayed typo correction should be
374 // printed before errors from parsing the RHS, not after.
375 Actions.CorrectDelayedTyposInExpr(LHS);
376 if (TernaryMiddle.isUsable())
377 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
381 // Remember the precedence of this operator and get the precedence of the
382 // operator immediately to the right of the RHS.
383 prec::Level ThisPrec = NextTokPrec;
384 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
385 getLangOpts().CPlusPlus11);
387 // Assignment and conditional expressions are right-associative.
388 bool isRightAssoc = ThisPrec == prec::Conditional ||
389 ThisPrec == prec::Assignment;
391 // Get the precedence of the operator to the right of the RHS. If it binds
392 // more tightly with RHS than we do, evaluate it completely first.
393 if (ThisPrec < NextTokPrec ||
394 (ThisPrec == NextTokPrec && isRightAssoc)) {
395 if (!RHS.isInvalid() && RHSIsInitList) {
396 Diag(Tok, diag::err_init_list_bin_op)
397 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
400 // If this is left-associative, only parse things on the RHS that bind
401 // more tightly than the current operator. If it is left-associative, it
402 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
403 // A=(B=(C=D)), where each paren is a level of recursion here.
404 // The function takes ownership of the RHS.
405 RHS = ParseRHSOfBinaryExpression(RHS,
406 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
407 RHSIsInitList = false;
409 if (RHS.isInvalid()) {
410 // FIXME: Errors generated by the delayed typo correction should be
411 // printed before errors from ParseRHSOfBinaryExpression, not after.
412 Actions.CorrectDelayedTyposInExpr(LHS);
413 if (TernaryMiddle.isUsable())
414 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
418 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
419 getLangOpts().CPlusPlus11);
422 if (!RHS.isInvalid() && RHSIsInitList) {
423 if (ThisPrec == prec::Assignment) {
424 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
425 << Actions.getExprRange(RHS.get());
427 Diag(OpToken, diag::err_init_list_bin_op)
428 << /*RHS*/1 << PP.getSpelling(OpToken)
429 << Actions.getExprRange(RHS.get());
434 ExprResult OrigLHS = LHS;
435 if (!LHS.isInvalid()) {
436 // Combine the LHS and RHS into the LHS (e.g. build AST).
437 if (TernaryMiddle.isInvalid()) {
438 // If we're using '>>' as an operator within a template
439 // argument list (in C++98), suggest the addition of
440 // parentheses so that the code remains well-formed in C++0x.
441 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
442 SuggestParentheses(OpToken.getLocation(),
443 diag::warn_cxx11_right_shift_in_template_arg,
444 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
445 Actions.getExprRange(RHS.get()).getEnd()));
447 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
448 OpToken.getKind(), LHS.get(), RHS.get());
450 // In this case, ActOnBinOp performed the CorrectDelayedTyposInExpr check.
451 if (!getLangOpts().CPlusPlus)
454 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
455 LHS.get(), TernaryMiddle.get(),
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 // Allow either an identifier or the keyword 'class' (in C++).
890 if (Tok.isNot(tok::identifier) &&
891 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
892 Diag(Tok, diag::err_expected_property_name);
895 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
896 SourceLocation PropertyLoc = ConsumeToken();
898 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
903 // In an Objective-C method, if we have "super" followed by an identifier,
904 // the token sequence is ill-formed. However, if there's a ':' or ']' after
905 // that identifier, this is probably a message send with a missing open
906 // bracket. Treat it as such.
907 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
908 getCurScope()->isInObjcMethodScope() &&
909 ((Tok.is(tok::identifier) &&
910 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
911 Tok.is(tok::code_completion))) {
912 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
917 // If we have an Objective-C class name followed by an identifier
918 // and either ':' or ']', this is an Objective-C class message
919 // send that's missing the opening '['. Recovery
920 // appropriately. Also take this path if we're performing code
921 // completion after an Objective-C class name.
922 if (getLangOpts().ObjC1 &&
923 ((Tok.is(tok::identifier) && !InMessageExpression) ||
924 Tok.is(tok::code_completion))) {
925 const Token& Next = NextToken();
926 if (Tok.is(tok::code_completion) ||
927 Next.is(tok::colon) || Next.is(tok::r_square))
928 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
929 if (Typ.get()->isObjCObjectOrInterfaceType()) {
930 // Fake up a Declarator to use with ActOnTypeName.
931 DeclSpec DS(AttrFactory);
932 DS.SetRangeStart(ILoc);
933 DS.SetRangeEnd(ILoc);
934 const char *PrevSpec = nullptr;
936 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
937 Actions.getASTContext().getPrintingPolicy());
939 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
940 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
945 Res = ParseObjCMessageExpressionBody(SourceLocation(),
952 // Make sure to pass down the right value for isAddressOfOperand.
953 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
954 isAddressOfOperand = false;
956 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
957 // need to know whether or not this identifier is a function designator or
960 CXXScopeSpec ScopeSpec;
961 SourceLocation TemplateKWLoc;
963 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
964 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
965 Validator->IsAddressOfOperand = isAddressOfOperand;
966 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
967 Validator->WantExpressionKeywords = false;
968 Validator->WantRemainingKeywords = false;
970 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
972 Name.setIdentifier(&II, ILoc);
973 Res = Actions.ActOnIdExpression(
974 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
975 isAddressOfOperand, std::move(Validator),
976 /*IsInlineAsmIdentifier=*/false,
977 Tok.is(tok::r_paren) ? nullptr : &Replacement);
978 if (!Res.isInvalid() && !Res.get()) {
979 UnconsumeToken(Replacement);
980 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
981 NotCastExpr, isTypeCast);
985 case tok::char_constant: // constant: character-constant
986 case tok::wide_char_constant:
987 case tok::utf8_char_constant:
988 case tok::utf16_char_constant:
989 case tok::utf32_char_constant:
990 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
993 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
994 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
995 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
996 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
997 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
998 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
999 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1002 case tok::string_literal: // primary-expression: string-literal
1003 case tok::wide_string_literal:
1004 case tok::utf8_string_literal:
1005 case tok::utf16_string_literal:
1006 case tok::utf32_string_literal:
1007 Res = ParseStringLiteralExpression(true);
1009 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1010 Res = ParseGenericSelectionExpression();
1012 case tok::kw___builtin_available:
1013 return ParseAvailabilityCheckExpr(Tok.getLocation());
1014 case tok::kw___builtin_va_arg:
1015 case tok::kw___builtin_offsetof:
1016 case tok::kw___builtin_choose_expr:
1017 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1018 case tok::kw___builtin_convertvector:
1019 return ParseBuiltinPrimaryExpression();
1020 case tok::kw___null:
1021 return Actions.ActOnGNUNullExpr(ConsumeToken());
1023 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1024 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1025 // C++ [expr.unary] has:
1026 // unary-expression:
1027 // ++ cast-expression
1028 // -- cast-expression
1029 Token SavedTok = Tok;
1031 // One special case is implicitly handled here: if the preceding tokens are
1032 // an ambiguous cast expression, such as "(T())++", then we recurse to
1033 // determine whether the '++' is prefix or postfix.
1034 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1035 /*isAddressOfOperand*/false, NotCastExpr,
1038 // If we return with NotCastExpr = true, we must not consume any tokens,
1039 // so put the token back where we found it.
1040 assert(Res.isInvalid());
1041 UnconsumeToken(SavedTok);
1044 if (!Res.isInvalid())
1045 Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1046 SavedKind, Res.get());
1049 case tok::amp: { // unary-expression: '&' cast-expression
1050 // Special treatment because of member pointers
1051 SourceLocation SavedLoc = ConsumeToken();
1052 Res = ParseCastExpression(false, true);
1053 if (!Res.isInvalid())
1054 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1058 case tok::star: // unary-expression: '*' cast-expression
1059 case tok::plus: // unary-expression: '+' cast-expression
1060 case tok::minus: // unary-expression: '-' cast-expression
1061 case tok::tilde: // unary-expression: '~' cast-expression
1062 case tok::exclaim: // unary-expression: '!' cast-expression
1063 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1064 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1065 SourceLocation SavedLoc = ConsumeToken();
1066 Res = ParseCastExpression(false);
1067 if (!Res.isInvalid())
1068 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1072 case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1073 SourceLocation CoawaitLoc = ConsumeToken();
1074 Res = ParseCastExpression(false);
1075 if (!Res.isInvalid())
1076 Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1080 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1081 // __extension__ silences extension warnings in the subexpression.
1082 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1083 SourceLocation SavedLoc = ConsumeToken();
1084 Res = ParseCastExpression(false);
1085 if (!Res.isInvalid())
1086 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1089 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1090 if (!getLangOpts().C11)
1091 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1093 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1094 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1095 // unary-expression: '__alignof' '(' type-name ')'
1096 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1097 // unary-expression: 'sizeof' '(' type-name ')'
1098 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1099 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1100 case tok::kw___builtin_omp_required_simd_align:
1101 return ParseUnaryExprOrTypeTraitExpression();
1102 case tok::ampamp: { // unary-expression: '&&' identifier
1103 SourceLocation AmpAmpLoc = ConsumeToken();
1104 if (Tok.isNot(tok::identifier))
1105 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1107 if (getCurScope()->getFnParent() == nullptr)
1108 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1110 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1111 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1113 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1117 case tok::kw_const_cast:
1118 case tok::kw_dynamic_cast:
1119 case tok::kw_reinterpret_cast:
1120 case tok::kw_static_cast:
1121 Res = ParseCXXCasts();
1123 case tok::kw_typeid:
1124 Res = ParseCXXTypeid();
1126 case tok::kw___uuidof:
1127 Res = ParseCXXUuidof();
1130 Res = ParseCXXThis();
1133 case tok::annot_typename:
1134 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1135 ParsedType Type = getTypeAnnotation(Tok);
1137 // Fake up a Declarator to use with ActOnTypeName.
1138 DeclSpec DS(AttrFactory);
1139 DS.SetRangeStart(Tok.getLocation());
1140 DS.SetRangeEnd(Tok.getLastLoc());
1142 const char *PrevSpec = nullptr;
1144 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1145 PrevSpec, DiagID, Type,
1146 Actions.getASTContext().getPrintingPolicy());
1148 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1149 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1154 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1160 case tok::annot_decltype:
1162 case tok::kw_wchar_t:
1163 case tok::kw_char16_t:
1164 case tok::kw_char32_t:
1169 case tok::kw___int64:
1170 case tok::kw___int128:
1171 case tok::kw_signed:
1172 case tok::kw_unsigned:
1175 case tok::kw_double:
1176 case tok::kw___float128:
1178 case tok::kw_typename:
1179 case tok::kw_typeof:
1180 case tok::kw___vector:
1181 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1182 #include "clang/Basic/OpenCLImageTypes.def"
1184 if (!getLangOpts().CPlusPlus) {
1185 Diag(Tok, diag::err_expected_expression);
1189 if (SavedKind == tok::kw_typename) {
1190 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1191 // typename-specifier braced-init-list
1192 if (TryAnnotateTypeOrScopeToken())
1195 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1196 // We are trying to parse a simple-type-specifier but might not get such
1197 // a token after error recovery.
1201 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1202 // simple-type-specifier braced-init-list
1204 DeclSpec DS(AttrFactory);
1206 ParseCXXSimpleTypeSpecifier(DS);
1207 if (Tok.isNot(tok::l_paren) &&
1208 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1209 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1210 << DS.getSourceRange());
1212 if (Tok.is(tok::l_brace))
1213 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1215 Res = ParseCXXTypeConstructExpression(DS);
1219 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1220 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1221 // (We can end up in this situation after tentative parsing.)
1222 if (TryAnnotateTypeOrScopeToken())
1224 if (!Tok.is(tok::annot_cxxscope))
1225 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1226 NotCastExpr, isTypeCast);
1228 Token Next = NextToken();
1229 if (Next.is(tok::annot_template_id)) {
1230 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1231 if (TemplateId->Kind == TNK_Type_template) {
1232 // We have a qualified template-id that we know refers to a
1233 // type, translate it into a type and continue parsing as a
1236 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1237 /*EnteringContext=*/false);
1238 AnnotateTemplateIdTokenAsType();
1239 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1240 NotCastExpr, isTypeCast);
1244 // Parse as an id-expression.
1245 Res = ParseCXXIdExpression(isAddressOfOperand);
1249 case tok::annot_template_id: { // [C++] template-id
1250 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1251 if (TemplateId->Kind == TNK_Type_template) {
1252 // We have a template-id that we know refers to a type,
1253 // translate it into a type and continue parsing as a cast
1255 AnnotateTemplateIdTokenAsType();
1256 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1257 NotCastExpr, isTypeCast);
1260 // Fall through to treat the template-id as an id-expression.
1263 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1264 Res = ParseCXXIdExpression(isAddressOfOperand);
1267 case tok::coloncolon: {
1268 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1269 // annotates the token, tail recurse.
1270 if (TryAnnotateTypeOrScopeToken())
1272 if (!Tok.is(tok::coloncolon))
1273 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1275 // ::new -> [C++] new-expression
1276 // ::delete -> [C++] delete-expression
1277 SourceLocation CCLoc = ConsumeToken();
1278 if (Tok.is(tok::kw_new))
1279 return ParseCXXNewExpression(true, CCLoc);
1280 if (Tok.is(tok::kw_delete))
1281 return ParseCXXDeleteExpression(true, CCLoc);
1283 // This is not a type name or scope specifier, it is an invalid expression.
1284 Diag(CCLoc, diag::err_expected_expression);
1288 case tok::kw_new: // [C++] new-expression
1289 return ParseCXXNewExpression(false, Tok.getLocation());
1291 case tok::kw_delete: // [C++] delete-expression
1292 return ParseCXXDeleteExpression(false, Tok.getLocation());
1294 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1295 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1296 SourceLocation KeyLoc = ConsumeToken();
1297 BalancedDelimiterTracker T(*this, tok::l_paren);
1299 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1301 // C++11 [expr.unary.noexcept]p1:
1302 // The noexcept operator determines whether the evaluation of its operand,
1303 // which is an unevaluated operand, can throw an exception.
1304 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1305 ExprResult Result = ParseExpression();
1309 if (!Result.isInvalid())
1310 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1311 Result.get(), T.getCloseLocation());
1315 #define TYPE_TRAIT(N,Spelling,K) \
1316 case tok::kw_##Spelling:
1317 #include "clang/Basic/TokenKinds.def"
1318 return ParseTypeTrait();
1320 case tok::kw___array_rank:
1321 case tok::kw___array_extent:
1322 return ParseArrayTypeTrait();
1324 case tok::kw___is_lvalue_expr:
1325 case tok::kw___is_rvalue_expr:
1326 return ParseExpressionTrait();
1329 SourceLocation AtLoc = ConsumeToken();
1330 return ParseObjCAtExpression(AtLoc);
1333 Res = ParseBlockLiteralExpression();
1335 case tok::code_completion: {
1336 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1341 if (getLangOpts().CPlusPlus11) {
1342 if (getLangOpts().ObjC1) {
1343 // C++11 lambda expressions and Objective-C message sends both start with a
1344 // square bracket. There are three possibilities here:
1345 // we have a valid lambda expression, we have an invalid lambda
1346 // expression, or we have something that doesn't appear to be a lambda.
1347 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1348 Res = TryParseLambdaExpression();
1349 if (!Res.isInvalid() && !Res.get())
1350 Res = ParseObjCMessageExpression();
1353 Res = ParseLambdaExpression();
1356 if (getLangOpts().ObjC1) {
1357 Res = ParseObjCMessageExpression();
1366 // Check to see whether Res is a function designator only. If it is and we
1367 // are compiling for OpenCL, we need to return an error as this implies
1368 // that the address of the function is being taken, which is illegal in CL.
1370 // These can be followed by postfix-expr pieces.
1371 Res = ParsePostfixExpressionSuffix(Res);
1372 if (getLangOpts().OpenCL)
1373 if (Expr *PostfixExpr = Res.get()) {
1374 QualType Ty = PostfixExpr->getType();
1375 if (!Ty.isNull() && Ty->isFunctionType()) {
1376 Diag(PostfixExpr->getExprLoc(),
1377 diag::err_opencl_taking_function_address_parser);
1385 /// \brief Once the leading part of a postfix-expression is parsed, this
1386 /// method parses any suffixes that apply.
1389 /// postfix-expression: [C99 6.5.2]
1390 /// primary-expression
1391 /// postfix-expression '[' expression ']'
1392 /// postfix-expression '[' braced-init-list ']'
1393 /// postfix-expression '(' argument-expression-list[opt] ')'
1394 /// postfix-expression '.' identifier
1395 /// postfix-expression '->' identifier
1396 /// postfix-expression '++'
1397 /// postfix-expression '--'
1398 /// '(' type-name ')' '{' initializer-list '}'
1399 /// '(' type-name ')' '{' initializer-list ',' '}'
1401 /// argument-expression-list: [C99 6.5.2]
1402 /// argument-expression ...[opt]
1403 /// argument-expression-list ',' assignment-expression ...[opt]
1406 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1407 // Now that the primary-expression piece of the postfix-expression has been
1408 // parsed, see if there are any postfix-expression pieces here.
1411 switch (Tok.getKind()) {
1412 case tok::code_completion:
1413 if (InMessageExpression)
1416 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1420 case tok::identifier:
1421 // If we see identifier: after an expression, and we're not already in a
1422 // message send, then this is probably a message send with a missing
1423 // opening bracket '['.
1424 if (getLangOpts().ObjC1 && !InMessageExpression &&
1425 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1426 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1427 nullptr, LHS.get());
1431 // Fall through; this isn't a message send.
1433 default: // Not a postfix-expression suffix.
1435 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1436 // If we have a array postfix expression that starts on a new line and
1437 // Objective-C is enabled, it is highly likely that the user forgot a
1438 // semicolon after the base expression and that the array postfix-expr is
1439 // actually another message send. In this case, do some look-ahead to see
1440 // if the contents of the square brackets are obviously not a valid
1441 // expression and recover by pretending there is no suffix.
1442 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1443 isSimpleObjCMessageExpression())
1446 // Reject array indices starting with a lambda-expression. '[[' is
1447 // reserved for attributes.
1448 if (CheckProhibitedCXX11Attribute()) {
1449 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1453 BalancedDelimiterTracker T(*this, tok::l_square);
1455 Loc = T.getOpenLocation();
1456 ExprResult Idx, Length;
1457 SourceLocation ColonLoc;
1458 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1459 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1460 Idx = ParseBraceInitializer();
1461 } else if (getLangOpts().OpenMP) {
1462 ColonProtectionRAIIObject RAII(*this);
1463 // Parse [: or [ expr or [ expr :
1464 if (!Tok.is(tok::colon)) {
1466 Idx = ParseExpression();
1468 if (Tok.is(tok::colon)) {
1470 ColonLoc = ConsumeToken();
1471 if (Tok.isNot(tok::r_square))
1472 Length = ParseExpression();
1475 Idx = ParseExpression();
1477 SourceLocation RLoc = Tok.getLocation();
1479 ExprResult OrigLHS = LHS;
1480 if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1481 Tok.is(tok::r_square)) {
1482 if (ColonLoc.isValid()) {
1483 LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1484 ColonLoc, Length.get(), RLoc);
1486 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1492 if (LHS.isInvalid()) {
1493 (void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
1494 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1495 (void)Actions.CorrectDelayedTyposInExpr(Length);
1505 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1506 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1507 // '(' argument-expression-list[opt] ')'
1508 tok::TokenKind OpKind = Tok.getKind();
1509 InMessageExpressionRAIIObject InMessage(*this, false);
1511 Expr *ExecConfig = nullptr;
1513 BalancedDelimiterTracker PT(*this, tok::l_paren);
1515 if (OpKind == tok::lesslessless) {
1516 ExprVector ExecConfigExprs;
1517 CommaLocsTy ExecConfigCommaLocs;
1518 SourceLocation OpenLoc = ConsumeToken();
1520 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1521 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1525 SourceLocation CloseLoc;
1526 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1527 } else if (LHS.isInvalid()) {
1528 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1530 // There was an error closing the brackets
1531 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1532 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1533 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1537 if (!LHS.isInvalid()) {
1538 if (ExpectAndConsume(tok::l_paren))
1541 Loc = PrevTokLocation;
1544 if (!LHS.isInvalid()) {
1545 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1549 if (ECResult.isInvalid())
1552 ExecConfig = ECResult.get();
1556 Loc = PT.getOpenLocation();
1559 ExprVector ArgExprs;
1560 CommaLocsTy CommaLocs;
1562 if (Tok.is(tok::code_completion)) {
1563 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1568 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1569 if (Tok.isNot(tok::r_paren)) {
1570 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1571 Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1573 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1575 } else if (LHS.isInvalid()) {
1576 for (auto &E : ArgExprs)
1577 Actions.CorrectDelayedTyposInExpr(E);
1583 if (LHS.isInvalid()) {
1584 SkipUntil(tok::r_paren, StopAtSemi);
1585 } else if (Tok.isNot(tok::r_paren)) {
1586 bool HadDelayedTypo = false;
1587 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1588 HadDelayedTypo = true;
1589 for (auto &E : ArgExprs)
1590 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1591 HadDelayedTypo = true;
1592 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1593 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1594 // the unmatched l_paren.
1596 SkipUntil(tok::r_paren, StopAtSemi);
1601 assert((ArgExprs.size() == 0 ||
1602 ArgExprs.size()-1 == CommaLocs.size())&&
1603 "Unexpected number of commas!");
1604 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1605 ArgExprs, Tok.getLocation(),
1614 // postfix-expression: p-e '->' template[opt] id-expression
1615 // postfix-expression: p-e '.' template[opt] id-expression
1616 tok::TokenKind OpKind = Tok.getKind();
1617 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1620 ParsedType ObjectType;
1621 bool MayBePseudoDestructor = false;
1622 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1623 Expr *Base = LHS.get();
1624 const Type* BaseType = Base->getType().getTypePtrOrNull();
1625 if (BaseType && Tok.is(tok::l_paren) &&
1626 (BaseType->isFunctionType() ||
1627 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1628 Diag(OpLoc, diag::err_function_is_not_record)
1629 << OpKind << Base->getSourceRange()
1630 << FixItHint::CreateRemoval(OpLoc);
1631 return ParsePostfixExpressionSuffix(Base);
1634 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1635 OpLoc, OpKind, ObjectType,
1636 MayBePseudoDestructor);
1637 if (LHS.isInvalid())
1640 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1641 /*EnteringContext=*/false,
1642 &MayBePseudoDestructor);
1643 if (SS.isNotEmpty())
1644 ObjectType = nullptr;
1647 if (Tok.is(tok::code_completion)) {
1648 // Code completion for a member access expression.
1649 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1650 OpLoc, OpKind == tok::arrow);
1656 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1657 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1662 // Either the action has told us that this cannot be a
1663 // pseudo-destructor expression (based on the type of base
1664 // expression), or we didn't see a '~' in the right place. We
1665 // can still parse a destructor name here, but in that case it
1666 // names a real destructor.
1667 // Allow explicit constructor calls in Microsoft mode.
1668 // FIXME: Add support for explicit call of template constructor.
1669 SourceLocation TemplateKWLoc;
1671 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1672 Tok.is(tok::kw_class)) {
1674 // After a '.' in a member access expression, treat the keyword
1675 // 'class' as if it were an identifier.
1677 // This hack allows property access to the 'class' method because it is
1678 // such a common method name. For other C++ keywords that are
1679 // Objective-C method names, one must use the message send syntax.
1680 IdentifierInfo *Id = Tok.getIdentifierInfo();
1681 SourceLocation Loc = ConsumeToken();
1682 Name.setIdentifier(Id, Loc);
1683 } else if (ParseUnqualifiedId(SS,
1684 /*EnteringContext=*/false,
1685 /*AllowDestructorName=*/true,
1686 /*AllowConstructorName=*/
1687 getLangOpts().MicrosoftExt,
1688 ObjectType, TemplateKWLoc, Name)) {
1689 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1693 if (!LHS.isInvalid())
1694 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1695 OpKind, SS, TemplateKWLoc, Name,
1696 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1700 case tok::plusplus: // postfix-expression: postfix-expression '++'
1701 case tok::minusminus: // postfix-expression: postfix-expression '--'
1702 if (!LHS.isInvalid()) {
1703 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1704 Tok.getKind(), LHS.get());
1712 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1713 /// vec_step and we are at the start of an expression or a parenthesized
1714 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1715 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1718 /// unary-expression: [C99 6.5.3]
1719 /// 'sizeof' unary-expression
1720 /// 'sizeof' '(' type-name ')'
1721 /// [GNU] '__alignof' unary-expression
1722 /// [GNU] '__alignof' '(' type-name ')'
1723 /// [C11] '_Alignof' '(' type-name ')'
1724 /// [C++0x] 'alignof' '(' type-id ')'
1726 /// [GNU] typeof-specifier:
1727 /// typeof ( expressions )
1728 /// typeof ( type-name )
1729 /// [GNU/C++] typeof unary-expression
1731 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1732 /// vec_step ( expressions )
1733 /// vec_step ( type-name )
1736 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1739 SourceRange &CastRange) {
1741 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1742 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1743 tok::kw___builtin_omp_required_simd_align) &&
1744 "Not a typeof/sizeof/alignof/vec_step expression!");
1748 // If the operand doesn't start with an '(', it must be an expression.
1749 if (Tok.isNot(tok::l_paren)) {
1750 // If construct allows a form without parenthesis, user may forget to put
1751 // pathenthesis around type name.
1752 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1753 tok::kw__Alignof)) {
1754 if (isTypeIdUnambiguously()) {
1755 DeclSpec DS(AttrFactory);
1756 ParseSpecifierQualifierList(DS);
1757 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1758 ParseDeclarator(DeclaratorInfo);
1760 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1761 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1762 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1764 << FixItHint::CreateInsertion(LParenLoc, "(")
1765 << FixItHint::CreateInsertion(RParenLoc, ")");
1772 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1773 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1778 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1780 // If it starts with a '(', we know that it is either a parenthesized
1781 // type-name, or it is a unary-expression that starts with a compound
1782 // literal, or starts with a primary-expression that is a parenthesized
1784 ParenParseOption ExprType = CastExpr;
1785 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1787 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1788 false, CastTy, RParenLoc);
1789 CastRange = SourceRange(LParenLoc, RParenLoc);
1791 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1793 if (ExprType == CastExpr) {
1798 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1799 // GNU typeof in C requires the expression to be parenthesized. Not so for
1800 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1801 // the start of a unary-expression, but doesn't include any postfix
1802 // pieces. Parse these now if present.
1803 if (!Operand.isInvalid())
1804 Operand = ParsePostfixExpressionSuffix(Operand.get());
1808 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1814 /// \brief Parse a sizeof or alignof expression.
1817 /// unary-expression: [C99 6.5.3]
1818 /// 'sizeof' unary-expression
1819 /// 'sizeof' '(' type-name ')'
1820 /// [C++11] 'sizeof' '...' '(' identifier ')'
1821 /// [GNU] '__alignof' unary-expression
1822 /// [GNU] '__alignof' '(' type-name ')'
1823 /// [C11] '_Alignof' '(' type-name ')'
1824 /// [C++11] 'alignof' '(' type-id ')'
1826 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1827 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1828 tok::kw__Alignof, tok::kw_vec_step,
1829 tok::kw___builtin_omp_required_simd_align) &&
1830 "Not a sizeof/alignof/vec_step expression!");
1834 // [C++11] 'sizeof' '...' '(' identifier ')'
1835 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1836 SourceLocation EllipsisLoc = ConsumeToken();
1837 SourceLocation LParenLoc, RParenLoc;
1838 IdentifierInfo *Name = nullptr;
1839 SourceLocation NameLoc;
1840 if (Tok.is(tok::l_paren)) {
1841 BalancedDelimiterTracker T(*this, tok::l_paren);
1843 LParenLoc = T.getOpenLocation();
1844 if (Tok.is(tok::identifier)) {
1845 Name = Tok.getIdentifierInfo();
1846 NameLoc = ConsumeToken();
1848 RParenLoc = T.getCloseLocation();
1849 if (RParenLoc.isInvalid())
1850 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1852 Diag(Tok, diag::err_expected_parameter_pack);
1853 SkipUntil(tok::r_paren, StopAtSemi);
1855 } else if (Tok.is(tok::identifier)) {
1856 Name = Tok.getIdentifierInfo();
1857 NameLoc = ConsumeToken();
1858 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1859 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1860 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1862 << FixItHint::CreateInsertion(LParenLoc, "(")
1863 << FixItHint::CreateInsertion(RParenLoc, ")");
1865 Diag(Tok, diag::err_sizeof_parameter_pack);
1871 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1872 Sema::ReuseLambdaContextDecl);
1874 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1875 OpTok.getLocation(),
1880 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1881 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1883 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1884 Sema::ReuseLambdaContextDecl);
1888 SourceRange CastRange;
1889 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1894 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1895 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1896 ExprKind = UETT_AlignOf;
1897 else if (OpTok.is(tok::kw_vec_step))
1898 ExprKind = UETT_VecStep;
1899 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
1900 ExprKind = UETT_OpenMPRequiredSimdAlign;
1903 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1906 CastTy.getAsOpaquePtr(),
1909 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1910 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1912 // If we get here, the operand to the sizeof/alignof was an expresion.
1913 if (!Operand.isInvalid())
1914 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1922 /// ParseBuiltinPrimaryExpression
1925 /// primary-expression: [C99 6.5.1]
1926 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1927 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1928 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1930 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1931 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1933 /// [GNU] offsetof-member-designator:
1934 /// [GNU] identifier
1935 /// [GNU] offsetof-member-designator '.' identifier
1936 /// [GNU] offsetof-member-designator '[' expression ']'
1938 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1940 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1942 tok::TokenKind T = Tok.getKind();
1943 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
1945 // All of these start with an open paren.
1946 if (Tok.isNot(tok::l_paren))
1947 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
1950 BalancedDelimiterTracker PT(*this, tok::l_paren);
1956 default: llvm_unreachable("Not a builtin primary expression!");
1957 case tok::kw___builtin_va_arg: {
1958 ExprResult Expr(ParseAssignmentExpression());
1960 if (ExpectAndConsume(tok::comma)) {
1961 SkipUntil(tok::r_paren, StopAtSemi);
1965 TypeResult Ty = ParseTypeName();
1967 if (Tok.isNot(tok::r_paren)) {
1968 Diag(Tok, diag::err_expected) << tok::r_paren;
1972 if (Expr.isInvalid() || Ty.isInvalid())
1975 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
1978 case tok::kw___builtin_offsetof: {
1979 SourceLocation TypeLoc = Tok.getLocation();
1980 TypeResult Ty = ParseTypeName();
1981 if (Ty.isInvalid()) {
1982 SkipUntil(tok::r_paren, StopAtSemi);
1986 if (ExpectAndConsume(tok::comma)) {
1987 SkipUntil(tok::r_paren, StopAtSemi);
1991 // We must have at least one identifier here.
1992 if (Tok.isNot(tok::identifier)) {
1993 Diag(Tok, diag::err_expected) << tok::identifier;
1994 SkipUntil(tok::r_paren, StopAtSemi);
1998 // Keep track of the various subcomponents we see.
1999 SmallVector<Sema::OffsetOfComponent, 4> Comps;
2001 Comps.push_back(Sema::OffsetOfComponent());
2002 Comps.back().isBrackets = false;
2003 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2004 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2006 // FIXME: This loop leaks the index expressions on error.
2008 if (Tok.is(tok::period)) {
2009 // offsetof-member-designator: offsetof-member-designator '.' identifier
2010 Comps.push_back(Sema::OffsetOfComponent());
2011 Comps.back().isBrackets = false;
2012 Comps.back().LocStart = ConsumeToken();
2014 if (Tok.isNot(tok::identifier)) {
2015 Diag(Tok, diag::err_expected) << tok::identifier;
2016 SkipUntil(tok::r_paren, StopAtSemi);
2019 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2020 Comps.back().LocEnd = ConsumeToken();
2022 } else if (Tok.is(tok::l_square)) {
2023 if (CheckProhibitedCXX11Attribute())
2026 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2027 Comps.push_back(Sema::OffsetOfComponent());
2028 Comps.back().isBrackets = true;
2029 BalancedDelimiterTracker ST(*this, tok::l_square);
2031 Comps.back().LocStart = ST.getOpenLocation();
2032 Res = ParseExpression();
2033 if (Res.isInvalid()) {
2034 SkipUntil(tok::r_paren, StopAtSemi);
2037 Comps.back().U.E = Res.get();
2040 Comps.back().LocEnd = ST.getCloseLocation();
2042 if (Tok.isNot(tok::r_paren)) {
2045 } else if (Ty.isInvalid()) {
2049 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2051 PT.getCloseLocation());
2058 case tok::kw___builtin_choose_expr: {
2059 ExprResult Cond(ParseAssignmentExpression());
2060 if (Cond.isInvalid()) {
2061 SkipUntil(tok::r_paren, StopAtSemi);
2064 if (ExpectAndConsume(tok::comma)) {
2065 SkipUntil(tok::r_paren, StopAtSemi);
2069 ExprResult Expr1(ParseAssignmentExpression());
2070 if (Expr1.isInvalid()) {
2071 SkipUntil(tok::r_paren, StopAtSemi);
2074 if (ExpectAndConsume(tok::comma)) {
2075 SkipUntil(tok::r_paren, StopAtSemi);
2079 ExprResult Expr2(ParseAssignmentExpression());
2080 if (Expr2.isInvalid()) {
2081 SkipUntil(tok::r_paren, StopAtSemi);
2084 if (Tok.isNot(tok::r_paren)) {
2085 Diag(Tok, diag::err_expected) << tok::r_paren;
2088 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2089 Expr2.get(), ConsumeParen());
2092 case tok::kw___builtin_astype: {
2093 // The first argument is an expression to be converted, followed by a comma.
2094 ExprResult Expr(ParseAssignmentExpression());
2095 if (Expr.isInvalid()) {
2096 SkipUntil(tok::r_paren, StopAtSemi);
2100 if (ExpectAndConsume(tok::comma)) {
2101 SkipUntil(tok::r_paren, StopAtSemi);
2105 // Second argument is the type to bitcast to.
2106 TypeResult DestTy = ParseTypeName();
2107 if (DestTy.isInvalid())
2110 // Attempt to consume the r-paren.
2111 if (Tok.isNot(tok::r_paren)) {
2112 Diag(Tok, diag::err_expected) << tok::r_paren;
2113 SkipUntil(tok::r_paren, StopAtSemi);
2117 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2121 case tok::kw___builtin_convertvector: {
2122 // The first argument is an expression to be converted, followed by a comma.
2123 ExprResult Expr(ParseAssignmentExpression());
2124 if (Expr.isInvalid()) {
2125 SkipUntil(tok::r_paren, StopAtSemi);
2129 if (ExpectAndConsume(tok::comma)) {
2130 SkipUntil(tok::r_paren, StopAtSemi);
2134 // Second argument is the type to bitcast to.
2135 TypeResult DestTy = ParseTypeName();
2136 if (DestTy.isInvalid())
2139 // Attempt to consume the r-paren.
2140 if (Tok.isNot(tok::r_paren)) {
2141 Diag(Tok, diag::err_expected) << tok::r_paren;
2142 SkipUntil(tok::r_paren, StopAtSemi);
2146 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2152 if (Res.isInvalid())
2155 // These can be followed by postfix-expr pieces because they are
2156 // primary-expressions.
2157 return ParsePostfixExpressionSuffix(Res.get());
2160 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2161 /// based on what is allowed by ExprType. The actual thing parsed is returned
2162 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2163 /// not the parsed cast-expression.
2166 /// primary-expression: [C99 6.5.1]
2167 /// '(' expression ')'
2168 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2169 /// postfix-expression: [C99 6.5.2]
2170 /// '(' type-name ')' '{' initializer-list '}'
2171 /// '(' type-name ')' '{' initializer-list ',' '}'
2172 /// cast-expression: [C99 6.5.4]
2173 /// '(' type-name ')' cast-expression
2174 /// [ARC] bridged-cast-expression
2175 /// [ARC] bridged-cast-expression:
2176 /// (__bridge type-name) cast-expression
2177 /// (__bridge_transfer type-name) cast-expression
2178 /// (__bridge_retained type-name) cast-expression
2179 /// fold-expression: [C++1z]
2180 /// '(' cast-expression fold-operator '...' ')'
2181 /// '(' '...' fold-operator cast-expression ')'
2182 /// '(' cast-expression fold-operator '...'
2183 /// fold-operator cast-expression ')'
2186 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2187 bool isTypeCast, ParsedType &CastTy,
2188 SourceLocation &RParenLoc) {
2189 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2190 ColonProtectionRAIIObject ColonProtection(*this, false);
2191 BalancedDelimiterTracker T(*this, tok::l_paren);
2192 if (T.consumeOpen())
2194 SourceLocation OpenLoc = T.getOpenLocation();
2196 ExprResult Result(true);
2197 bool isAmbiguousTypeId;
2200 if (Tok.is(tok::code_completion)) {
2201 Actions.CodeCompleteOrdinaryName(getCurScope(),
2202 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2203 : Sema::PCC_Expression);
2208 // Diagnose use of bridge casts in non-arc mode.
2209 bool BridgeCast = (getLangOpts().ObjC2 &&
2210 Tok.isOneOf(tok::kw___bridge,
2211 tok::kw___bridge_transfer,
2212 tok::kw___bridge_retained,
2213 tok::kw___bridge_retain));
2214 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2215 if (!TryConsumeToken(tok::kw___bridge)) {
2216 StringRef BridgeCastName = Tok.getName();
2217 SourceLocation BridgeKeywordLoc = ConsumeToken();
2218 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2219 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2221 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2226 // None of these cases should fall through with an invalid Result
2227 // unless they've already reported an error.
2228 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2229 Diag(Tok, diag::ext_gnu_statement_expr);
2231 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2232 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2234 // Find the nearest non-record decl context. Variables declared in a
2235 // statement expression behave as if they were declared in the enclosing
2236 // function, block, or other code construct.
2237 DeclContext *CodeDC = Actions.CurContext;
2238 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2239 CodeDC = CodeDC->getParent();
2240 assert(CodeDC && !CodeDC->isFileContext() &&
2241 "statement expr not in code context");
2243 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2245 Actions.ActOnStartStmtExpr();
2247 StmtResult Stmt(ParseCompoundStatement(true));
2248 ExprType = CompoundStmt;
2250 // If the substmt parsed correctly, build the AST node.
2251 if (!Stmt.isInvalid()) {
2252 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2254 Actions.ActOnStmtExprError();
2257 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2258 tok::TokenKind tokenKind = Tok.getKind();
2259 SourceLocation BridgeKeywordLoc = ConsumeToken();
2261 // Parse an Objective-C ARC ownership cast expression.
2262 ObjCBridgeCastKind Kind;
2263 if (tokenKind == tok::kw___bridge)
2265 else if (tokenKind == tok::kw___bridge_transfer)
2266 Kind = OBC_BridgeTransfer;
2267 else if (tokenKind == tok::kw___bridge_retained)
2268 Kind = OBC_BridgeRetained;
2270 // As a hopefully temporary workaround, allow __bridge_retain as
2271 // a synonym for __bridge_retained, but only in system headers.
2272 assert(tokenKind == tok::kw___bridge_retain);
2273 Kind = OBC_BridgeRetained;
2274 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2275 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2276 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2277 "__bridge_retained");
2280 TypeResult Ty = ParseTypeName();
2282 ColonProtection.restore();
2283 RParenLoc = T.getCloseLocation();
2284 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2286 if (Ty.isInvalid() || SubExpr.isInvalid())
2289 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2290 BridgeKeywordLoc, Ty.get(),
2291 RParenLoc, SubExpr.get());
2292 } else if (ExprType >= CompoundLiteral &&
2293 isTypeIdInParens(isAmbiguousTypeId)) {
2295 // Otherwise, this is a compound literal expression or cast expression.
2297 // In C++, if the type-id is ambiguous we disambiguate based on context.
2298 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2299 // in which case we should treat it as type-id.
2300 // if stopIfCastExpr is false, we need to determine the context past the
2301 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2302 if (isAmbiguousTypeId && !stopIfCastExpr) {
2303 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2305 RParenLoc = T.getCloseLocation();
2309 // Parse the type declarator.
2310 DeclSpec DS(AttrFactory);
2311 ParseSpecifierQualifierList(DS);
2312 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2313 ParseDeclarator(DeclaratorInfo);
2315 // If our type is followed by an identifier and either ':' or ']', then
2316 // this is probably an Objective-C message send where the leading '[' is
2317 // missing. Recover as if that were the case.
2318 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2319 !InMessageExpression && getLangOpts().ObjC1 &&
2320 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2323 InMessageExpressionRAIIObject InMessage(*this, false);
2324 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2326 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2332 ColonProtection.restore();
2333 RParenLoc = T.getCloseLocation();
2334 if (Tok.is(tok::l_brace)) {
2335 ExprType = CompoundLiteral;
2338 InMessageExpressionRAIIObject InMessage(*this, false);
2339 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2341 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2344 if (ExprType == CastExpr) {
2345 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2347 if (DeclaratorInfo.isInvalidType())
2350 // Note that this doesn't parse the subsequent cast-expression, it just
2351 // returns the parsed type to the callee.
2352 if (stopIfCastExpr) {
2355 InMessageExpressionRAIIObject InMessage(*this, false);
2356 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2359 return ExprResult();
2362 // Reject the cast of super idiom in ObjC.
2363 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2364 Tok.getIdentifierInfo() == Ident_super &&
2365 getCurScope()->isInObjcMethodScope() &&
2366 GetLookAheadToken(1).isNot(tok::period)) {
2367 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2368 << SourceRange(OpenLoc, RParenLoc);
2372 // Parse the cast-expression that follows it next.
2373 // TODO: For cast expression with CastTy.
2374 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2375 /*isAddressOfOperand=*/false,
2376 /*isTypeCast=*/IsTypeCast);
2377 if (!Result.isInvalid()) {
2378 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2379 DeclaratorInfo, CastTy,
2380 RParenLoc, Result.get());
2385 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2388 } else if (Tok.is(tok::ellipsis) &&
2389 isFoldOperator(NextToken().getKind())) {
2390 return ParseFoldExpression(ExprResult(), T);
2391 } else if (isTypeCast) {
2392 // Parse the expression-list.
2393 InMessageExpressionRAIIObject InMessage(*this, false);
2395 ExprVector ArgExprs;
2396 CommaLocsTy CommaLocs;
2398 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2399 // FIXME: If we ever support comma expressions as operands to
2400 // fold-expressions, we'll need to allow multiple ArgExprs here.
2401 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2402 NextToken().is(tok::ellipsis))
2403 return ParseFoldExpression(Result, T);
2405 ExprType = SimpleExpr;
2406 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2410 InMessageExpressionRAIIObject InMessage(*this, false);
2412 Result = ParseExpression(MaybeTypeCast);
2413 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2414 // Correct typos in non-C++ code earlier so that implicit-cast-like
2415 // expressions are parsed correctly.
2416 Result = Actions.CorrectDelayedTyposInExpr(Result);
2418 ExprType = SimpleExpr;
2420 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2421 return ParseFoldExpression(Result, T);
2423 // Don't build a paren expression unless we actually match a ')'.
2424 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2426 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2430 if (Result.isInvalid()) {
2431 SkipUntil(tok::r_paren, StopAtSemi);
2436 RParenLoc = T.getCloseLocation();
2440 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2441 /// and we are at the left brace.
2444 /// postfix-expression: [C99 6.5.2]
2445 /// '(' type-name ')' '{' initializer-list '}'
2446 /// '(' type-name ')' '{' initializer-list ',' '}'
2449 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2450 SourceLocation LParenLoc,
2451 SourceLocation RParenLoc) {
2452 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2453 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2454 Diag(LParenLoc, diag::ext_c99_compound_literal);
2455 ExprResult Result = ParseInitializer();
2456 if (!Result.isInvalid() && Ty)
2457 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2461 /// ParseStringLiteralExpression - This handles the various token types that
2462 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2463 /// translation phase #6].
2466 /// primary-expression: [C99 6.5.1]
2469 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2470 assert(isTokenStringLiteral() && "Not a string literal!");
2472 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2473 // considered to be strings for concatenation purposes.
2474 SmallVector<Token, 4> StringToks;
2477 StringToks.push_back(Tok);
2478 ConsumeStringToken();
2479 } while (isTokenStringLiteral());
2481 // Pass the set of string tokens, ready for concatenation, to the actions.
2482 return Actions.ActOnStringLiteral(StringToks,
2483 AllowUserDefinedLiteral ? getCurScope()
2487 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2491 /// generic-selection:
2492 /// _Generic ( assignment-expression , generic-assoc-list )
2493 /// generic-assoc-list:
2494 /// generic-association
2495 /// generic-assoc-list , generic-association
2496 /// generic-association:
2497 /// type-name : assignment-expression
2498 /// default : assignment-expression
2500 ExprResult Parser::ParseGenericSelectionExpression() {
2501 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2502 SourceLocation KeyLoc = ConsumeToken();
2504 if (!getLangOpts().C11)
2505 Diag(KeyLoc, diag::ext_c11_generic_selection);
2507 BalancedDelimiterTracker T(*this, tok::l_paren);
2508 if (T.expectAndConsume())
2511 ExprResult ControllingExpr;
2513 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2515 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2517 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2518 if (ControllingExpr.isInvalid()) {
2519 SkipUntil(tok::r_paren, StopAtSemi);
2524 if (ExpectAndConsume(tok::comma)) {
2525 SkipUntil(tok::r_paren, StopAtSemi);
2529 SourceLocation DefaultLoc;
2534 if (Tok.is(tok::kw_default)) {
2535 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2536 // generic association."
2537 if (!DefaultLoc.isInvalid()) {
2538 Diag(Tok, diag::err_duplicate_default_assoc);
2539 Diag(DefaultLoc, diag::note_previous_default_assoc);
2540 SkipUntil(tok::r_paren, StopAtSemi);
2543 DefaultLoc = ConsumeToken();
2546 ColonProtectionRAIIObject X(*this);
2547 TypeResult TR = ParseTypeName();
2548 if (TR.isInvalid()) {
2549 SkipUntil(tok::r_paren, StopAtSemi);
2554 Types.push_back(Ty);
2556 if (ExpectAndConsume(tok::colon)) {
2557 SkipUntil(tok::r_paren, StopAtSemi);
2561 // FIXME: These expressions should be parsed in a potentially potentially
2562 // evaluated context.
2564 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2565 if (ER.isInvalid()) {
2566 SkipUntil(tok::r_paren, StopAtSemi);
2569 Exprs.push_back(ER.get());
2570 } while (TryConsumeToken(tok::comma));
2573 if (T.getCloseLocation().isInvalid())
2576 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2577 T.getCloseLocation(),
2578 ControllingExpr.get(),
2582 /// \brief Parse A C++1z fold-expression after the opening paren and optional
2583 /// left-hand-side expression.
2586 /// fold-expression:
2587 /// ( cast-expression fold-operator ... )
2588 /// ( ... fold-operator cast-expression )
2589 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2590 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2591 BalancedDelimiterTracker &T) {
2592 if (LHS.isInvalid()) {
2597 tok::TokenKind Kind = tok::unknown;
2598 SourceLocation FirstOpLoc;
2599 if (LHS.isUsable()) {
2600 Kind = Tok.getKind();
2601 assert(isFoldOperator(Kind) && "missing fold-operator");
2602 FirstOpLoc = ConsumeToken();
2605 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2606 SourceLocation EllipsisLoc = ConsumeToken();
2609 if (Tok.isNot(tok::r_paren)) {
2610 if (!isFoldOperator(Tok.getKind()))
2611 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2613 if (Kind != tok::unknown && Tok.getKind() != Kind)
2614 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2615 << SourceRange(FirstOpLoc);
2616 Kind = Tok.getKind();
2619 RHS = ParseExpression();
2620 if (RHS.isInvalid()) {
2626 Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
2627 ? diag::warn_cxx14_compat_fold_expression
2628 : diag::ext_fold_expression);
2631 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2632 EllipsisLoc, RHS.get(), T.getCloseLocation());
2635 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2638 /// argument-expression-list:
2639 /// assignment-expression
2640 /// argument-expression-list , assignment-expression
2642 /// [C++] expression-list:
2643 /// [C++] assignment-expression
2644 /// [C++] expression-list , assignment-expression
2646 /// [C++0x] expression-list:
2647 /// [C++0x] initializer-list
2649 /// [C++0x] initializer-list
2650 /// [C++0x] initializer-clause ...[opt]
2651 /// [C++0x] initializer-list , initializer-clause ...[opt]
2653 /// [C++0x] initializer-clause:
2654 /// [C++0x] assignment-expression
2655 /// [C++0x] braced-init-list
2657 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2658 SmallVectorImpl<SourceLocation> &CommaLocs,
2659 std::function<void()> Completer) {
2660 bool SawError = false;
2662 if (Tok.is(tok::code_completion)) {
2666 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2672 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2673 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2674 Expr = ParseBraceInitializer();
2676 Expr = ParseAssignmentExpression();
2678 if (Tok.is(tok::ellipsis))
2679 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2680 if (Expr.isInvalid()) {
2681 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2684 Exprs.push_back(Expr.get());
2687 if (Tok.isNot(tok::comma))
2689 // Move to the next argument, remember where the comma was.
2690 CommaLocs.push_back(ConsumeToken());
2693 // Ensure typos get diagnosed when errors were encountered while parsing the
2695 for (auto &E : Exprs) {
2696 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2697 if (Expr.isUsable()) E = Expr.get();
2703 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2704 /// used for misc language extensions.
2707 /// simple-expression-list:
2708 /// assignment-expression
2709 /// simple-expression-list , assignment-expression
2712 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2713 SmallVectorImpl<SourceLocation> &CommaLocs) {
2715 ExprResult Expr = ParseAssignmentExpression();
2716 if (Expr.isInvalid())
2719 Exprs.push_back(Expr.get());
2721 if (Tok.isNot(tok::comma))
2724 // Move to the next argument, remember where the comma was.
2725 CommaLocs.push_back(ConsumeToken());
2729 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2732 /// [clang] block-id:
2733 /// [clang] specifier-qualifier-list block-declarator
2735 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2736 if (Tok.is(tok::code_completion)) {
2737 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2738 return cutOffParsing();
2741 // Parse the specifier-qualifier-list piece.
2742 DeclSpec DS(AttrFactory);
2743 ParseSpecifierQualifierList(DS);
2745 // Parse the block-declarator.
2746 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2747 ParseDeclarator(DeclaratorInfo);
2749 MaybeParseGNUAttributes(DeclaratorInfo);
2751 // Inform sema that we are starting a block.
2752 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2755 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2756 /// like ^(int x){ return x+1; }
2760 /// [clang] '^' block-args[opt] compound-statement
2761 /// [clang] '^' block-id compound-statement
2762 /// [clang] block-args:
2763 /// [clang] '(' parameter-list ')'
2765 ExprResult Parser::ParseBlockLiteralExpression() {
2766 assert(Tok.is(tok::caret) && "block literal starts with ^");
2767 SourceLocation CaretLoc = ConsumeToken();
2769 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2770 "block literal parsing");
2772 // Enter a scope to hold everything within the block. This includes the
2773 // argument decls, decls within the compound expression, etc. This also
2774 // allows determining whether a variable reference inside the block is
2775 // within or outside of the block.
2776 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2779 // Inform sema that we are starting a block.
2780 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2782 // Parse the return type if present.
2783 DeclSpec DS(AttrFactory);
2784 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2785 // FIXME: Since the return type isn't actually parsed, it can't be used to
2786 // fill ParamInfo with an initial valid range, so do it manually.
2787 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2789 // If this block has arguments, parse them. There is no ambiguity here with
2790 // the expression case, because the expression case requires a parameter list.
2791 if (Tok.is(tok::l_paren)) {
2792 ParseParenDeclarator(ParamInfo);
2793 // Parse the pieces after the identifier as if we had "int(...)".
2794 // SetIdentifier sets the source range end, but in this case we're past
2796 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2797 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2798 ParamInfo.SetRangeEnd(Tmp);
2799 if (ParamInfo.isInvalidType()) {
2800 // If there was an error parsing the arguments, they may have
2801 // tried to use ^(x+y) which requires an argument list. Just
2802 // skip the whole block literal.
2803 Actions.ActOnBlockError(CaretLoc, getCurScope());
2807 MaybeParseGNUAttributes(ParamInfo);
2809 // Inform sema that we are starting a block.
2810 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2811 } else if (!Tok.is(tok::l_brace)) {
2812 ParseBlockId(CaretLoc);
2814 // Otherwise, pretend we saw (void).
2815 ParsedAttributes attrs(AttrFactory);
2816 SourceLocation NoLoc;
2817 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2818 /*IsAmbiguous=*/false,
2819 /*RParenLoc=*/NoLoc,
2820 /*ArgInfo=*/nullptr,
2822 /*EllipsisLoc=*/NoLoc,
2823 /*RParenLoc=*/NoLoc,
2825 /*RefQualifierIsLvalueRef=*/true,
2826 /*RefQualifierLoc=*/NoLoc,
2827 /*ConstQualifierLoc=*/NoLoc,
2828 /*VolatileQualifierLoc=*/NoLoc,
2829 /*RestrictQualifierLoc=*/NoLoc,
2830 /*MutableLoc=*/NoLoc,
2832 /*ESpecRange=*/SourceRange(),
2833 /*Exceptions=*/nullptr,
2834 /*ExceptionRanges=*/nullptr,
2835 /*NumExceptions=*/0,
2836 /*NoexceptExpr=*/nullptr,
2837 /*ExceptionSpecTokens=*/nullptr,
2842 MaybeParseGNUAttributes(ParamInfo);
2844 // Inform sema that we are starting a block.
2845 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2849 ExprResult Result(true);
2850 if (!Tok.is(tok::l_brace)) {
2851 // Saw something like: ^expr
2852 Diag(Tok, diag::err_expected_expression);
2853 Actions.ActOnBlockError(CaretLoc, getCurScope());
2857 StmtResult Stmt(ParseCompoundStatementBody());
2859 if (!Stmt.isInvalid())
2860 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2862 Actions.ActOnBlockError(CaretLoc, getCurScope());
2866 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2870 ExprResult Parser::ParseObjCBoolLiteral() {
2871 tok::TokenKind Kind = Tok.getKind();
2872 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
2875 /// Validate availability spec list, emitting diagnostics if necessary. Returns
2876 /// true if invalid.
2877 static bool CheckAvailabilitySpecList(Parser &P,
2878 ArrayRef<AvailabilitySpec> AvailSpecs) {
2879 llvm::SmallSet<StringRef, 4> Platforms;
2880 bool HasOtherPlatformSpec = false;
2882 for (const auto &Spec : AvailSpecs) {
2883 if (Spec.isOtherPlatformSpec()) {
2884 if (HasOtherPlatformSpec) {
2885 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
2889 HasOtherPlatformSpec = true;
2893 bool Inserted = Platforms.insert(Spec.getPlatform()).second;
2895 // Rule out multiple version specs referring to the same platform.
2896 // For example, we emit an error for:
2897 // @available(macos 10.10, macos 10.11, *)
2898 StringRef Platform = Spec.getPlatform();
2899 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
2900 << Spec.getEndLoc() << Platform;
2905 if (!HasOtherPlatformSpec) {
2906 SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
2907 P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
2908 << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
2915 /// Parse availability query specification.
2917 /// availability-spec:
2919 /// identifier version-tuple
2920 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
2921 if (Tok.is(tok::star)) {
2922 return AvailabilitySpec(ConsumeToken());
2924 // Parse the platform name.
2925 if (Tok.isNot(tok::identifier)) {
2926 Diag(Tok, diag::err_avail_query_expected_platform_name);
2930 IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
2931 SourceRange VersionRange;
2932 VersionTuple Version = ParseVersionTuple(VersionRange);
2934 if (Version.empty())
2937 StringRef Platform = PlatformIdentifier->Ident->getName();
2939 if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
2940 Diag(PlatformIdentifier->Loc,
2941 diag::err_avail_query_unrecognized_platform_name)
2946 return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
2947 VersionRange.getEnd());
2951 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
2952 assert(Tok.is(tok::kw___builtin_available) ||
2953 Tok.isObjCAtKeyword(tok::objc_available));
2955 // Eat the available or __builtin_available.
2958 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2959 if (Parens.expectAndConsume())
2962 SmallVector<AvailabilitySpec, 4> AvailSpecs;
2963 bool HasError = false;
2965 Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
2969 AvailSpecs.push_back(*Spec);
2971 if (!TryConsumeToken(tok::comma))
2976 SkipUntil(tok::r_paren, StopAtSemi);
2980 CheckAvailabilitySpecList(*this, AvailSpecs);
2982 if (Parens.consumeClose())
2985 return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
2986 Parens.getCloseLocation());