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();
167 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
168 /*isAddressOfOperand=*/false,
170 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
173 /// \brief Parse an assignment expression where part of an Objective-C message
174 /// send has already been parsed.
176 /// In this case \p LBracLoc indicates the location of the '[' of the message
177 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
178 /// the receiver of the message.
180 /// Since this handles full assignment-expression's, it handles postfix
181 /// expressions and other binary operators for these expressions as well.
183 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
184 SourceLocation SuperLoc,
185 ParsedType ReceiverType,
186 Expr *ReceiverExpr) {
188 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
189 ReceiverType, ReceiverExpr);
190 R = ParsePostfixExpressionSuffix(R);
191 return ParseRHSOfBinaryExpression(R, prec::Assignment);
195 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
196 // C++03 [basic.def.odr]p2:
197 // An expression is potentially evaluated unless it appears where an
198 // integral constant expression is required (see 5.19) [...].
199 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
200 EnterExpressionEvaluationContext Unevaluated(Actions,
201 Sema::ConstantEvaluated);
203 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
204 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
205 return Actions.ActOnConstantExpression(Res);
208 bool Parser::isNotExpressionStart() {
209 tok::TokenKind K = Tok.getKind();
210 if (K == tok::l_brace || K == tok::r_brace ||
211 K == tok::kw_for || K == tok::kw_while ||
212 K == tok::kw_if || K == tok::kw_else ||
213 K == tok::kw_goto || K == tok::kw_try)
215 // If this is a decl-specifier, we can't be at the start of an expression.
216 return isKnownToBeDeclarationSpecifier();
219 /// \brief Parse a binary expression that starts with \p LHS and has a
220 /// precedence of at least \p MinPrec.
222 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
223 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
224 GreaterThanIsOperator,
225 getLangOpts().CPlusPlus11);
226 SourceLocation ColonLoc;
229 // If this token has a lower precedence than we are allowed to parse (e.g.
230 // because we are called recursively, or because the token is not a binop),
232 if (NextTokPrec < MinPrec)
235 // Consume the operator, saving the operator token for error reporting.
239 // Bail out when encountering a comma followed by a token which can't
240 // possibly be the start of an expression. For instance:
241 // int f() { return 1, }
242 // We can't do this before consuming the comma, because
243 // isNotExpressionStart() looks at the token stream.
244 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
250 // Special case handling for the ternary operator.
251 ExprResult TernaryMiddle(true);
252 if (NextTokPrec == prec::Conditional) {
253 if (Tok.isNot(tok::colon)) {
254 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
255 ColonProtectionRAIIObject X(*this);
257 // Handle this production specially:
258 // logical-OR-expression '?' expression ':' conditional-expression
259 // In particular, the RHS of the '?' is 'expression', not
260 // 'logical-OR-expression' as we might expect.
261 TernaryMiddle = ParseExpression();
262 if (TernaryMiddle.isInvalid()) {
264 TernaryMiddle = nullptr;
267 // Special case handling of "X ? Y : Z" where Y is empty:
268 // logical-OR-expression '?' ':' conditional-expression [GNU]
269 TernaryMiddle = nullptr;
270 Diag(Tok, diag::ext_gnu_conditional_expr);
273 if (!TryConsumeToken(tok::colon, ColonLoc)) {
274 // Otherwise, we're missing a ':'. Assume that this was a typo that
275 // the user forgot. If we're not in a macro expansion, we can suggest
276 // a fixit hint. If there were two spaces before the current token,
277 // suggest inserting the colon in between them, otherwise insert ": ".
278 SourceLocation FILoc = Tok.getLocation();
279 const char *FIText = ": ";
280 const SourceManager &SM = PP.getSourceManager();
281 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
282 assert(FILoc.isFileID());
283 bool IsInvalid = false;
284 const char *SourcePtr =
285 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
286 if (!IsInvalid && *SourcePtr == ' ') {
288 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
289 if (!IsInvalid && *SourcePtr == ' ') {
290 FILoc = FILoc.getLocWithOffset(-1);
296 Diag(Tok, diag::err_expected)
297 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
298 Diag(OpToken, diag::note_matching) << tok::question;
299 ColonLoc = Tok.getLocation();
303 // Code completion for the right-hand side of an assignment expression
304 // goes through a special hook that takes the left-hand side into account.
305 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
306 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
311 // Parse another leaf here for the RHS of the operator.
312 // ParseCastExpression works here because all RHS expressions in C have it
313 // as a prefix, at least. However, in C++, an assignment-expression could
314 // be a throw-expression, which is not a valid cast-expression.
315 // Therefore we need some special-casing here.
316 // Also note that the third operand of the conditional operator is
317 // an assignment-expression in C++, and in C++11, we can have a
318 // braced-init-list on the RHS of an assignment. For better diagnostics,
319 // parse as if we were allowed braced-init-lists everywhere, and check that
320 // they only appear on the RHS of assignments later.
322 bool RHSIsInitList = false;
323 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
324 RHS = ParseBraceInitializer();
325 RHSIsInitList = true;
326 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
327 RHS = ParseAssignmentExpression();
329 RHS = ParseCastExpression(false);
334 // Remember the precedence of this operator and get the precedence of the
335 // operator immediately to the right of the RHS.
336 prec::Level ThisPrec = NextTokPrec;
337 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
338 getLangOpts().CPlusPlus11);
340 // Assignment and conditional expressions are right-associative.
341 bool isRightAssoc = ThisPrec == prec::Conditional ||
342 ThisPrec == prec::Assignment;
344 // Get the precedence of the operator to the right of the RHS. If it binds
345 // more tightly with RHS than we do, evaluate it completely first.
346 if (ThisPrec < NextTokPrec ||
347 (ThisPrec == NextTokPrec && isRightAssoc)) {
348 if (!RHS.isInvalid() && RHSIsInitList) {
349 Diag(Tok, diag::err_init_list_bin_op)
350 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
353 // If this is left-associative, only parse things on the RHS that bind
354 // more tightly than the current operator. If it is left-associative, it
355 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
356 // A=(B=(C=D)), where each paren is a level of recursion here.
357 // The function takes ownership of the RHS.
358 RHS = ParseRHSOfBinaryExpression(RHS,
359 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
360 RHSIsInitList = false;
365 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
366 getLangOpts().CPlusPlus11);
368 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
370 if (!RHS.isInvalid() && RHSIsInitList) {
371 if (ThisPrec == prec::Assignment) {
372 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
373 << Actions.getExprRange(RHS.get());
375 Diag(OpToken, diag::err_init_list_bin_op)
376 << /*RHS*/1 << PP.getSpelling(OpToken)
377 << Actions.getExprRange(RHS.get());
382 if (!LHS.isInvalid()) {
383 // Combine the LHS and RHS into the LHS (e.g. build AST).
384 if (TernaryMiddle.isInvalid()) {
385 // If we're using '>>' as an operator within a template
386 // argument list (in C++98), suggest the addition of
387 // parentheses so that the code remains well-formed in C++0x.
388 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
389 SuggestParentheses(OpToken.getLocation(),
390 diag::warn_cxx11_right_shift_in_template_arg,
391 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
392 Actions.getExprRange(RHS.get()).getEnd()));
394 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
395 OpToken.getKind(), LHS.get(), RHS.get());
397 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
398 LHS.get(), TernaryMiddle.get(),
404 /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
405 /// parse a unary-expression.
407 /// \p isAddressOfOperand exists because an id-expression that is the
408 /// operand of address-of gets special treatment due to member pointers.
410 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
411 bool isAddressOfOperand,
412 TypeCastState isTypeCast) {
414 ExprResult Res = ParseCastExpression(isUnaryExpression,
419 Diag(Tok, diag::err_expected_expression);
424 class CastExpressionIdValidator : public CorrectionCandidateCallback {
426 CastExpressionIdValidator(bool AllowTypes, bool AllowNonTypes)
427 : AllowNonTypes(AllowNonTypes) {
428 WantTypeSpecifiers = AllowTypes;
431 bool ValidateCandidate(const TypoCorrection &candidate) override {
432 NamedDecl *ND = candidate.getCorrectionDecl();
434 return candidate.isKeyword();
436 if (isa<TypeDecl>(ND))
437 return WantTypeSpecifiers;
438 return AllowNonTypes &&
439 CorrectionCandidateCallback::ValidateCandidate(candidate);
447 /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
448 /// a unary-expression.
450 /// \p isAddressOfOperand exists because an id-expression that is the operand
451 /// of address-of gets special treatment due to member pointers. NotCastExpr
452 /// is set to true if the token is not the start of a cast-expression, and no
453 /// diagnostic is emitted in this case.
456 /// cast-expression: [C99 6.5.4]
458 /// '(' type-name ')' cast-expression
460 /// unary-expression: [C99 6.5.3]
461 /// postfix-expression
462 /// '++' unary-expression
463 /// '--' unary-expression
464 /// unary-operator cast-expression
465 /// 'sizeof' unary-expression
466 /// 'sizeof' '(' type-name ')'
467 /// [C++11] 'sizeof' '...' '(' identifier ')'
468 /// [GNU] '__alignof' unary-expression
469 /// [GNU] '__alignof' '(' type-name ')'
470 /// [C11] '_Alignof' '(' type-name ')'
471 /// [C++11] 'alignof' '(' type-id ')'
472 /// [GNU] '&&' identifier
473 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
474 /// [C++] new-expression
475 /// [C++] delete-expression
477 /// unary-operator: one of
478 /// '&' '*' '+' '-' '~' '!'
479 /// [GNU] '__extension__' '__real' '__imag'
481 /// primary-expression: [C99 6.5.1]
483 /// [C++] id-expression
486 /// [C++] boolean-literal [C++ 2.13.5]
487 /// [C++11] 'nullptr' [C++11 2.14.7]
488 /// [C++11] user-defined-literal
489 /// '(' expression ')'
490 /// [C11] generic-selection
491 /// '__func__' [C99 6.4.2.2]
492 /// [GNU] '__FUNCTION__'
493 /// [MS] '__FUNCDNAME__'
494 /// [MS] 'L__FUNCTION__'
495 /// [GNU] '__PRETTY_FUNCTION__'
496 /// [GNU] '(' compound-statement ')'
497 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
498 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
499 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
501 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
503 /// [OBJC] '[' objc-message-expr ']'
504 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
505 /// [OBJC] '\@protocol' '(' identifier ')'
506 /// [OBJC] '\@encode' '(' type-name ')'
507 /// [OBJC] objc-string-literal
508 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
509 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
510 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
511 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
512 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
513 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
514 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
515 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
516 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
517 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
518 /// [C++] 'this' [C++ 9.3.2]
519 /// [G++] unary-type-trait '(' type-id ')'
520 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
521 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
522 /// [clang] '^' block-literal
524 /// constant: [C99 6.4.4]
526 /// floating-constant
527 /// enumeration-constant -> identifier
528 /// character-constant
530 /// id-expression: [C++ 5.1]
534 /// unqualified-id: [C++ 5.1]
536 /// operator-function-id
537 /// conversion-function-id
541 /// new-expression: [C++ 5.3.4]
542 /// '::'[opt] 'new' new-placement[opt] new-type-id
543 /// new-initializer[opt]
544 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
545 /// new-initializer[opt]
547 /// delete-expression: [C++ 5.3.5]
548 /// '::'[opt] 'delete' cast-expression
549 /// '::'[opt] 'delete' '[' ']' cast-expression
551 /// [GNU/Embarcadero] unary-type-trait:
552 /// '__is_arithmetic'
553 /// '__is_floating_point'
555 /// '__is_lvalue_expr'
556 /// '__is_rvalue_expr'
557 /// '__is_complete_type'
562 /// '__is_lvalue_reference'
563 /// '__is_rvalue_reference'
564 /// '__is_fundamental'
569 /// '__is_member_object_pointer'
570 /// '__is_member_function_pointer'
571 /// '__is_member_pointer'
575 /// '__is_standard_layout'
579 /// [GNU] unary-type-trait:
580 /// '__has_nothrow_assign'
581 /// '__has_nothrow_copy'
582 /// '__has_nothrow_constructor'
583 /// '__has_trivial_assign' [TODO]
584 /// '__has_trivial_copy' [TODO]
585 /// '__has_trivial_constructor'
586 /// '__has_trivial_destructor'
587 /// '__has_virtual_destructor'
588 /// '__is_abstract' [TODO]
590 /// '__is_empty' [TODO]
594 /// '__is_polymorphic'
595 /// '__is_sealed' [MS]
599 /// [Clang] unary-type-trait:
600 /// '__trivially_copyable'
602 /// binary-type-trait:
603 /// [GNU] '__is_base_of'
604 /// [MS] '__is_convertible_to'
605 /// '__is_convertible'
608 /// [Embarcadero] array-type-trait:
612 /// [Embarcadero] expression-trait:
613 /// '__is_lvalue_expr'
614 /// '__is_rvalue_expr'
617 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
618 bool isAddressOfOperand,
620 TypeCastState isTypeCast) {
622 tok::TokenKind SavedKind = Tok.getKind();
625 // This handles all of cast-expression, unary-expression, postfix-expression,
626 // and primary-expression. We handle them together like this for efficiency
627 // and to simplify handling of an expression starting with a '(' token: which
628 // may be one of a parenthesized expression, cast-expression, compound literal
629 // expression, or statement expression.
631 // If the parsed tokens consist of a primary-expression, the cases below
632 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
633 // to handle the postfix expression suffixes. Cases that cannot be followed
634 // by postfix exprs should return without invoking
635 // ParsePostfixExpressionSuffix.
638 // If this expression is limited to being a unary-expression, the parent can
639 // not start a cast expression.
640 ParenParseOption ParenExprType =
641 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
644 SourceLocation RParenLoc;
645 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
646 isTypeCast == IsTypeCast, CastTy, RParenLoc);
648 switch (ParenExprType) {
649 case SimpleExpr: break; // Nothing else to do.
650 case CompoundStmt: break; // Nothing else to do.
651 case CompoundLiteral:
652 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
653 // postfix-expression exist, parse them now.
656 // We have parsed the cast-expression and no postfix-expr pieces are
664 // primary-expression
665 case tok::numeric_constant:
666 // constant: integer-constant
667 // constant: floating-constant
669 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
675 return ParseCXXBoolLiteral();
677 case tok::kw___objc_yes:
678 case tok::kw___objc_no:
679 return ParseObjCBoolLiteral();
681 case tok::kw_nullptr:
682 Diag(Tok, diag::warn_cxx98_compat_nullptr);
683 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
685 case tok::annot_primary_expr:
686 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
687 Res = getExprAnnotation(Tok);
691 case tok::kw_decltype:
692 // Annotate the token and tail recurse.
693 if (TryAnnotateTypeOrScopeToken())
695 assert(Tok.isNot(tok::kw_decltype));
696 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
698 case tok::identifier: { // primary-expression: identifier
699 // unqualified-id: identifier
700 // constant: enumeration-constant
701 // Turn a potentially qualified name into a annot_typename or
702 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
703 if (getLangOpts().CPlusPlus) {
704 // Avoid the unnecessary parse-time lookup in the common case
705 // where the syntax forbids a type.
706 const Token &Next = NextToken();
708 // If this identifier was reverted from a token ID, and the next token
709 // is a parenthesis, this is likely to be a use of a type trait. Check
711 if (Next.is(tok::l_paren) && Tok.is(tok::identifier) &&
712 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier() &&
713 TryIdentKeywordUpgrade())
714 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
715 NotCastExpr, isTypeCast);
717 if (Next.is(tok::coloncolon) ||
718 (!ColonIsSacred && Next.is(tok::colon)) ||
719 Next.is(tok::less) ||
720 Next.is(tok::l_paren) ||
721 Next.is(tok::l_brace)) {
722 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
723 if (TryAnnotateTypeOrScopeToken())
725 if (!Tok.is(tok::identifier))
726 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
730 // Consume the identifier so that we can see if it is followed by a '(' or
732 IdentifierInfo &II = *Tok.getIdentifierInfo();
733 SourceLocation ILoc = ConsumeToken();
735 // Support 'Class.property' and 'super.property' notation.
736 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
737 (Actions.getTypeName(II, ILoc, getCurScope()) ||
738 // Allow the base to be 'super' if in an objc-method.
739 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
742 // Allow either an identifier or the keyword 'class' (in C++).
743 if (Tok.isNot(tok::identifier) &&
744 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
745 Diag(Tok, diag::err_expected_property_name);
748 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
749 SourceLocation PropertyLoc = ConsumeToken();
751 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
756 // In an Objective-C method, if we have "super" followed by an identifier,
757 // the token sequence is ill-formed. However, if there's a ':' or ']' after
758 // that identifier, this is probably a message send with a missing open
759 // bracket. Treat it as such.
760 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
761 getCurScope()->isInObjcMethodScope() &&
762 ((Tok.is(tok::identifier) &&
763 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
764 Tok.is(tok::code_completion))) {
765 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
770 // If we have an Objective-C class name followed by an identifier
771 // and either ':' or ']', this is an Objective-C class message
772 // send that's missing the opening '['. Recovery
773 // appropriately. Also take this path if we're performing code
774 // completion after an Objective-C class name.
775 if (getLangOpts().ObjC1 &&
776 ((Tok.is(tok::identifier) && !InMessageExpression) ||
777 Tok.is(tok::code_completion))) {
778 const Token& Next = NextToken();
779 if (Tok.is(tok::code_completion) ||
780 Next.is(tok::colon) || Next.is(tok::r_square))
781 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
782 if (Typ.get()->isObjCObjectOrInterfaceType()) {
783 // Fake up a Declarator to use with ActOnTypeName.
784 DeclSpec DS(AttrFactory);
785 DS.SetRangeStart(ILoc);
786 DS.SetRangeEnd(ILoc);
787 const char *PrevSpec = nullptr;
789 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
790 Actions.getASTContext().getPrintingPolicy());
792 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
793 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
798 Res = ParseObjCMessageExpressionBody(SourceLocation(),
805 // Make sure to pass down the right value for isAddressOfOperand.
806 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
807 isAddressOfOperand = false;
809 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
810 // need to know whether or not this identifier is a function designator or
813 CXXScopeSpec ScopeSpec;
814 SourceLocation TemplateKWLoc;
815 CastExpressionIdValidator Validator(isTypeCast != NotTypeCast,
816 isTypeCast != IsTypeCast);
817 Validator.IsAddressOfOperand = isAddressOfOperand;
818 Name.setIdentifier(&II, ILoc);
819 Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, TemplateKWLoc,
820 Name, Tok.is(tok::l_paren),
821 isAddressOfOperand, &Validator);
824 case tok::char_constant: // constant: character-constant
825 case tok::wide_char_constant:
826 case tok::utf16_char_constant:
827 case tok::utf32_char_constant:
828 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
831 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
832 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
833 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
834 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
835 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
836 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
837 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
840 case tok::string_literal: // primary-expression: string-literal
841 case tok::wide_string_literal:
842 case tok::utf8_string_literal:
843 case tok::utf16_string_literal:
844 case tok::utf32_string_literal:
845 Res = ParseStringLiteralExpression(true);
847 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
848 Res = ParseGenericSelectionExpression();
850 case tok::kw___builtin_va_arg:
851 case tok::kw___builtin_offsetof:
852 case tok::kw___builtin_choose_expr:
853 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
854 case tok::kw___builtin_convertvector:
855 return ParseBuiltinPrimaryExpression();
857 return Actions.ActOnGNUNullExpr(ConsumeToken());
859 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
860 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
861 // C++ [expr.unary] has:
863 // ++ cast-expression
864 // -- cast-expression
865 SourceLocation SavedLoc = ConsumeToken();
866 // One special case is implicitly handled here: if the preceding tokens are
867 // an ambiguous cast expression, such as "(T())++", then we recurse to
868 // determine whether the '++' is prefix or postfix.
869 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
870 /*isAddressOfOperand*/false, NotCastExpr,
872 if (!Res.isInvalid())
873 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
876 case tok::amp: { // unary-expression: '&' cast-expression
877 // Special treatment because of member pointers
878 SourceLocation SavedLoc = ConsumeToken();
879 Res = ParseCastExpression(false, true);
880 if (!Res.isInvalid())
881 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
885 case tok::star: // unary-expression: '*' cast-expression
886 case tok::plus: // unary-expression: '+' cast-expression
887 case tok::minus: // unary-expression: '-' cast-expression
888 case tok::tilde: // unary-expression: '~' cast-expression
889 case tok::exclaim: // unary-expression: '!' cast-expression
890 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
891 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
892 SourceLocation SavedLoc = ConsumeToken();
893 Res = ParseCastExpression(false);
894 if (!Res.isInvalid())
895 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
899 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
900 // __extension__ silences extension warnings in the subexpression.
901 ExtensionRAIIObject O(Diags); // Use RAII to do this.
902 SourceLocation SavedLoc = ConsumeToken();
903 Res = ParseCastExpression(false);
904 if (!Res.isInvalid())
905 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
908 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
909 if (!getLangOpts().C11)
910 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
912 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
913 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
914 // unary-expression: '__alignof' '(' type-name ')'
915 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
916 // unary-expression: 'sizeof' '(' type-name ')'
917 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
918 return ParseUnaryExprOrTypeTraitExpression();
919 case tok::ampamp: { // unary-expression: '&&' identifier
920 SourceLocation AmpAmpLoc = ConsumeToken();
921 if (Tok.isNot(tok::identifier))
922 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
924 if (getCurScope()->getFnParent() == nullptr)
925 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
927 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
928 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
930 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
934 case tok::kw_const_cast:
935 case tok::kw_dynamic_cast:
936 case tok::kw_reinterpret_cast:
937 case tok::kw_static_cast:
938 Res = ParseCXXCasts();
941 Res = ParseCXXTypeid();
943 case tok::kw___uuidof:
944 Res = ParseCXXUuidof();
947 Res = ParseCXXThis();
950 case tok::annot_typename:
951 if (isStartOfObjCClassMessageMissingOpenBracket()) {
952 ParsedType Type = getTypeAnnotation(Tok);
954 // Fake up a Declarator to use with ActOnTypeName.
955 DeclSpec DS(AttrFactory);
956 DS.SetRangeStart(Tok.getLocation());
957 DS.SetRangeEnd(Tok.getLastLoc());
959 const char *PrevSpec = nullptr;
961 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
962 PrevSpec, DiagID, Type,
963 Actions.getASTContext().getPrintingPolicy());
965 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
966 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
971 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
977 case tok::annot_decltype:
979 case tok::kw_wchar_t:
980 case tok::kw_char16_t:
981 case tok::kw_char32_t:
986 case tok::kw___int64:
987 case tok::kw___int128:
989 case tok::kw_unsigned:
994 case tok::kw_typename:
996 case tok::kw___vector: {
997 if (!getLangOpts().CPlusPlus) {
998 Diag(Tok, diag::err_expected_expression);
1002 if (SavedKind == tok::kw_typename) {
1003 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1004 // typename-specifier braced-init-list
1005 if (TryAnnotateTypeOrScopeToken())
1008 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1009 // We are trying to parse a simple-type-specifier but might not get such
1010 // a token after error recovery.
1014 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1015 // simple-type-specifier braced-init-list
1017 DeclSpec DS(AttrFactory);
1019 ParseCXXSimpleTypeSpecifier(DS);
1020 if (Tok.isNot(tok::l_paren) &&
1021 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1022 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1023 << DS.getSourceRange());
1025 if (Tok.is(tok::l_brace))
1026 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1028 Res = ParseCXXTypeConstructExpression(DS);
1032 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1033 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1034 // (We can end up in this situation after tentative parsing.)
1035 if (TryAnnotateTypeOrScopeToken())
1037 if (!Tok.is(tok::annot_cxxscope))
1038 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1039 NotCastExpr, isTypeCast);
1041 Token Next = NextToken();
1042 if (Next.is(tok::annot_template_id)) {
1043 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1044 if (TemplateId->Kind == TNK_Type_template) {
1045 // We have a qualified template-id that we know refers to a
1046 // type, translate it into a type and continue parsing as a
1049 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1050 /*EnteringContext=*/false);
1051 AnnotateTemplateIdTokenAsType();
1052 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1053 NotCastExpr, isTypeCast);
1057 // Parse as an id-expression.
1058 Res = ParseCXXIdExpression(isAddressOfOperand);
1062 case tok::annot_template_id: { // [C++] template-id
1063 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1064 if (TemplateId->Kind == TNK_Type_template) {
1065 // We have a template-id that we know refers to a type,
1066 // translate it into a type and continue parsing as a cast
1068 AnnotateTemplateIdTokenAsType();
1069 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1070 NotCastExpr, isTypeCast);
1073 // Fall through to treat the template-id as an id-expression.
1076 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1077 Res = ParseCXXIdExpression(isAddressOfOperand);
1080 case tok::coloncolon: {
1081 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1082 // annotates the token, tail recurse.
1083 if (TryAnnotateTypeOrScopeToken())
1085 if (!Tok.is(tok::coloncolon))
1086 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1088 // ::new -> [C++] new-expression
1089 // ::delete -> [C++] delete-expression
1090 SourceLocation CCLoc = ConsumeToken();
1091 if (Tok.is(tok::kw_new))
1092 return ParseCXXNewExpression(true, CCLoc);
1093 if (Tok.is(tok::kw_delete))
1094 return ParseCXXDeleteExpression(true, CCLoc);
1096 // This is not a type name or scope specifier, it is an invalid expression.
1097 Diag(CCLoc, diag::err_expected_expression);
1101 case tok::kw_new: // [C++] new-expression
1102 return ParseCXXNewExpression(false, Tok.getLocation());
1104 case tok::kw_delete: // [C++] delete-expression
1105 return ParseCXXDeleteExpression(false, Tok.getLocation());
1107 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1108 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1109 SourceLocation KeyLoc = ConsumeToken();
1110 BalancedDelimiterTracker T(*this, tok::l_paren);
1112 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1114 // C++11 [expr.unary.noexcept]p1:
1115 // The noexcept operator determines whether the evaluation of its operand,
1116 // which is an unevaluated operand, can throw an exception.
1117 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1118 ExprResult Result = ParseExpression();
1122 if (!Result.isInvalid())
1123 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1124 Result.get(), T.getCloseLocation());
1128 #define TYPE_TRAIT(N,Spelling,K) \
1129 case tok::kw_##Spelling:
1130 #include "clang/Basic/TokenKinds.def"
1131 return ParseTypeTrait();
1133 case tok::kw___array_rank:
1134 case tok::kw___array_extent:
1135 return ParseArrayTypeTrait();
1137 case tok::kw___is_lvalue_expr:
1138 case tok::kw___is_rvalue_expr:
1139 return ParseExpressionTrait();
1142 SourceLocation AtLoc = ConsumeToken();
1143 return ParseObjCAtExpression(AtLoc);
1146 Res = ParseBlockLiteralExpression();
1148 case tok::code_completion: {
1149 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1154 if (getLangOpts().CPlusPlus11) {
1155 if (getLangOpts().ObjC1) {
1156 // C++11 lambda expressions and Objective-C message sends both start with a
1157 // square bracket. There are three possibilities here:
1158 // we have a valid lambda expression, we have an invalid lambda
1159 // expression, or we have something that doesn't appear to be a lambda.
1160 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1161 Res = TryParseLambdaExpression();
1162 if (!Res.isInvalid() && !Res.get())
1163 Res = ParseObjCMessageExpression();
1166 Res = ParseLambdaExpression();
1169 if (getLangOpts().ObjC1) {
1170 Res = ParseObjCMessageExpression();
1179 // These can be followed by postfix-expr pieces.
1180 return ParsePostfixExpressionSuffix(Res);
1183 /// \brief Once the leading part of a postfix-expression is parsed, this
1184 /// method parses any suffixes that apply.
1187 /// postfix-expression: [C99 6.5.2]
1188 /// primary-expression
1189 /// postfix-expression '[' expression ']'
1190 /// postfix-expression '[' braced-init-list ']'
1191 /// postfix-expression '(' argument-expression-list[opt] ')'
1192 /// postfix-expression '.' identifier
1193 /// postfix-expression '->' identifier
1194 /// postfix-expression '++'
1195 /// postfix-expression '--'
1196 /// '(' type-name ')' '{' initializer-list '}'
1197 /// '(' type-name ')' '{' initializer-list ',' '}'
1199 /// argument-expression-list: [C99 6.5.2]
1200 /// argument-expression ...[opt]
1201 /// argument-expression-list ',' assignment-expression ...[opt]
1204 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1205 // Now that the primary-expression piece of the postfix-expression has been
1206 // parsed, see if there are any postfix-expression pieces here.
1209 switch (Tok.getKind()) {
1210 case tok::code_completion:
1211 if (InMessageExpression)
1214 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1218 case tok::identifier:
1219 // If we see identifier: after an expression, and we're not already in a
1220 // message send, then this is probably a message send with a missing
1221 // opening bracket '['.
1222 if (getLangOpts().ObjC1 && !InMessageExpression &&
1223 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1224 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1225 ParsedType(), LHS.get());
1229 // Fall through; this isn't a message send.
1231 default: // Not a postfix-expression suffix.
1233 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1234 // If we have a array postfix expression that starts on a new line and
1235 // Objective-C is enabled, it is highly likely that the user forgot a
1236 // semicolon after the base expression and that the array postfix-expr is
1237 // actually another message send. In this case, do some look-ahead to see
1238 // if the contents of the square brackets are obviously not a valid
1239 // expression and recover by pretending there is no suffix.
1240 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1241 isSimpleObjCMessageExpression())
1244 // Reject array indices starting with a lambda-expression. '[[' is
1245 // reserved for attributes.
1246 if (CheckProhibitedCXX11Attribute())
1249 BalancedDelimiterTracker T(*this, tok::l_square);
1251 Loc = T.getOpenLocation();
1253 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1254 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1255 Idx = ParseBraceInitializer();
1257 Idx = ParseExpression();
1259 SourceLocation RLoc = Tok.getLocation();
1261 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
1262 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1272 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1273 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1274 // '(' argument-expression-list[opt] ')'
1275 tok::TokenKind OpKind = Tok.getKind();
1276 InMessageExpressionRAIIObject InMessage(*this, false);
1278 Expr *ExecConfig = nullptr;
1280 BalancedDelimiterTracker PT(*this, tok::l_paren);
1282 if (OpKind == tok::lesslessless) {
1283 ExprVector ExecConfigExprs;
1284 CommaLocsTy ExecConfigCommaLocs;
1285 SourceLocation OpenLoc = ConsumeToken();
1287 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1291 SourceLocation CloseLoc;
1292 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1293 } else if (LHS.isInvalid()) {
1294 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1296 // There was an error closing the brackets
1297 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1298 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1299 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1303 if (!LHS.isInvalid()) {
1304 if (ExpectAndConsume(tok::l_paren))
1307 Loc = PrevTokLocation;
1310 if (!LHS.isInvalid()) {
1311 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1315 if (ECResult.isInvalid())
1318 ExecConfig = ECResult.get();
1322 Loc = PT.getOpenLocation();
1325 ExprVector ArgExprs;
1326 CommaLocsTy CommaLocs;
1328 if (Tok.is(tok::code_completion)) {
1329 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1334 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1335 if (Tok.isNot(tok::r_paren)) {
1336 if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall,
1344 if (LHS.isInvalid()) {
1345 SkipUntil(tok::r_paren, StopAtSemi);
1346 } else if (Tok.isNot(tok::r_paren)) {
1350 assert((ArgExprs.size() == 0 ||
1351 ArgExprs.size()-1 == CommaLocs.size())&&
1352 "Unexpected number of commas!");
1353 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1354 ArgExprs, Tok.getLocation(),
1363 // postfix-expression: p-e '->' template[opt] id-expression
1364 // postfix-expression: p-e '.' template[opt] id-expression
1365 tok::TokenKind OpKind = Tok.getKind();
1366 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1369 ParsedType ObjectType;
1370 bool MayBePseudoDestructor = false;
1371 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1372 Expr *Base = LHS.get();
1373 const Type* BaseType = Base->getType().getTypePtrOrNull();
1374 if (BaseType && Tok.is(tok::l_paren) &&
1375 (BaseType->isFunctionType() ||
1376 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1377 Diag(OpLoc, diag::err_function_is_not_record)
1378 << OpKind << Base->getSourceRange()
1379 << FixItHint::CreateRemoval(OpLoc);
1380 return ParsePostfixExpressionSuffix(Base);
1383 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1384 OpLoc, OpKind, ObjectType,
1385 MayBePseudoDestructor);
1386 if (LHS.isInvalid())
1389 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1390 /*EnteringContext=*/false,
1391 &MayBePseudoDestructor);
1392 if (SS.isNotEmpty())
1393 ObjectType = ParsedType();
1396 if (Tok.is(tok::code_completion)) {
1397 // Code completion for a member access expression.
1398 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1399 OpLoc, OpKind == tok::arrow);
1405 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1406 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1411 // Either the action has told is that this cannot be a
1412 // pseudo-destructor expression (based on the type of base
1413 // expression), or we didn't see a '~' in the right place. We
1414 // can still parse a destructor name here, but in that case it
1415 // names a real destructor.
1416 // Allow explicit constructor calls in Microsoft mode.
1417 // FIXME: Add support for explicit call of template constructor.
1418 SourceLocation TemplateKWLoc;
1420 if (getLangOpts().ObjC2 && OpKind == tok::period && Tok.is(tok::kw_class)) {
1422 // After a '.' in a member access expression, treat the keyword
1423 // 'class' as if it were an identifier.
1425 // This hack allows property access to the 'class' method because it is
1426 // such a common method name. For other C++ keywords that are
1427 // Objective-C method names, one must use the message send syntax.
1428 IdentifierInfo *Id = Tok.getIdentifierInfo();
1429 SourceLocation Loc = ConsumeToken();
1430 Name.setIdentifier(Id, Loc);
1431 } else if (ParseUnqualifiedId(SS,
1432 /*EnteringContext=*/false,
1433 /*AllowDestructorName=*/true,
1434 /*AllowConstructorName=*/
1435 getLangOpts().MicrosoftExt,
1436 ObjectType, TemplateKWLoc, Name))
1439 if (!LHS.isInvalid())
1440 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1441 OpKind, SS, TemplateKWLoc, Name,
1442 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1444 Tok.is(tok::l_paren));
1447 case tok::plusplus: // postfix-expression: postfix-expression '++'
1448 case tok::minusminus: // postfix-expression: postfix-expression '--'
1449 if (!LHS.isInvalid()) {
1450 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1451 Tok.getKind(), LHS.get());
1459 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1460 /// vec_step and we are at the start of an expression or a parenthesized
1461 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1462 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1465 /// unary-expression: [C99 6.5.3]
1466 /// 'sizeof' unary-expression
1467 /// 'sizeof' '(' type-name ')'
1468 /// [GNU] '__alignof' unary-expression
1469 /// [GNU] '__alignof' '(' type-name ')'
1470 /// [C11] '_Alignof' '(' type-name ')'
1471 /// [C++0x] 'alignof' '(' type-id ')'
1473 /// [GNU] typeof-specifier:
1474 /// typeof ( expressions )
1475 /// typeof ( type-name )
1476 /// [GNU/C++] typeof unary-expression
1478 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1479 /// vec_step ( expressions )
1480 /// vec_step ( type-name )
1483 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1486 SourceRange &CastRange) {
1488 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) ||
1489 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) ||
1490 OpTok.is(tok::kw__Alignof) || OpTok.is(tok::kw_vec_step)) &&
1491 "Not a typeof/sizeof/alignof/vec_step expression!");
1495 // If the operand doesn't start with an '(', it must be an expression.
1496 if (Tok.isNot(tok::l_paren)) {
1497 // If construct allows a form without parenthesis, user may forget to put
1498 // pathenthesis around type name.
1499 if (OpTok.is(tok::kw_sizeof) || OpTok.is(tok::kw___alignof) ||
1500 OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof)) {
1501 if (isTypeIdUnambiguously()) {
1502 DeclSpec DS(AttrFactory);
1503 ParseSpecifierQualifierList(DS);
1504 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1505 ParseDeclarator(DeclaratorInfo);
1507 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1508 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1509 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1511 << FixItHint::CreateInsertion(LParenLoc, "(")
1512 << FixItHint::CreateInsertion(RParenLoc, ")");
1519 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1520 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1525 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1527 // If it starts with a '(', we know that it is either a parenthesized
1528 // type-name, or it is a unary-expression that starts with a compound
1529 // literal, or starts with a primary-expression that is a parenthesized
1531 ParenParseOption ExprType = CastExpr;
1532 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1534 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1535 false, CastTy, RParenLoc);
1536 CastRange = SourceRange(LParenLoc, RParenLoc);
1538 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1540 if (ExprType == CastExpr) {
1545 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1546 // GNU typeof in C requires the expression to be parenthesized. Not so for
1547 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1548 // the start of a unary-expression, but doesn't include any postfix
1549 // pieces. Parse these now if present.
1550 if (!Operand.isInvalid())
1551 Operand = ParsePostfixExpressionSuffix(Operand.get());
1555 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1561 /// \brief Parse a sizeof or alignof expression.
1564 /// unary-expression: [C99 6.5.3]
1565 /// 'sizeof' unary-expression
1566 /// 'sizeof' '(' type-name ')'
1567 /// [C++11] 'sizeof' '...' '(' identifier ')'
1568 /// [GNU] '__alignof' unary-expression
1569 /// [GNU] '__alignof' '(' type-name ')'
1570 /// [C11] '_Alignof' '(' type-name ')'
1571 /// [C++11] 'alignof' '(' type-id ')'
1573 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1574 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) ||
1575 Tok.is(tok::kw_alignof) || Tok.is(tok::kw__Alignof) ||
1576 Tok.is(tok::kw_vec_step)) &&
1577 "Not a sizeof/alignof/vec_step expression!");
1581 // [C++11] 'sizeof' '...' '(' identifier ')'
1582 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1583 SourceLocation EllipsisLoc = ConsumeToken();
1584 SourceLocation LParenLoc, RParenLoc;
1585 IdentifierInfo *Name = nullptr;
1586 SourceLocation NameLoc;
1587 if (Tok.is(tok::l_paren)) {
1588 BalancedDelimiterTracker T(*this, tok::l_paren);
1590 LParenLoc = T.getOpenLocation();
1591 if (Tok.is(tok::identifier)) {
1592 Name = Tok.getIdentifierInfo();
1593 NameLoc = ConsumeToken();
1595 RParenLoc = T.getCloseLocation();
1596 if (RParenLoc.isInvalid())
1597 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1599 Diag(Tok, diag::err_expected_parameter_pack);
1600 SkipUntil(tok::r_paren, StopAtSemi);
1602 } else if (Tok.is(tok::identifier)) {
1603 Name = Tok.getIdentifierInfo();
1604 NameLoc = ConsumeToken();
1605 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1606 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1607 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1609 << FixItHint::CreateInsertion(LParenLoc, "(")
1610 << FixItHint::CreateInsertion(RParenLoc, ")");
1612 Diag(Tok, diag::err_sizeof_parameter_pack);
1618 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1619 Sema::ReuseLambdaContextDecl);
1621 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1622 OpTok.getLocation(),
1627 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof))
1628 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1630 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1631 Sema::ReuseLambdaContextDecl);
1635 SourceRange CastRange;
1636 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1641 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1642 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof) ||
1643 OpTok.is(tok::kw__Alignof))
1644 ExprKind = UETT_AlignOf;
1645 else if (OpTok.is(tok::kw_vec_step))
1646 ExprKind = UETT_VecStep;
1649 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1652 CastTy.getAsOpaquePtr(),
1655 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof))
1656 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1658 // If we get here, the operand to the sizeof/alignof was an expresion.
1659 if (!Operand.isInvalid())
1660 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1668 /// ParseBuiltinPrimaryExpression
1671 /// primary-expression: [C99 6.5.1]
1672 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1673 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1674 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1676 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1677 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1679 /// [GNU] offsetof-member-designator:
1680 /// [GNU] identifier
1681 /// [GNU] offsetof-member-designator '.' identifier
1682 /// [GNU] offsetof-member-designator '[' expression ']'
1684 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1686 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1688 tok::TokenKind T = Tok.getKind();
1689 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
1691 // All of these start with an open paren.
1692 if (Tok.isNot(tok::l_paren))
1693 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
1696 BalancedDelimiterTracker PT(*this, tok::l_paren);
1702 default: llvm_unreachable("Not a builtin primary expression!");
1703 case tok::kw___builtin_va_arg: {
1704 ExprResult Expr(ParseAssignmentExpression());
1706 if (ExpectAndConsume(tok::comma)) {
1707 SkipUntil(tok::r_paren, StopAtSemi);
1711 TypeResult Ty = ParseTypeName();
1713 if (Tok.isNot(tok::r_paren)) {
1714 Diag(Tok, diag::err_expected) << tok::r_paren;
1718 if (Expr.isInvalid() || Ty.isInvalid())
1721 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
1724 case tok::kw___builtin_offsetof: {
1725 SourceLocation TypeLoc = Tok.getLocation();
1726 TypeResult Ty = ParseTypeName();
1727 if (Ty.isInvalid()) {
1728 SkipUntil(tok::r_paren, StopAtSemi);
1732 if (ExpectAndConsume(tok::comma)) {
1733 SkipUntil(tok::r_paren, StopAtSemi);
1737 // We must have at least one identifier here.
1738 if (Tok.isNot(tok::identifier)) {
1739 Diag(Tok, diag::err_expected) << tok::identifier;
1740 SkipUntil(tok::r_paren, StopAtSemi);
1744 // Keep track of the various subcomponents we see.
1745 SmallVector<Sema::OffsetOfComponent, 4> Comps;
1747 Comps.push_back(Sema::OffsetOfComponent());
1748 Comps.back().isBrackets = false;
1749 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1750 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1752 // FIXME: This loop leaks the index expressions on error.
1754 if (Tok.is(tok::period)) {
1755 // offsetof-member-designator: offsetof-member-designator '.' identifier
1756 Comps.push_back(Sema::OffsetOfComponent());
1757 Comps.back().isBrackets = false;
1758 Comps.back().LocStart = ConsumeToken();
1760 if (Tok.isNot(tok::identifier)) {
1761 Diag(Tok, diag::err_expected) << tok::identifier;
1762 SkipUntil(tok::r_paren, StopAtSemi);
1765 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1766 Comps.back().LocEnd = ConsumeToken();
1768 } else if (Tok.is(tok::l_square)) {
1769 if (CheckProhibitedCXX11Attribute())
1772 // offsetof-member-designator: offsetof-member-design '[' expression ']'
1773 Comps.push_back(Sema::OffsetOfComponent());
1774 Comps.back().isBrackets = true;
1775 BalancedDelimiterTracker ST(*this, tok::l_square);
1777 Comps.back().LocStart = ST.getOpenLocation();
1778 Res = ParseExpression();
1779 if (Res.isInvalid()) {
1780 SkipUntil(tok::r_paren, StopAtSemi);
1783 Comps.back().U.E = Res.get();
1786 Comps.back().LocEnd = ST.getCloseLocation();
1788 if (Tok.isNot(tok::r_paren)) {
1791 } else if (Ty.isInvalid()) {
1795 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
1796 Ty.get(), &Comps[0], Comps.size(),
1797 PT.getCloseLocation());
1804 case tok::kw___builtin_choose_expr: {
1805 ExprResult Cond(ParseAssignmentExpression());
1806 if (Cond.isInvalid()) {
1807 SkipUntil(tok::r_paren, StopAtSemi);
1810 if (ExpectAndConsume(tok::comma)) {
1811 SkipUntil(tok::r_paren, StopAtSemi);
1815 ExprResult Expr1(ParseAssignmentExpression());
1816 if (Expr1.isInvalid()) {
1817 SkipUntil(tok::r_paren, StopAtSemi);
1820 if (ExpectAndConsume(tok::comma)) {
1821 SkipUntil(tok::r_paren, StopAtSemi);
1825 ExprResult Expr2(ParseAssignmentExpression());
1826 if (Expr2.isInvalid()) {
1827 SkipUntil(tok::r_paren, StopAtSemi);
1830 if (Tok.isNot(tok::r_paren)) {
1831 Diag(Tok, diag::err_expected) << tok::r_paren;
1834 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
1835 Expr2.get(), ConsumeParen());
1838 case tok::kw___builtin_astype: {
1839 // The first argument is an expression to be converted, followed by a comma.
1840 ExprResult Expr(ParseAssignmentExpression());
1841 if (Expr.isInvalid()) {
1842 SkipUntil(tok::r_paren, StopAtSemi);
1846 if (ExpectAndConsume(tok::comma)) {
1847 SkipUntil(tok::r_paren, StopAtSemi);
1851 // Second argument is the type to bitcast to.
1852 TypeResult DestTy = ParseTypeName();
1853 if (DestTy.isInvalid())
1856 // Attempt to consume the r-paren.
1857 if (Tok.isNot(tok::r_paren)) {
1858 Diag(Tok, diag::err_expected) << tok::r_paren;
1859 SkipUntil(tok::r_paren, StopAtSemi);
1863 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
1867 case tok::kw___builtin_convertvector: {
1868 // The first argument is an expression to be converted, followed by a comma.
1869 ExprResult Expr(ParseAssignmentExpression());
1870 if (Expr.isInvalid()) {
1871 SkipUntil(tok::r_paren, StopAtSemi);
1875 if (ExpectAndConsume(tok::comma)) {
1876 SkipUntil(tok::r_paren, StopAtSemi);
1880 // Second argument is the type to bitcast to.
1881 TypeResult DestTy = ParseTypeName();
1882 if (DestTy.isInvalid())
1885 // Attempt to consume the r-paren.
1886 if (Tok.isNot(tok::r_paren)) {
1887 Diag(Tok, diag::err_expected) << tok::r_paren;
1888 SkipUntil(tok::r_paren, StopAtSemi);
1892 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
1898 if (Res.isInvalid())
1901 // These can be followed by postfix-expr pieces because they are
1902 // primary-expressions.
1903 return ParsePostfixExpressionSuffix(Res.get());
1906 /// ParseParenExpression - This parses the unit that starts with a '(' token,
1907 /// based on what is allowed by ExprType. The actual thing parsed is returned
1908 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
1909 /// not the parsed cast-expression.
1912 /// primary-expression: [C99 6.5.1]
1913 /// '(' expression ')'
1914 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
1915 /// postfix-expression: [C99 6.5.2]
1916 /// '(' type-name ')' '{' initializer-list '}'
1917 /// '(' type-name ')' '{' initializer-list ',' '}'
1918 /// cast-expression: [C99 6.5.4]
1919 /// '(' type-name ')' cast-expression
1920 /// [ARC] bridged-cast-expression
1922 /// [ARC] bridged-cast-expression:
1923 /// (__bridge type-name) cast-expression
1924 /// (__bridge_transfer type-name) cast-expression
1925 /// (__bridge_retained type-name) cast-expression
1928 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
1929 bool isTypeCast, ParsedType &CastTy,
1930 SourceLocation &RParenLoc) {
1931 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
1932 ColonProtectionRAIIObject ColonProtection(*this, false);
1933 BalancedDelimiterTracker T(*this, tok::l_paren);
1934 if (T.consumeOpen())
1936 SourceLocation OpenLoc = T.getOpenLocation();
1938 ExprResult Result(true);
1939 bool isAmbiguousTypeId;
1940 CastTy = ParsedType();
1942 if (Tok.is(tok::code_completion)) {
1943 Actions.CodeCompleteOrdinaryName(getCurScope(),
1944 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
1945 : Sema::PCC_Expression);
1950 // Diagnose use of bridge casts in non-arc mode.
1951 bool BridgeCast = (getLangOpts().ObjC2 &&
1952 (Tok.is(tok::kw___bridge) ||
1953 Tok.is(tok::kw___bridge_transfer) ||
1954 Tok.is(tok::kw___bridge_retained) ||
1955 Tok.is(tok::kw___bridge_retain)));
1956 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
1957 if (!TryConsumeToken(tok::kw___bridge)) {
1958 StringRef BridgeCastName = Tok.getName();
1959 SourceLocation BridgeKeywordLoc = ConsumeToken();
1960 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
1961 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
1963 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
1968 // None of these cases should fall through with an invalid Result
1969 // unless they've already reported an error.
1970 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
1971 Diag(Tok, diag::ext_gnu_statement_expr);
1972 Actions.ActOnStartStmtExpr();
1974 StmtResult Stmt(ParseCompoundStatement(true));
1975 ExprType = CompoundStmt;
1977 // If the substmt parsed correctly, build the AST node.
1978 if (!Stmt.isInvalid()) {
1979 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
1981 Actions.ActOnStmtExprError();
1983 } else if (ExprType >= CompoundLiteral && BridgeCast) {
1984 tok::TokenKind tokenKind = Tok.getKind();
1985 SourceLocation BridgeKeywordLoc = ConsumeToken();
1987 // Parse an Objective-C ARC ownership cast expression.
1988 ObjCBridgeCastKind Kind;
1989 if (tokenKind == tok::kw___bridge)
1991 else if (tokenKind == tok::kw___bridge_transfer)
1992 Kind = OBC_BridgeTransfer;
1993 else if (tokenKind == tok::kw___bridge_retained)
1994 Kind = OBC_BridgeRetained;
1996 // As a hopefully temporary workaround, allow __bridge_retain as
1997 // a synonym for __bridge_retained, but only in system headers.
1998 assert(tokenKind == tok::kw___bridge_retain);
1999 Kind = OBC_BridgeRetained;
2000 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2001 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2002 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2003 "__bridge_retained");
2006 TypeResult Ty = ParseTypeName();
2008 ColonProtection.restore();
2009 RParenLoc = T.getCloseLocation();
2010 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2012 if (Ty.isInvalid() || SubExpr.isInvalid())
2015 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2016 BridgeKeywordLoc, Ty.get(),
2017 RParenLoc, SubExpr.get());
2018 } else if (ExprType >= CompoundLiteral &&
2019 isTypeIdInParens(isAmbiguousTypeId)) {
2021 // Otherwise, this is a compound literal expression or cast expression.
2023 // In C++, if the type-id is ambiguous we disambiguate based on context.
2024 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2025 // in which case we should treat it as type-id.
2026 // if stopIfCastExpr is false, we need to determine the context past the
2027 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2028 if (isAmbiguousTypeId && !stopIfCastExpr) {
2029 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2031 RParenLoc = T.getCloseLocation();
2035 // Parse the type declarator.
2036 DeclSpec DS(AttrFactory);
2037 ParseSpecifierQualifierList(DS);
2038 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2039 ParseDeclarator(DeclaratorInfo);
2041 // If our type is followed by an identifier and either ':' or ']', then
2042 // this is probably an Objective-C message send where the leading '[' is
2043 // missing. Recover as if that were the case.
2044 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2045 !InMessageExpression && getLangOpts().ObjC1 &&
2046 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2049 InMessageExpressionRAIIObject InMessage(*this, false);
2050 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2052 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2058 ColonProtection.restore();
2059 RParenLoc = T.getCloseLocation();
2060 if (Tok.is(tok::l_brace)) {
2061 ExprType = CompoundLiteral;
2064 InMessageExpressionRAIIObject InMessage(*this, false);
2065 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2067 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2070 if (ExprType == CastExpr) {
2071 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2073 if (DeclaratorInfo.isInvalidType())
2076 // Note that this doesn't parse the subsequent cast-expression, it just
2077 // returns the parsed type to the callee.
2078 if (stopIfCastExpr) {
2081 InMessageExpressionRAIIObject InMessage(*this, false);
2082 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2085 return ExprResult();
2088 // Reject the cast of super idiom in ObjC.
2089 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2090 Tok.getIdentifierInfo() == Ident_super &&
2091 getCurScope()->isInObjcMethodScope() &&
2092 GetLookAheadToken(1).isNot(tok::period)) {
2093 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2094 << SourceRange(OpenLoc, RParenLoc);
2098 // Parse the cast-expression that follows it next.
2099 // TODO: For cast expression with CastTy.
2100 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2101 /*isAddressOfOperand=*/false,
2102 /*isTypeCast=*/IsTypeCast);
2103 if (!Result.isInvalid()) {
2104 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2105 DeclaratorInfo, CastTy,
2106 RParenLoc, Result.get());
2111 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2114 } else if (isTypeCast) {
2115 // Parse the expression-list.
2116 InMessageExpressionRAIIObject InMessage(*this, false);
2118 ExprVector ArgExprs;
2119 CommaLocsTy CommaLocs;
2121 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2122 ExprType = SimpleExpr;
2123 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2127 InMessageExpressionRAIIObject InMessage(*this, false);
2129 Result = ParseExpression(MaybeTypeCast);
2130 ExprType = SimpleExpr;
2132 // Don't build a paren expression unless we actually match a ')'.
2133 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2135 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2139 if (Result.isInvalid()) {
2140 SkipUntil(tok::r_paren, StopAtSemi);
2145 RParenLoc = T.getCloseLocation();
2149 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2150 /// and we are at the left brace.
2153 /// postfix-expression: [C99 6.5.2]
2154 /// '(' type-name ')' '{' initializer-list '}'
2155 /// '(' type-name ')' '{' initializer-list ',' '}'
2158 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2159 SourceLocation LParenLoc,
2160 SourceLocation RParenLoc) {
2161 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2162 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2163 Diag(LParenLoc, diag::ext_c99_compound_literal);
2164 ExprResult Result = ParseInitializer();
2165 if (!Result.isInvalid() && Ty)
2166 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2170 /// ParseStringLiteralExpression - This handles the various token types that
2171 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2172 /// translation phase #6].
2175 /// primary-expression: [C99 6.5.1]
2178 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2179 assert(isTokenStringLiteral() && "Not a string literal!");
2181 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2182 // considered to be strings for concatenation purposes.
2183 SmallVector<Token, 4> StringToks;
2186 StringToks.push_back(Tok);
2187 ConsumeStringToken();
2188 } while (isTokenStringLiteral());
2190 // Pass the set of string tokens, ready for concatenation, to the actions.
2191 return Actions.ActOnStringLiteral(StringToks,
2192 AllowUserDefinedLiteral ? getCurScope()
2196 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2200 /// generic-selection:
2201 /// _Generic ( assignment-expression , generic-assoc-list )
2202 /// generic-assoc-list:
2203 /// generic-association
2204 /// generic-assoc-list , generic-association
2205 /// generic-association:
2206 /// type-name : assignment-expression
2207 /// default : assignment-expression
2209 ExprResult Parser::ParseGenericSelectionExpression() {
2210 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2211 SourceLocation KeyLoc = ConsumeToken();
2213 if (!getLangOpts().C11)
2214 Diag(KeyLoc, diag::ext_c11_generic_selection);
2216 BalancedDelimiterTracker T(*this, tok::l_paren);
2217 if (T.expectAndConsume())
2220 ExprResult ControllingExpr;
2222 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2224 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2225 ControllingExpr = ParseAssignmentExpression();
2226 if (ControllingExpr.isInvalid()) {
2227 SkipUntil(tok::r_paren, StopAtSemi);
2232 if (ExpectAndConsume(tok::comma)) {
2233 SkipUntil(tok::r_paren, StopAtSemi);
2237 SourceLocation DefaultLoc;
2242 if (Tok.is(tok::kw_default)) {
2243 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2244 // generic association."
2245 if (!DefaultLoc.isInvalid()) {
2246 Diag(Tok, diag::err_duplicate_default_assoc);
2247 Diag(DefaultLoc, diag::note_previous_default_assoc);
2248 SkipUntil(tok::r_paren, StopAtSemi);
2251 DefaultLoc = ConsumeToken();
2254 ColonProtectionRAIIObject X(*this);
2255 TypeResult TR = ParseTypeName();
2256 if (TR.isInvalid()) {
2257 SkipUntil(tok::r_paren, StopAtSemi);
2262 Types.push_back(Ty);
2264 if (ExpectAndConsume(tok::colon)) {
2265 SkipUntil(tok::r_paren, StopAtSemi);
2269 // FIXME: These expressions should be parsed in a potentially potentially
2270 // evaluated context.
2271 ExprResult ER(ParseAssignmentExpression());
2272 if (ER.isInvalid()) {
2273 SkipUntil(tok::r_paren, StopAtSemi);
2276 Exprs.push_back(ER.get());
2277 } while (TryConsumeToken(tok::comma));
2280 if (T.getCloseLocation().isInvalid())
2283 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2284 T.getCloseLocation(),
2285 ControllingExpr.get(),
2289 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2292 /// argument-expression-list:
2293 /// assignment-expression
2294 /// argument-expression-list , assignment-expression
2296 /// [C++] expression-list:
2297 /// [C++] assignment-expression
2298 /// [C++] expression-list , assignment-expression
2300 /// [C++0x] expression-list:
2301 /// [C++0x] initializer-list
2303 /// [C++0x] initializer-list
2304 /// [C++0x] initializer-clause ...[opt]
2305 /// [C++0x] initializer-list , initializer-clause ...[opt]
2307 /// [C++0x] initializer-clause:
2308 /// [C++0x] assignment-expression
2309 /// [C++0x] braced-init-list
2311 bool Parser::ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
2312 SmallVectorImpl<SourceLocation> &CommaLocs,
2313 void (Sema::*Completer)(Scope *S,
2315 ArrayRef<Expr *> Args),
2317 bool SawError = false;
2319 if (Tok.is(tok::code_completion)) {
2321 (Actions.*Completer)(getCurScope(), Data, Exprs);
2323 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2329 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2330 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2331 Expr = ParseBraceInitializer();
2333 Expr = ParseAssignmentExpression();
2335 if (Tok.is(tok::ellipsis))
2336 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2337 if (Expr.isInvalid()) {
2338 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2341 Exprs.push_back(Expr.get());
2344 if (Tok.isNot(tok::comma))
2346 // Move to the next argument, remember where the comma was.
2347 CommaLocs.push_back(ConsumeToken());
2351 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2352 /// used for misc language extensions.
2355 /// simple-expression-list:
2356 /// assignment-expression
2357 /// simple-expression-list , assignment-expression
2360 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2361 SmallVectorImpl<SourceLocation> &CommaLocs) {
2363 ExprResult Expr = ParseAssignmentExpression();
2364 if (Expr.isInvalid())
2367 Exprs.push_back(Expr.get());
2369 if (Tok.isNot(tok::comma))
2372 // Move to the next argument, remember where the comma was.
2373 CommaLocs.push_back(ConsumeToken());
2377 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2380 /// [clang] block-id:
2381 /// [clang] specifier-qualifier-list block-declarator
2383 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2384 if (Tok.is(tok::code_completion)) {
2385 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2386 return cutOffParsing();
2389 // Parse the specifier-qualifier-list piece.
2390 DeclSpec DS(AttrFactory);
2391 ParseSpecifierQualifierList(DS);
2393 // Parse the block-declarator.
2394 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2395 ParseDeclarator(DeclaratorInfo);
2397 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes.
2398 DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation());
2400 MaybeParseGNUAttributes(DeclaratorInfo);
2402 // Inform sema that we are starting a block.
2403 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2406 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2407 /// like ^(int x){ return x+1; }
2411 /// [clang] '^' block-args[opt] compound-statement
2412 /// [clang] '^' block-id compound-statement
2413 /// [clang] block-args:
2414 /// [clang] '(' parameter-list ')'
2416 ExprResult Parser::ParseBlockLiteralExpression() {
2417 assert(Tok.is(tok::caret) && "block literal starts with ^");
2418 SourceLocation CaretLoc = ConsumeToken();
2420 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2421 "block literal parsing");
2423 // Enter a scope to hold everything within the block. This includes the
2424 // argument decls, decls within the compound expression, etc. This also
2425 // allows determining whether a variable reference inside the block is
2426 // within or outside of the block.
2427 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2430 // Inform sema that we are starting a block.
2431 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2433 // Parse the return type if present.
2434 DeclSpec DS(AttrFactory);
2435 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2436 // FIXME: Since the return type isn't actually parsed, it can't be used to
2437 // fill ParamInfo with an initial valid range, so do it manually.
2438 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2440 // If this block has arguments, parse them. There is no ambiguity here with
2441 // the expression case, because the expression case requires a parameter list.
2442 if (Tok.is(tok::l_paren)) {
2443 ParseParenDeclarator(ParamInfo);
2444 // Parse the pieces after the identifier as if we had "int(...)".
2445 // SetIdentifier sets the source range end, but in this case we're past
2447 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2448 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2449 ParamInfo.SetRangeEnd(Tmp);
2450 if (ParamInfo.isInvalidType()) {
2451 // If there was an error parsing the arguments, they may have
2452 // tried to use ^(x+y) which requires an argument list. Just
2453 // skip the whole block literal.
2454 Actions.ActOnBlockError(CaretLoc, getCurScope());
2458 MaybeParseGNUAttributes(ParamInfo);
2460 // Inform sema that we are starting a block.
2461 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2462 } else if (!Tok.is(tok::l_brace)) {
2463 ParseBlockId(CaretLoc);
2465 // Otherwise, pretend we saw (void).
2466 ParsedAttributes attrs(AttrFactory);
2467 SourceLocation NoLoc;
2468 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2469 /*IsAmbiguous=*/false,
2470 /*RParenLoc=*/NoLoc,
2471 /*ArgInfo=*/nullptr,
2473 /*EllipsisLoc=*/NoLoc,
2474 /*RParenLoc=*/NoLoc,
2476 /*RefQualifierIsLvalueRef=*/true,
2477 /*RefQualifierLoc=*/NoLoc,
2478 /*ConstQualifierLoc=*/NoLoc,
2479 /*VolatileQualifierLoc=*/NoLoc,
2480 /*MutableLoc=*/NoLoc,
2483 /*Exceptions=*/nullptr,
2484 /*ExceptionRanges=*/nullptr,
2485 /*NumExceptions=*/0,
2486 /*NoexceptExpr=*/nullptr,
2491 MaybeParseGNUAttributes(ParamInfo);
2493 // Inform sema that we are starting a block.
2494 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2498 ExprResult Result(true);
2499 if (!Tok.is(tok::l_brace)) {
2500 // Saw something like: ^expr
2501 Diag(Tok, diag::err_expected_expression);
2502 Actions.ActOnBlockError(CaretLoc, getCurScope());
2506 StmtResult Stmt(ParseCompoundStatementBody());
2508 if (!Stmt.isInvalid())
2509 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2511 Actions.ActOnBlockError(CaretLoc, getCurScope());
2515 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2519 ExprResult Parser::ParseObjCBoolLiteral() {
2520 tok::TokenKind Kind = Tok.getKind();
2521 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);