1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Provides the Expression parsing implementation.
12 /// Expressions in C99 basically consist of a bunch of binary operators with
13 /// unary operators and other random stuff at the leaves.
15 /// In the C99 grammar, these unary operators bind tightest and are represented
16 /// as the 'cast-expression' production. Everything else is either a binary
17 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
18 /// handled by ParseCastExpression, the higher level pieces are handled by
19 /// ParseBinaryExpression.
21 //===----------------------------------------------------------------------===//
23 #include "clang/Parse/Parser.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/Basic/PrettyStackTrace.h"
27 #include "clang/Parse/RAIIObjectsForParser.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/ParsedTemplate.h"
30 #include "clang/Sema/Scope.h"
31 #include "clang/Sema/TypoCorrection.h"
32 #include "llvm/ADT/SmallVector.h"
33 using namespace clang;
35 /// Simple precedence-based parser for binary/ternary operators.
37 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
38 /// production. C99 specifies that the LHS of an assignment operator should be
39 /// parsed as a unary-expression, but consistency dictates that it be a
40 /// conditional-expession. In practice, the important thing here is that the
41 /// LHS of an assignment has to be an l-value, which productions between
42 /// unary-expression and conditional-expression don't produce. Because we want
43 /// consistency, we parse the LHS as a conditional-expression, then check for
44 /// l-value-ness in semantic analysis stages.
47 /// pm-expression: [C++ 5.5]
49 /// pm-expression '.*' cast-expression
50 /// pm-expression '->*' cast-expression
52 /// multiplicative-expression: [C99 6.5.5]
53 /// Note: in C++, apply pm-expression instead of cast-expression
55 /// multiplicative-expression '*' cast-expression
56 /// multiplicative-expression '/' cast-expression
57 /// multiplicative-expression '%' cast-expression
59 /// additive-expression: [C99 6.5.6]
60 /// multiplicative-expression
61 /// additive-expression '+' multiplicative-expression
62 /// additive-expression '-' multiplicative-expression
64 /// shift-expression: [C99 6.5.7]
65 /// additive-expression
66 /// shift-expression '<<' additive-expression
67 /// shift-expression '>>' additive-expression
69 /// compare-expression: [C++20 expr.spaceship]
71 /// compare-expression '<=>' shift-expression
73 /// relational-expression: [C99 6.5.8]
74 /// compare-expression
75 /// relational-expression '<' compare-expression
76 /// relational-expression '>' compare-expression
77 /// relational-expression '<=' compare-expression
78 /// relational-expression '>=' compare-expression
80 /// equality-expression: [C99 6.5.9]
81 /// relational-expression
82 /// equality-expression '==' relational-expression
83 /// equality-expression '!=' relational-expression
85 /// AND-expression: [C99 6.5.10]
86 /// equality-expression
87 /// AND-expression '&' equality-expression
89 /// exclusive-OR-expression: [C99 6.5.11]
91 /// exclusive-OR-expression '^' AND-expression
93 /// inclusive-OR-expression: [C99 6.5.12]
94 /// exclusive-OR-expression
95 /// inclusive-OR-expression '|' exclusive-OR-expression
97 /// logical-AND-expression: [C99 6.5.13]
98 /// inclusive-OR-expression
99 /// logical-AND-expression '&&' inclusive-OR-expression
101 /// logical-OR-expression: [C99 6.5.14]
102 /// logical-AND-expression
103 /// logical-OR-expression '||' logical-AND-expression
105 /// conditional-expression: [C99 6.5.15]
106 /// logical-OR-expression
107 /// logical-OR-expression '?' expression ':' conditional-expression
108 /// [GNU] logical-OR-expression '?' ':' conditional-expression
109 /// [C++] the third operand is an assignment-expression
111 /// assignment-expression: [C99 6.5.16]
112 /// conditional-expression
113 /// unary-expression assignment-operator assignment-expression
114 /// [C++] throw-expression [C++ 15]
116 /// assignment-operator: one of
117 /// = *= /= %= += -= <<= >>= &= ^= |=
119 /// expression: [C99 6.5.17]
120 /// assignment-expression ...[opt]
121 /// expression ',' assignment-expression ...[opt]
123 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
124 ExprResult LHS(ParseAssignmentExpression(isTypeCast));
125 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
128 /// This routine is called when the '@' is seen and consumed.
129 /// Current token is an Identifier and is not a 'try'. This
130 /// routine is necessary to disambiguate \@try-statement from,
131 /// for example, \@encode-expression.
134 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
135 ExprResult LHS(ParseObjCAtExpression(AtLoc));
136 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
139 /// This routine is called when a leading '__extension__' is seen and
140 /// consumed. This is necessary because the token gets consumed in the
141 /// process of disambiguating between an expression and a declaration.
143 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
144 ExprResult LHS(true);
146 // Silence extension warnings in the sub-expression
147 ExtensionRAIIObject O(Diags);
149 LHS = ParseCastExpression(AnyCastExpr);
152 if (!LHS.isInvalid())
153 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
156 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
159 /// Parse an expr that doesn't include (top-level) commas.
160 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
161 if (Tok.is(tok::code_completion)) {
162 Actions.CodeCompleteExpression(getCurScope(),
163 PreferredType.get(Tok.getLocation()));
168 if (Tok.is(tok::kw_throw))
169 return ParseThrowExpression();
170 if (Tok.is(tok::kw_co_yield))
171 return ParseCoyieldExpression();
173 ExprResult LHS = ParseCastExpression(AnyCastExpr,
174 /*isAddressOfOperand=*/false,
176 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
179 /// Parse an assignment expression where part of an Objective-C message
180 /// send has already been parsed.
182 /// In this case \p LBracLoc indicates the location of the '[' of the message
183 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
184 /// the receiver of the message.
186 /// Since this handles full assignment-expression's, it handles postfix
187 /// expressions and other binary operators for these expressions as well.
189 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
190 SourceLocation SuperLoc,
191 ParsedType ReceiverType,
192 Expr *ReceiverExpr) {
194 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
195 ReceiverType, ReceiverExpr);
196 R = ParsePostfixExpressionSuffix(R);
197 return ParseRHSOfBinaryExpression(R, prec::Assignment);
201 Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) {
202 assert(Actions.ExprEvalContexts.back().Context ==
203 Sema::ExpressionEvaluationContext::ConstantEvaluated &&
204 "Call this function only if your ExpressionEvaluationContext is "
205 "already ConstantEvaluated");
206 ExprResult LHS(ParseCastExpression(AnyCastExpr, false, isTypeCast));
207 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
208 return Actions.ActOnConstantExpression(Res);
211 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
212 // C++03 [basic.def.odr]p2:
213 // An expression is potentially evaluated unless it appears where an
214 // integral constant expression is required (see 5.19) [...].
215 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
216 EnterExpressionEvaluationContext ConstantEvaluated(
217 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
218 return ParseConstantExpressionInExprEvalContext(isTypeCast);
221 ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
222 EnterExpressionEvaluationContext ConstantEvaluated(
223 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
224 ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
225 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
226 return Actions.ActOnCaseExpr(CaseLoc, Res);
229 /// Parse a constraint-expression.
232 /// constraint-expression: C++2a[temp.constr.decl]p1
233 /// logical-or-expression
235 ExprResult Parser::ParseConstraintExpression() {
236 EnterExpressionEvaluationContext ConstantEvaluated(
237 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
238 ExprResult LHS(ParseCastExpression(AnyCastExpr));
239 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
240 if (Res.isUsable() && !Actions.CheckConstraintExpression(Res.get())) {
241 Actions.CorrectDelayedTyposInExpr(Res);
247 /// \brief Parse a constraint-logical-and-expression.
250 /// C++2a[temp.constr.decl]p1
251 /// constraint-logical-and-expression:
252 /// primary-expression
253 /// constraint-logical-and-expression '&&' primary-expression
257 Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) {
258 EnterExpressionEvaluationContext ConstantEvaluated(
259 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
260 bool NotPrimaryExpression = false;
261 auto ParsePrimary = [&] () {
262 ExprResult E = ParseCastExpression(PrimaryExprOnly,
263 /*isAddressOfOperand=*/false,
264 /*isTypeCast=*/NotTypeCast,
265 /*isVectorLiteral=*/false,
266 &NotPrimaryExpression);
269 auto RecoverFromNonPrimary = [&] (ExprResult E, bool Note) {
270 E = ParsePostfixExpressionSuffix(E);
271 // Use InclusiveOr, the precedence just after '&&' to not parse the
272 // next arguments to the logical and.
273 E = ParseRHSOfBinaryExpression(E, prec::InclusiveOr);
275 Diag(E.get()->getExprLoc(),
277 ? diag::note_unparenthesized_non_primary_expr_in_requires_clause
278 : diag::err_unparenthesized_non_primary_expr_in_requires_clause)
279 << FixItHint::CreateInsertion(E.get()->getBeginLoc(), "(")
280 << FixItHint::CreateInsertion(
281 PP.getLocForEndOfToken(E.get()->getEndLoc()), ")")
282 << E.get()->getSourceRange();
286 if (NotPrimaryExpression ||
287 // Check if the following tokens must be a part of a non-primary
289 getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
290 /*CPlusPlus11=*/true) > prec::LogicalAnd ||
291 // Postfix operators other than '(' (which will be checked for in
292 // CheckConstraintExpression).
293 Tok.isOneOf(tok::period, tok::plusplus, tok::minusminus) ||
294 (Tok.is(tok::l_square) && !NextToken().is(tok::l_square))) {
295 E = RecoverFromNonPrimary(E, /*Note=*/false);
298 NotPrimaryExpression = false;
300 bool PossibleNonPrimary;
301 bool IsConstraintExpr =
302 Actions.CheckConstraintExpression(E.get(), Tok, &PossibleNonPrimary,
303 IsTrailingRequiresClause);
304 if (!IsConstraintExpr || PossibleNonPrimary) {
305 // Atomic constraint might be an unparenthesized non-primary expression
306 // (such as a binary operator), in which case we might get here (e.g. in
307 // 'requires 0 + 1 && true' we would now be at '+', and parse and ignore
308 // the rest of the addition expression). Try to parse the rest of it here.
309 if (PossibleNonPrimary)
310 E = RecoverFromNonPrimary(E, /*Note=*/!IsConstraintExpr);
311 Actions.CorrectDelayedTyposInExpr(E);
316 ExprResult LHS = ParsePrimary();
319 while (Tok.is(tok::ampamp)) {
320 SourceLocation LogicalAndLoc = ConsumeToken();
321 ExprResult RHS = ParsePrimary();
322 if (RHS.isInvalid()) {
323 Actions.CorrectDelayedTyposInExpr(LHS);
326 ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalAndLoc,
327 tok::ampamp, LHS.get(), RHS.get());
328 if (!Op.isUsable()) {
329 Actions.CorrectDelayedTyposInExpr(RHS);
330 Actions.CorrectDelayedTyposInExpr(LHS);
338 /// \brief Parse a constraint-logical-or-expression.
341 /// C++2a[temp.constr.decl]p1
342 /// constraint-logical-or-expression:
343 /// constraint-logical-and-expression
344 /// constraint-logical-or-expression '||'
345 /// constraint-logical-and-expression
349 Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) {
350 ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause));
353 while (Tok.is(tok::pipepipe)) {
354 SourceLocation LogicalOrLoc = ConsumeToken();
356 ParseConstraintLogicalAndExpression(IsTrailingRequiresClause);
357 if (!RHS.isUsable()) {
358 Actions.CorrectDelayedTyposInExpr(LHS);
361 ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalOrLoc,
362 tok::pipepipe, LHS.get(), RHS.get());
363 if (!Op.isUsable()) {
364 Actions.CorrectDelayedTyposInExpr(RHS);
365 Actions.CorrectDelayedTyposInExpr(LHS);
373 bool Parser::isNotExpressionStart() {
374 tok::TokenKind K = Tok.getKind();
375 if (K == tok::l_brace || K == tok::r_brace ||
376 K == tok::kw_for || K == tok::kw_while ||
377 K == tok::kw_if || K == tok::kw_else ||
378 K == tok::kw_goto || K == tok::kw_try)
380 // If this is a decl-specifier, we can't be at the start of an expression.
381 return isKnownToBeDeclarationSpecifier();
384 bool Parser::isFoldOperator(prec::Level Level) const {
385 return Level > prec::Unknown && Level != prec::Conditional &&
386 Level != prec::Spaceship;
389 bool Parser::isFoldOperator(tok::TokenKind Kind) const {
390 return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
393 /// Parse a binary expression that starts with \p LHS and has a
394 /// precedence of at least \p MinPrec.
396 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
397 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
398 GreaterThanIsOperator,
399 getLangOpts().CPlusPlus11);
400 SourceLocation ColonLoc;
402 auto SavedType = PreferredType;
404 // Every iteration may rely on a preferred type for the whole expression.
405 PreferredType = SavedType;
406 // If this token has a lower precedence than we are allowed to parse (e.g.
407 // because we are called recursively, or because the token is not a binop),
409 if (NextTokPrec < MinPrec)
412 // Consume the operator, saving the operator token for error reporting.
416 if (OpToken.is(tok::caretcaret)) {
417 return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
420 // If we're potentially in a template-id, we may now be able to determine
421 // whether we're actually in one or not.
422 if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
423 tok::greatergreatergreater) &&
424 checkPotentialAngleBracketDelimiter(OpToken))
427 // Bail out when encountering a comma followed by a token which can't
428 // possibly be the start of an expression. For instance:
429 // int f() { return 1, }
430 // We can't do this before consuming the comma, because
431 // isNotExpressionStart() looks at the token stream.
432 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
433 PP.EnterToken(Tok, /*IsReinject*/true);
438 // If the next token is an ellipsis, then this is a fold-expression. Leave
439 // it alone so we can handle it in the paren expression.
440 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
441 // FIXME: We can't check this via lookahead before we consume the token
442 // because that tickles a lexer bug.
443 PP.EnterToken(Tok, /*IsReinject*/true);
448 // In Objective-C++, alternative operator tokens can be used as keyword args
449 // in message expressions. Unconsume the token so that it can reinterpreted
450 // as an identifier in ParseObjCMessageExpressionBody. i.e., we support:
451 // [foo meth:0 and:0];
453 if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
454 Tok.isOneOf(tok::colon, tok::r_square) &&
455 OpToken.getIdentifierInfo() != nullptr) {
456 PP.EnterToken(Tok, /*IsReinject*/true);
461 // Special case handling for the ternary operator.
462 ExprResult TernaryMiddle(true);
463 if (NextTokPrec == prec::Conditional) {
464 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
465 // Parse a braced-init-list here for error recovery purposes.
466 SourceLocation BraceLoc = Tok.getLocation();
467 TernaryMiddle = ParseBraceInitializer();
468 if (!TernaryMiddle.isInvalid()) {
469 Diag(BraceLoc, diag::err_init_list_bin_op)
470 << /*RHS*/ 1 << PP.getSpelling(OpToken)
471 << Actions.getExprRange(TernaryMiddle.get());
472 TernaryMiddle = ExprError();
474 } else if (Tok.isNot(tok::colon)) {
475 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
476 ColonProtectionRAIIObject X(*this);
478 // Handle this production specially:
479 // logical-OR-expression '?' expression ':' conditional-expression
480 // In particular, the RHS of the '?' is 'expression', not
481 // 'logical-OR-expression' as we might expect.
482 TernaryMiddle = ParseExpression();
484 // Special case handling of "X ? Y : Z" where Y is empty:
485 // logical-OR-expression '?' ':' conditional-expression [GNU]
486 TernaryMiddle = nullptr;
487 Diag(Tok, diag::ext_gnu_conditional_expr);
490 if (TernaryMiddle.isInvalid()) {
491 Actions.CorrectDelayedTyposInExpr(LHS);
493 TernaryMiddle = nullptr;
496 if (!TryConsumeToken(tok::colon, ColonLoc)) {
497 // Otherwise, we're missing a ':'. Assume that this was a typo that
498 // the user forgot. If we're not in a macro expansion, we can suggest
499 // a fixit hint. If there were two spaces before the current token,
500 // suggest inserting the colon in between them, otherwise insert ": ".
501 SourceLocation FILoc = Tok.getLocation();
502 const char *FIText = ": ";
503 const SourceManager &SM = PP.getSourceManager();
504 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
505 assert(FILoc.isFileID());
506 bool IsInvalid = false;
507 const char *SourcePtr =
508 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
509 if (!IsInvalid && *SourcePtr == ' ') {
511 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
512 if (!IsInvalid && *SourcePtr == ' ') {
513 FILoc = FILoc.getLocWithOffset(-1);
519 Diag(Tok, diag::err_expected)
520 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
521 Diag(OpToken, diag::note_matching) << tok::question;
522 ColonLoc = Tok.getLocation();
526 PreferredType.enterBinary(Actions, Tok.getLocation(), LHS.get(),
528 // Parse another leaf here for the RHS of the operator.
529 // ParseCastExpression works here because all RHS expressions in C have it
530 // as a prefix, at least. However, in C++, an assignment-expression could
531 // be a throw-expression, which is not a valid cast-expression.
532 // Therefore we need some special-casing here.
533 // Also note that the third operand of the conditional operator is
534 // an assignment-expression in C++, and in C++11, we can have a
535 // braced-init-list on the RHS of an assignment. For better diagnostics,
536 // parse as if we were allowed braced-init-lists everywhere, and check that
537 // they only appear on the RHS of assignments later.
539 bool RHSIsInitList = false;
540 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
541 RHS = ParseBraceInitializer();
542 RHSIsInitList = true;
543 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
544 RHS = ParseAssignmentExpression();
546 RHS = ParseCastExpression(AnyCastExpr);
548 if (RHS.isInvalid()) {
549 // FIXME: Errors generated by the delayed typo correction should be
550 // printed before errors from parsing the RHS, not after.
551 Actions.CorrectDelayedTyposInExpr(LHS);
552 if (TernaryMiddle.isUsable())
553 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
557 // Remember the precedence of this operator and get the precedence of the
558 // operator immediately to the right of the RHS.
559 prec::Level ThisPrec = NextTokPrec;
560 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
561 getLangOpts().CPlusPlus11);
563 // Assignment and conditional expressions are right-associative.
564 bool isRightAssoc = ThisPrec == prec::Conditional ||
565 ThisPrec == prec::Assignment;
567 // Get the precedence of the operator to the right of the RHS. If it binds
568 // more tightly with RHS than we do, evaluate it completely first.
569 if (ThisPrec < NextTokPrec ||
570 (ThisPrec == NextTokPrec && isRightAssoc)) {
571 if (!RHS.isInvalid() && RHSIsInitList) {
572 Diag(Tok, diag::err_init_list_bin_op)
573 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
576 // If this is left-associative, only parse things on the RHS that bind
577 // more tightly than the current operator. If it is left-associative, it
578 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
579 // A=(B=(C=D)), where each paren is a level of recursion here.
580 // The function takes ownership of the RHS.
581 RHS = ParseRHSOfBinaryExpression(RHS,
582 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
583 RHSIsInitList = false;
585 if (RHS.isInvalid()) {
586 // FIXME: Errors generated by the delayed typo correction should be
587 // printed before errors from ParseRHSOfBinaryExpression, not after.
588 Actions.CorrectDelayedTyposInExpr(LHS);
589 if (TernaryMiddle.isUsable())
590 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
594 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
595 getLangOpts().CPlusPlus11);
598 if (!RHS.isInvalid() && RHSIsInitList) {
599 if (ThisPrec == prec::Assignment) {
600 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
601 << Actions.getExprRange(RHS.get());
602 } else if (ColonLoc.isValid()) {
603 Diag(ColonLoc, diag::err_init_list_bin_op)
605 << Actions.getExprRange(RHS.get());
608 Diag(OpToken, diag::err_init_list_bin_op)
609 << /*RHS*/1 << PP.getSpelling(OpToken)
610 << Actions.getExprRange(RHS.get());
615 ExprResult OrigLHS = LHS;
616 if (!LHS.isInvalid()) {
617 // Combine the LHS and RHS into the LHS (e.g. build AST).
618 if (TernaryMiddle.isInvalid()) {
619 // If we're using '>>' as an operator within a template
620 // argument list (in C++98), suggest the addition of
621 // parentheses so that the code remains well-formed in C++0x.
622 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
623 SuggestParentheses(OpToken.getLocation(),
624 diag::warn_cxx11_right_shift_in_template_arg,
625 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
626 Actions.getExprRange(RHS.get()).getEnd()));
628 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
629 OpToken.getKind(), LHS.get(), RHS.get());
632 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
633 LHS.get(), TernaryMiddle.get(),
636 // In this case, ActOnBinOp or ActOnConditionalOp performed the
637 // CorrectDelayedTyposInExpr check.
638 if (!getLangOpts().CPlusPlus)
642 // Ensure potential typos aren't left undiagnosed.
643 if (LHS.isInvalid()) {
644 Actions.CorrectDelayedTyposInExpr(OrigLHS);
645 Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
646 Actions.CorrectDelayedTyposInExpr(RHS);
651 /// Parse a cast-expression, unary-expression or primary-expression, based
654 /// \p isAddressOfOperand exists because an id-expression that is the
655 /// operand of address-of gets special treatment due to member pointers.
657 ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
658 bool isAddressOfOperand,
659 TypeCastState isTypeCast,
660 bool isVectorLiteral,
661 bool *NotPrimaryExpression) {
663 ExprResult Res = ParseCastExpression(ParseKind,
668 NotPrimaryExpression);
670 Diag(Tok, diag::err_expected_expression);
675 class CastExpressionIdValidator final : public CorrectionCandidateCallback {
677 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
678 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
679 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
682 bool ValidateCandidate(const TypoCorrection &candidate) override {
683 NamedDecl *ND = candidate.getCorrectionDecl();
685 return candidate.isKeyword();
687 if (isa<TypeDecl>(ND))
688 return WantTypeSpecifiers;
690 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
693 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
696 for (auto *C : candidate) {
697 NamedDecl *ND = C->getUnderlyingDecl();
698 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
704 std::unique_ptr<CorrectionCandidateCallback> clone() override {
705 return std::make_unique<CastExpressionIdValidator>(*this);
714 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
715 /// a unary-expression.
717 /// \p isAddressOfOperand exists because an id-expression that is the operand
718 /// of address-of gets special treatment due to member pointers. NotCastExpr
719 /// is set to true if the token is not the start of a cast-expression, and no
720 /// diagnostic is emitted in this case and no tokens are consumed.
723 /// cast-expression: [C99 6.5.4]
725 /// '(' type-name ')' cast-expression
727 /// unary-expression: [C99 6.5.3]
728 /// postfix-expression
729 /// '++' unary-expression
730 /// '--' unary-expression
731 /// [Coro] 'co_await' cast-expression
732 /// unary-operator cast-expression
733 /// 'sizeof' unary-expression
734 /// 'sizeof' '(' type-name ')'
735 /// [C++11] 'sizeof' '...' '(' identifier ')'
736 /// [GNU] '__alignof' unary-expression
737 /// [GNU] '__alignof' '(' type-name ')'
738 /// [C11] '_Alignof' '(' type-name ')'
739 /// [C++11] 'alignof' '(' type-id ')'
740 /// [GNU] '&&' identifier
741 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
742 /// [C++] new-expression
743 /// [C++] delete-expression
745 /// unary-operator: one of
746 /// '&' '*' '+' '-' '~' '!'
747 /// [GNU] '__extension__' '__real' '__imag'
749 /// primary-expression: [C99 6.5.1]
751 /// [C++] id-expression
754 /// [C++] boolean-literal [C++ 2.13.5]
755 /// [C++11] 'nullptr' [C++11 2.14.7]
756 /// [C++11] user-defined-literal
757 /// '(' expression ')'
758 /// [C11] generic-selection
759 /// [C++2a] requires-expression
760 /// '__func__' [C99 6.4.2.2]
761 /// [GNU] '__FUNCTION__'
762 /// [MS] '__FUNCDNAME__'
763 /// [MS] 'L__FUNCTION__'
764 /// [MS] '__FUNCSIG__'
765 /// [MS] 'L__FUNCSIG__'
766 /// [GNU] '__PRETTY_FUNCTION__'
767 /// [GNU] '(' compound-statement ')'
768 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
769 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
770 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
772 /// [GNU] '__builtin_FILE' '(' ')'
773 /// [GNU] '__builtin_FUNCTION' '(' ')'
774 /// [GNU] '__builtin_LINE' '(' ')'
775 /// [CLANG] '__builtin_COLUMN' '(' ')'
776 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
778 /// [OBJC] '[' objc-message-expr ']'
779 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
780 /// [OBJC] '\@protocol' '(' identifier ')'
781 /// [OBJC] '\@encode' '(' type-name ')'
782 /// [OBJC] objc-string-literal
783 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
784 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
785 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
786 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
787 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
788 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
789 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
790 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
791 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
792 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
793 /// [C++] 'this' [C++ 9.3.2]
794 /// [G++] unary-type-trait '(' type-id ')'
795 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
796 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
797 /// [clang] '^' block-literal
799 /// constant: [C99 6.4.4]
801 /// floating-constant
802 /// enumeration-constant -> identifier
803 /// character-constant
805 /// id-expression: [C++ 5.1]
809 /// unqualified-id: [C++ 5.1]
811 /// operator-function-id
812 /// conversion-function-id
816 /// new-expression: [C++ 5.3.4]
817 /// '::'[opt] 'new' new-placement[opt] new-type-id
818 /// new-initializer[opt]
819 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
820 /// new-initializer[opt]
822 /// delete-expression: [C++ 5.3.5]
823 /// '::'[opt] 'delete' cast-expression
824 /// '::'[opt] 'delete' '[' ']' cast-expression
826 /// [GNU/Embarcadero] unary-type-trait:
827 /// '__is_arithmetic'
828 /// '__is_floating_point'
830 /// '__is_lvalue_expr'
831 /// '__is_rvalue_expr'
832 /// '__is_complete_type'
837 /// '__is_lvalue_reference'
838 /// '__is_rvalue_reference'
839 /// '__is_fundamental'
844 /// '__is_member_object_pointer'
845 /// '__is_member_function_pointer'
846 /// '__is_member_pointer'
850 /// '__is_standard_layout'
854 /// [GNU] unary-type-trait:
855 /// '__has_nothrow_assign'
856 /// '__has_nothrow_copy'
857 /// '__has_nothrow_constructor'
858 /// '__has_trivial_assign' [TODO]
859 /// '__has_trivial_copy' [TODO]
860 /// '__has_trivial_constructor'
861 /// '__has_trivial_destructor'
862 /// '__has_virtual_destructor'
863 /// '__is_abstract' [TODO]
865 /// '__is_empty' [TODO]
869 /// '__is_polymorphic'
870 /// '__is_sealed' [MS]
873 /// '__has_unique_object_representations'
875 /// [Clang] unary-type-trait:
877 /// '__trivially_copyable'
879 /// binary-type-trait:
880 /// [GNU] '__is_base_of'
881 /// [MS] '__is_convertible_to'
882 /// '__is_convertible'
885 /// [Embarcadero] array-type-trait:
889 /// [Embarcadero] expression-trait:
890 /// '__is_lvalue_expr'
891 /// '__is_rvalue_expr'
894 ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
895 bool isAddressOfOperand,
897 TypeCastState isTypeCast,
898 bool isVectorLiteral,
899 bool *NotPrimaryExpression) {
901 tok::TokenKind SavedKind = Tok.getKind();
902 auto SavedType = PreferredType;
905 // This handles all of cast-expression, unary-expression, postfix-expression,
906 // and primary-expression. We handle them together like this for efficiency
907 // and to simplify handling of an expression starting with a '(' token: which
908 // may be one of a parenthesized expression, cast-expression, compound literal
909 // expression, or statement expression.
911 // If the parsed tokens consist of a primary-expression, the cases below
912 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
913 // to handle the postfix expression suffixes. Cases that cannot be followed
914 // by postfix exprs should return without invoking
915 // ParsePostfixExpressionSuffix.
918 // If this expression is limited to being a unary-expression, the paren can
919 // not start a cast expression.
920 ParenParseOption ParenExprType;
922 case CastParseKind::UnaryExprOnly:
923 if (!getLangOpts().CPlusPlus)
924 ParenExprType = CompoundLiteral;
926 case CastParseKind::AnyCastExpr:
927 ParenExprType = ParenParseOption::CastExpr;
929 case CastParseKind::PrimaryExprOnly:
930 ParenExprType = FoldExpr;
934 SourceLocation RParenLoc;
935 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
936 isTypeCast == IsTypeCast, CastTy, RParenLoc);
941 switch (ParenExprType) {
942 case SimpleExpr: break; // Nothing else to do.
943 case CompoundStmt: break; // Nothing else to do.
944 case CompoundLiteral:
945 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
946 // postfix-expression exist, parse them now.
949 // We have parsed the cast-expression and no postfix-expr pieces are
953 // We only parsed a fold-expression. There might be postfix-expr pieces
954 // afterwards; parse them now.
961 // primary-expression
962 case tok::numeric_constant:
963 // constant: integer-constant
964 // constant: floating-constant
966 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
972 Res = ParseCXXBoolLiteral();
975 case tok::kw___objc_yes:
976 case tok::kw___objc_no:
977 return ParseObjCBoolLiteral();
979 case tok::kw_nullptr:
980 Diag(Tok, diag::warn_cxx98_compat_nullptr);
981 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
983 case tok::annot_primary_expr:
984 Res = getExprAnnotation(Tok);
985 ConsumeAnnotationToken();
986 if (!Res.isInvalid() && Tok.is(tok::less))
987 checkPotentialAngleBracket(Res);
990 case tok::annot_non_type:
991 case tok::annot_non_type_dependent:
992 case tok::annot_non_type_undeclared: {
995 Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
996 assert(!Res.isUnset() &&
997 "should not perform typo correction on annotation token");
1001 case tok::kw___super:
1002 case tok::kw_decltype:
1003 // Annotate the token and tail recurse.
1004 if (TryAnnotateTypeOrScopeToken())
1006 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
1007 return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1008 isVectorLiteral, NotPrimaryExpression);
1010 case tok::identifier: { // primary-expression: identifier
1011 // unqualified-id: identifier
1012 // constant: enumeration-constant
1013 // Turn a potentially qualified name into a annot_typename or
1014 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
1015 if (getLangOpts().CPlusPlus) {
1016 // Avoid the unnecessary parse-time lookup in the common case
1017 // where the syntax forbids a type.
1018 const Token &Next = NextToken();
1020 // If this identifier was reverted from a token ID, and the next token
1021 // is a parenthesis, this is likely to be a use of a type trait. Check
1023 if (Next.is(tok::l_paren) &&
1024 Tok.is(tok::identifier) &&
1025 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
1026 IdentifierInfo *II = Tok.getIdentifierInfo();
1027 // Build up the mapping of revertible type traits, for future use.
1028 if (RevertibleTypeTraits.empty()) {
1029 #define RTT_JOIN(X,Y) X##Y
1030 #define REVERTIBLE_TYPE_TRAIT(Name) \
1031 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
1032 = RTT_JOIN(tok::kw_,Name)
1034 REVERTIBLE_TYPE_TRAIT(__is_abstract);
1035 REVERTIBLE_TYPE_TRAIT(__is_aggregate);
1036 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
1037 REVERTIBLE_TYPE_TRAIT(__is_array);
1038 REVERTIBLE_TYPE_TRAIT(__is_assignable);
1039 REVERTIBLE_TYPE_TRAIT(__is_base_of);
1040 REVERTIBLE_TYPE_TRAIT(__is_class);
1041 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
1042 REVERTIBLE_TYPE_TRAIT(__is_compound);
1043 REVERTIBLE_TYPE_TRAIT(__is_const);
1044 REVERTIBLE_TYPE_TRAIT(__is_constructible);
1045 REVERTIBLE_TYPE_TRAIT(__is_convertible);
1046 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
1047 REVERTIBLE_TYPE_TRAIT(__is_destructible);
1048 REVERTIBLE_TYPE_TRAIT(__is_empty);
1049 REVERTIBLE_TYPE_TRAIT(__is_enum);
1050 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
1051 REVERTIBLE_TYPE_TRAIT(__is_final);
1052 REVERTIBLE_TYPE_TRAIT(__is_function);
1053 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
1054 REVERTIBLE_TYPE_TRAIT(__is_integral);
1055 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
1056 REVERTIBLE_TYPE_TRAIT(__is_literal);
1057 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
1058 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
1059 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
1060 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
1061 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
1062 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
1063 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
1064 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
1065 REVERTIBLE_TYPE_TRAIT(__is_object);
1066 REVERTIBLE_TYPE_TRAIT(__is_pod);
1067 REVERTIBLE_TYPE_TRAIT(__is_pointer);
1068 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
1069 REVERTIBLE_TYPE_TRAIT(__is_reference);
1070 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
1071 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
1072 REVERTIBLE_TYPE_TRAIT(__is_same);
1073 REVERTIBLE_TYPE_TRAIT(__is_scalar);
1074 REVERTIBLE_TYPE_TRAIT(__is_sealed);
1075 REVERTIBLE_TYPE_TRAIT(__is_signed);
1076 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
1077 REVERTIBLE_TYPE_TRAIT(__is_trivial);
1078 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
1079 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
1080 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
1081 REVERTIBLE_TYPE_TRAIT(__is_union);
1082 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
1083 REVERTIBLE_TYPE_TRAIT(__is_void);
1084 REVERTIBLE_TYPE_TRAIT(__is_volatile);
1085 #undef REVERTIBLE_TYPE_TRAIT
1089 // If we find that this is in fact the name of a type trait,
1090 // update the token kind in place and parse again to treat it as
1091 // the appropriate kind of type trait.
1092 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
1093 = RevertibleTypeTraits.find(II);
1094 if (Known != RevertibleTypeTraits.end()) {
1095 Tok.setKind(Known->second);
1096 return ParseCastExpression(ParseKind, isAddressOfOperand,
1097 NotCastExpr, isTypeCast,
1098 isVectorLiteral, NotPrimaryExpression);
1102 if ((!ColonIsSacred && Next.is(tok::colon)) ||
1103 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
1105 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1106 if (TryAnnotateTypeOrScopeToken())
1108 if (!Tok.is(tok::identifier))
1109 return ParseCastExpression(ParseKind, isAddressOfOperand,
1110 NotCastExpr, isTypeCast,
1112 NotPrimaryExpression);
1116 // Consume the identifier so that we can see if it is followed by a '(' or
1118 IdentifierInfo &II = *Tok.getIdentifierInfo();
1119 SourceLocation ILoc = ConsumeToken();
1121 // Support 'Class.property' and 'super.property' notation.
1122 if (getLangOpts().ObjC && Tok.is(tok::period) &&
1123 (Actions.getTypeName(II, ILoc, getCurScope()) ||
1124 // Allow the base to be 'super' if in an objc-method.
1125 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
1128 if (Tok.is(tok::code_completion) && &II != Ident_super) {
1129 Actions.CodeCompleteObjCClassPropertyRefExpr(
1130 getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
1134 // Allow either an identifier or the keyword 'class' (in C++).
1135 if (Tok.isNot(tok::identifier) &&
1136 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
1137 Diag(Tok, diag::err_expected_property_name);
1140 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
1141 SourceLocation PropertyLoc = ConsumeToken();
1143 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
1148 // In an Objective-C method, if we have "super" followed by an identifier,
1149 // the token sequence is ill-formed. However, if there's a ':' or ']' after
1150 // that identifier, this is probably a message send with a missing open
1151 // bracket. Treat it as such.
1152 if (getLangOpts().ObjC && &II == Ident_super && !InMessageExpression &&
1153 getCurScope()->isInObjcMethodScope() &&
1154 ((Tok.is(tok::identifier) &&
1155 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
1156 Tok.is(tok::code_completion))) {
1157 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
1162 // If we have an Objective-C class name followed by an identifier
1163 // and either ':' or ']', this is an Objective-C class message
1164 // send that's missing the opening '['. Recovery
1165 // appropriately. Also take this path if we're performing code
1166 // completion after an Objective-C class name.
1167 if (getLangOpts().ObjC &&
1168 ((Tok.is(tok::identifier) && !InMessageExpression) ||
1169 Tok.is(tok::code_completion))) {
1170 const Token& Next = NextToken();
1171 if (Tok.is(tok::code_completion) ||
1172 Next.is(tok::colon) || Next.is(tok::r_square))
1173 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
1174 if (Typ.get()->isObjCObjectOrInterfaceType()) {
1175 // Fake up a Declarator to use with ActOnTypeName.
1176 DeclSpec DS(AttrFactory);
1177 DS.SetRangeStart(ILoc);
1178 DS.SetRangeEnd(ILoc);
1179 const char *PrevSpec = nullptr;
1181 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1182 Actions.getASTContext().getPrintingPolicy());
1184 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1185 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1190 Res = ParseObjCMessageExpressionBody(SourceLocation(),
1197 // Make sure to pass down the right value for isAddressOfOperand.
1198 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
1199 isAddressOfOperand = false;
1201 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1202 // need to know whether or not this identifier is a function designator or
1205 CXXScopeSpec ScopeSpec;
1206 SourceLocation TemplateKWLoc;
1208 CastExpressionIdValidator Validator(
1210 /*AllowTypes=*/isTypeCast != NotTypeCast,
1211 /*AllowNonTypes=*/isTypeCast != IsTypeCast);
1212 Validator.IsAddressOfOperand = isAddressOfOperand;
1213 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1214 Validator.WantExpressionKeywords = false;
1215 Validator.WantRemainingKeywords = false;
1217 Validator.WantRemainingKeywords = Tok.isNot(tok::r_paren);
1219 Name.setIdentifier(&II, ILoc);
1220 Res = Actions.ActOnIdExpression(
1221 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1222 isAddressOfOperand, &Validator,
1223 /*IsInlineAsmIdentifier=*/false,
1224 Tok.is(tok::r_paren) ? nullptr : &Replacement);
1225 if (!Res.isInvalid() && Res.isUnset()) {
1226 UnconsumeToken(Replacement);
1227 return ParseCastExpression(ParseKind, isAddressOfOperand,
1228 NotCastExpr, isTypeCast,
1229 /*isVectorLiteral=*/false,
1230 NotPrimaryExpression);
1232 if (!Res.isInvalid() && Tok.is(tok::less))
1233 checkPotentialAngleBracket(Res);
1236 case tok::char_constant: // constant: character-constant
1237 case tok::wide_char_constant:
1238 case tok::utf8_char_constant:
1239 case tok::utf16_char_constant:
1240 case tok::utf32_char_constant:
1241 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1244 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
1245 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
1246 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
1247 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
1248 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
1249 case tok::kw_L__FUNCSIG__: // primary-expression: L__FUNCSIG__ [MS]
1250 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1251 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1254 case tok::string_literal: // primary-expression: string-literal
1255 case tok::wide_string_literal:
1256 case tok::utf8_string_literal:
1257 case tok::utf16_string_literal:
1258 case tok::utf32_string_literal:
1259 Res = ParseStringLiteralExpression(true);
1261 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1262 Res = ParseGenericSelectionExpression();
1264 case tok::kw___builtin_available:
1265 return ParseAvailabilityCheckExpr(Tok.getLocation());
1266 case tok::kw___builtin_va_arg:
1267 case tok::kw___builtin_offsetof:
1268 case tok::kw___builtin_choose_expr:
1269 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1270 case tok::kw___builtin_convertvector:
1271 case tok::kw___builtin_COLUMN:
1272 case tok::kw___builtin_FILE:
1273 case tok::kw___builtin_FUNCTION:
1274 case tok::kw___builtin_LINE:
1275 if (NotPrimaryExpression)
1276 *NotPrimaryExpression = true;
1277 return ParseBuiltinPrimaryExpression();
1278 case tok::kw___null:
1279 return Actions.ActOnGNUNullExpr(ConsumeToken());
1281 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1282 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1283 if (NotPrimaryExpression)
1284 *NotPrimaryExpression = true;
1285 // C++ [expr.unary] has:
1286 // unary-expression:
1287 // ++ cast-expression
1288 // -- cast-expression
1289 Token SavedTok = Tok;
1292 PreferredType.enterUnary(Actions, Tok.getLocation(), SavedTok.getKind(),
1293 SavedTok.getLocation());
1294 // One special case is implicitly handled here: if the preceding tokens are
1295 // an ambiguous cast expression, such as "(T())++", then we recurse to
1296 // determine whether the '++' is prefix or postfix.
1297 Res = ParseCastExpression(getLangOpts().CPlusPlus ?
1298 UnaryExprOnly : AnyCastExpr,
1299 /*isAddressOfOperand*/false, NotCastExpr,
1302 // If we return with NotCastExpr = true, we must not consume any tokens,
1303 // so put the token back where we found it.
1304 assert(Res.isInvalid());
1305 UnconsumeToken(SavedTok);
1308 if (!Res.isInvalid())
1309 Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1310 SavedKind, Res.get());
1313 case tok::amp: { // unary-expression: '&' cast-expression
1314 if (NotPrimaryExpression)
1315 *NotPrimaryExpression = true;
1316 // Special treatment because of member pointers
1317 SourceLocation SavedLoc = ConsumeToken();
1318 PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
1319 Res = ParseCastExpression(AnyCastExpr, true);
1320 if (!Res.isInvalid())
1321 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1325 case tok::star: // unary-expression: '*' cast-expression
1326 case tok::plus: // unary-expression: '+' cast-expression
1327 case tok::minus: // unary-expression: '-' cast-expression
1328 case tok::tilde: // unary-expression: '~' cast-expression
1329 case tok::exclaim: // unary-expression: '!' cast-expression
1330 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1331 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1332 if (NotPrimaryExpression)
1333 *NotPrimaryExpression = true;
1334 SourceLocation SavedLoc = ConsumeToken();
1335 PreferredType.enterUnary(Actions, Tok.getLocation(), SavedKind, SavedLoc);
1336 Res = ParseCastExpression(AnyCastExpr);
1337 if (!Res.isInvalid())
1338 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1342 case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1343 if (NotPrimaryExpression)
1344 *NotPrimaryExpression = true;
1345 SourceLocation CoawaitLoc = ConsumeToken();
1346 Res = ParseCastExpression(AnyCastExpr);
1347 if (!Res.isInvalid())
1348 Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1352 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1353 // __extension__ silences extension warnings in the subexpression.
1354 if (NotPrimaryExpression)
1355 *NotPrimaryExpression = true;
1356 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1357 SourceLocation SavedLoc = ConsumeToken();
1358 Res = ParseCastExpression(AnyCastExpr);
1359 if (!Res.isInvalid())
1360 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1363 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1364 if (!getLangOpts().C11)
1365 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
1367 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1368 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1369 // unary-expression: '__alignof' '(' type-name ')'
1370 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1371 // unary-expression: 'sizeof' '(' type-name ')'
1372 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1373 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1374 case tok::kw___builtin_omp_required_simd_align:
1375 if (NotPrimaryExpression)
1376 *NotPrimaryExpression = true;
1377 return ParseUnaryExprOrTypeTraitExpression();
1378 case tok::ampamp: { // unary-expression: '&&' identifier
1379 if (NotPrimaryExpression)
1380 *NotPrimaryExpression = true;
1381 SourceLocation AmpAmpLoc = ConsumeToken();
1382 if (Tok.isNot(tok::identifier))
1383 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1385 if (getCurScope()->getFnParent() == nullptr)
1386 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1388 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1389 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1391 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1395 case tok::kw_const_cast:
1396 case tok::kw_dynamic_cast:
1397 case tok::kw_reinterpret_cast:
1398 case tok::kw_static_cast:
1399 if (NotPrimaryExpression)
1400 *NotPrimaryExpression = true;
1401 Res = ParseCXXCasts();
1403 case tok::kw___builtin_bit_cast:
1404 if (NotPrimaryExpression)
1405 *NotPrimaryExpression = true;
1406 Res = ParseBuiltinBitCast();
1408 case tok::kw_typeid:
1409 if (NotPrimaryExpression)
1410 *NotPrimaryExpression = true;
1411 Res = ParseCXXTypeid();
1413 case tok::kw___uuidof:
1414 if (NotPrimaryExpression)
1415 *NotPrimaryExpression = true;
1416 Res = ParseCXXUuidof();
1419 Res = ParseCXXThis();
1422 case tok::annot_typename:
1423 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1424 ParsedType Type = getTypeAnnotation(Tok);
1426 // Fake up a Declarator to use with ActOnTypeName.
1427 DeclSpec DS(AttrFactory);
1428 DS.SetRangeStart(Tok.getLocation());
1429 DS.SetRangeEnd(Tok.getLastLoc());
1431 const char *PrevSpec = nullptr;
1433 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1434 PrevSpec, DiagID, Type,
1435 Actions.getASTContext().getPrintingPolicy());
1437 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1438 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1442 ConsumeAnnotationToken();
1443 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1449 case tok::annot_decltype:
1451 case tok::kw_wchar_t:
1452 case tok::kw_char8_t:
1453 case tok::kw_char16_t:
1454 case tok::kw_char32_t:
1459 case tok::kw___int64:
1460 case tok::kw___int128:
1461 case tok::kw_signed:
1462 case tok::kw_unsigned:
1465 case tok::kw_double:
1466 case tok::kw__Float16:
1467 case tok::kw___float128:
1469 case tok::kw_typename:
1470 case tok::kw_typeof:
1471 case tok::kw___vector:
1472 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1473 #include "clang/Basic/OpenCLImageTypes.def"
1475 if (!getLangOpts().CPlusPlus) {
1476 Diag(Tok, diag::err_expected_expression);
1480 // Everything henceforth is a postfix-expression.
1481 if (NotPrimaryExpression)
1482 *NotPrimaryExpression = true;
1484 if (SavedKind == tok::kw_typename) {
1485 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1486 // typename-specifier braced-init-list
1487 if (TryAnnotateTypeOrScopeToken())
1490 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1491 // We are trying to parse a simple-type-specifier but might not get such
1492 // a token after error recovery.
1496 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1497 // simple-type-specifier braced-init-list
1499 DeclSpec DS(AttrFactory);
1501 ParseCXXSimpleTypeSpecifier(DS);
1502 if (Tok.isNot(tok::l_paren) &&
1503 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1504 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1505 << DS.getSourceRange());
1507 if (Tok.is(tok::l_brace))
1508 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1510 Res = ParseCXXTypeConstructExpression(DS);
1514 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1515 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1516 // (We can end up in this situation after tentative parsing.)
1517 if (TryAnnotateTypeOrScopeToken())
1519 if (!Tok.is(tok::annot_cxxscope))
1520 return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1521 isTypeCast, isVectorLiteral,
1522 NotPrimaryExpression);
1524 Token Next = NextToken();
1525 if (Next.is(tok::annot_template_id)) {
1526 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1527 if (TemplateId->Kind == TNK_Type_template) {
1528 // We have a qualified template-id that we know refers to a
1529 // type, translate it into a type and continue parsing as a
1532 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1533 /*EnteringContext=*/false);
1534 AnnotateTemplateIdTokenAsType(SS);
1535 return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1536 isTypeCast, isVectorLiteral,
1537 NotPrimaryExpression);
1541 // Parse as an id-expression.
1542 Res = ParseCXXIdExpression(isAddressOfOperand);
1546 case tok::annot_template_id: { // [C++] template-id
1547 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1548 if (TemplateId->Kind == TNK_Type_template) {
1549 // We have a template-id that we know refers to a type,
1550 // translate it into a type and continue parsing as a cast
1553 AnnotateTemplateIdTokenAsType(SS);
1554 return ParseCastExpression(ParseKind, isAddressOfOperand,
1555 NotCastExpr, isTypeCast, isVectorLiteral,
1556 NotPrimaryExpression);
1559 // Fall through to treat the template-id as an id-expression.
1563 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1564 Res = ParseCXXIdExpression(isAddressOfOperand);
1567 case tok::coloncolon: {
1568 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1569 // annotates the token, tail recurse.
1570 if (TryAnnotateTypeOrScopeToken())
1572 if (!Tok.is(tok::coloncolon))
1573 return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1574 isVectorLiteral, NotPrimaryExpression);
1576 // ::new -> [C++] new-expression
1577 // ::delete -> [C++] delete-expression
1578 SourceLocation CCLoc = ConsumeToken();
1579 if (Tok.is(tok::kw_new)) {
1580 if (NotPrimaryExpression)
1581 *NotPrimaryExpression = true;
1582 return ParseCXXNewExpression(true, CCLoc);
1584 if (Tok.is(tok::kw_delete)) {
1585 if (NotPrimaryExpression)
1586 *NotPrimaryExpression = true;
1587 return ParseCXXDeleteExpression(true, CCLoc);
1590 // This is not a type name or scope specifier, it is an invalid expression.
1591 Diag(CCLoc, diag::err_expected_expression);
1595 case tok::kw_new: // [C++] new-expression
1596 if (NotPrimaryExpression)
1597 *NotPrimaryExpression = true;
1598 return ParseCXXNewExpression(false, Tok.getLocation());
1600 case tok::kw_delete: // [C++] delete-expression
1601 if (NotPrimaryExpression)
1602 *NotPrimaryExpression = true;
1603 return ParseCXXDeleteExpression(false, Tok.getLocation());
1605 case tok::kw_requires: // [C++2a] requires-expression
1606 return ParseRequiresExpression();
1608 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1609 if (NotPrimaryExpression)
1610 *NotPrimaryExpression = true;
1611 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1612 SourceLocation KeyLoc = ConsumeToken();
1613 BalancedDelimiterTracker T(*this, tok::l_paren);
1615 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1617 // C++11 [expr.unary.noexcept]p1:
1618 // The noexcept operator determines whether the evaluation of its operand,
1619 // which is an unevaluated operand, can throw an exception.
1620 EnterExpressionEvaluationContext Unevaluated(
1621 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1622 ExprResult Result = ParseExpression();
1626 if (!Result.isInvalid())
1627 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1628 Result.get(), T.getCloseLocation());
1632 #define TYPE_TRAIT(N,Spelling,K) \
1633 case tok::kw_##Spelling:
1634 #include "clang/Basic/TokenKinds.def"
1635 return ParseTypeTrait();
1637 case tok::kw___array_rank:
1638 case tok::kw___array_extent:
1639 if (NotPrimaryExpression)
1640 *NotPrimaryExpression = true;
1641 return ParseArrayTypeTrait();
1643 case tok::kw___is_lvalue_expr:
1644 case tok::kw___is_rvalue_expr:
1645 if (NotPrimaryExpression)
1646 *NotPrimaryExpression = true;
1647 return ParseExpressionTrait();
1650 if (NotPrimaryExpression)
1651 *NotPrimaryExpression = true;
1652 SourceLocation AtLoc = ConsumeToken();
1653 return ParseObjCAtExpression(AtLoc);
1656 Res = ParseBlockLiteralExpression();
1658 case tok::code_completion: {
1659 Actions.CodeCompleteExpression(getCurScope(),
1660 PreferredType.get(Tok.getLocation()));
1665 if (getLangOpts().CPlusPlus11) {
1666 if (getLangOpts().ObjC) {
1667 // C++11 lambda expressions and Objective-C message sends both start with a
1668 // square bracket. There are three possibilities here:
1669 // we have a valid lambda expression, we have an invalid lambda
1670 // expression, or we have something that doesn't appear to be a lambda.
1671 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1672 Res = TryParseLambdaExpression();
1673 if (!Res.isInvalid() && !Res.get()) {
1674 // We assume Objective-C++ message expressions are not
1675 // primary-expressions.
1676 if (NotPrimaryExpression)
1677 *NotPrimaryExpression = true;
1678 Res = ParseObjCMessageExpression();
1682 Res = ParseLambdaExpression();
1685 if (getLangOpts().ObjC) {
1686 Res = ParseObjCMessageExpression();
1695 // Check to see whether Res is a function designator only. If it is and we
1696 // are compiling for OpenCL, we need to return an error as this implies
1697 // that the address of the function is being taken, which is illegal in CL.
1699 if (ParseKind == PrimaryExprOnly)
1700 // This is strictly a primary-expression - no postfix-expr pieces should be
1704 // These can be followed by postfix-expr pieces.
1705 PreferredType = SavedType;
1706 Res = ParsePostfixExpressionSuffix(Res);
1707 if (getLangOpts().OpenCL)
1708 if (Expr *PostfixExpr = Res.get()) {
1709 QualType Ty = PostfixExpr->getType();
1710 if (!Ty.isNull() && Ty->isFunctionType()) {
1711 Diag(PostfixExpr->getExprLoc(),
1712 diag::err_opencl_taking_function_address_parser);
1720 /// Once the leading part of a postfix-expression is parsed, this
1721 /// method parses any suffixes that apply.
1724 /// postfix-expression: [C99 6.5.2]
1725 /// primary-expression
1726 /// postfix-expression '[' expression ']'
1727 /// postfix-expression '[' braced-init-list ']'
1728 /// postfix-expression '(' argument-expression-list[opt] ')'
1729 /// postfix-expression '.' identifier
1730 /// postfix-expression '->' identifier
1731 /// postfix-expression '++'
1732 /// postfix-expression '--'
1733 /// '(' type-name ')' '{' initializer-list '}'
1734 /// '(' type-name ')' '{' initializer-list ',' '}'
1736 /// argument-expression-list: [C99 6.5.2]
1737 /// argument-expression ...[opt]
1738 /// argument-expression-list ',' assignment-expression ...[opt]
1741 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1742 // Now that the primary-expression piece of the postfix-expression has been
1743 // parsed, see if there are any postfix-expression pieces here.
1745 auto SavedType = PreferredType;
1747 // Each iteration relies on preferred type for the whole expression.
1748 PreferredType = SavedType;
1749 switch (Tok.getKind()) {
1750 case tok::code_completion:
1751 if (InMessageExpression)
1754 Actions.CodeCompletePostfixExpression(
1755 getCurScope(), LHS, PreferredType.get(Tok.getLocation()));
1759 case tok::identifier:
1760 // If we see identifier: after an expression, and we're not already in a
1761 // message send, then this is probably a message send with a missing
1762 // opening bracket '['.
1763 if (getLangOpts().ObjC && !InMessageExpression &&
1764 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1765 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1766 nullptr, LHS.get());
1769 // Fall through; this isn't a message send.
1772 default: // Not a postfix-expression suffix.
1774 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1775 // If we have a array postfix expression that starts on a new line and
1776 // Objective-C is enabled, it is highly likely that the user forgot a
1777 // semicolon after the base expression and that the array postfix-expr is
1778 // actually another message send. In this case, do some look-ahead to see
1779 // if the contents of the square brackets are obviously not a valid
1780 // expression and recover by pretending there is no suffix.
1781 if (getLangOpts().ObjC && Tok.isAtStartOfLine() &&
1782 isSimpleObjCMessageExpression())
1785 // Reject array indices starting with a lambda-expression. '[[' is
1786 // reserved for attributes.
1787 if (CheckProhibitedCXX11Attribute()) {
1788 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1792 BalancedDelimiterTracker T(*this, tok::l_square);
1794 Loc = T.getOpenLocation();
1795 ExprResult Idx, Length;
1796 SourceLocation ColonLoc;
1797 PreferredType.enterSubscript(Actions, Tok.getLocation(), LHS.get());
1798 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1799 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1800 Idx = ParseBraceInitializer();
1801 } else if (getLangOpts().OpenMP) {
1802 ColonProtectionRAIIObject RAII(*this);
1803 // Parse [: or [ expr or [ expr :
1804 if (!Tok.is(tok::colon)) {
1806 Idx = ParseExpression();
1808 if (Tok.is(tok::colon)) {
1810 ColonLoc = ConsumeToken();
1811 if (Tok.isNot(tok::r_square))
1812 Length = ParseExpression();
1815 Idx = ParseExpression();
1817 SourceLocation RLoc = Tok.getLocation();
1819 LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1820 Idx = Actions.CorrectDelayedTyposInExpr(Idx);
1821 Length = Actions.CorrectDelayedTyposInExpr(Length);
1822 if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1823 Tok.is(tok::r_square)) {
1824 if (ColonLoc.isValid()) {
1825 LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1826 ColonLoc, Length.get(), RLoc);
1828 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1841 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1842 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1843 // '(' argument-expression-list[opt] ')'
1844 tok::TokenKind OpKind = Tok.getKind();
1845 InMessageExpressionRAIIObject InMessage(*this, false);
1847 Expr *ExecConfig = nullptr;
1849 BalancedDelimiterTracker PT(*this, tok::l_paren);
1851 if (OpKind == tok::lesslessless) {
1852 ExprVector ExecConfigExprs;
1853 CommaLocsTy ExecConfigCommaLocs;
1854 SourceLocation OpenLoc = ConsumeToken();
1856 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1857 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1861 SourceLocation CloseLoc;
1862 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1863 } else if (LHS.isInvalid()) {
1864 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1866 // There was an error closing the brackets
1867 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1868 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1869 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1873 if (!LHS.isInvalid()) {
1874 if (ExpectAndConsume(tok::l_paren))
1877 Loc = PrevTokLocation;
1880 if (!LHS.isInvalid()) {
1881 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1885 if (ECResult.isInvalid())
1888 ExecConfig = ECResult.get();
1892 Loc = PT.getOpenLocation();
1895 ExprVector ArgExprs;
1896 CommaLocsTy CommaLocs;
1897 auto RunSignatureHelp = [&]() -> QualType {
1898 QualType PreferredType = Actions.ProduceCallSignatureHelp(
1899 getCurScope(), LHS.get(), ArgExprs, PT.getOpenLocation());
1900 CalledSignatureHelp = true;
1901 return PreferredType;
1903 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1904 if (Tok.isNot(tok::r_paren)) {
1905 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1906 PreferredType.enterFunctionArgument(Tok.getLocation(),
1909 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1910 // If we got an error when parsing expression list, we don't call
1911 // the CodeCompleteCall handler inside the parser. So call it here
1912 // to make sure we get overload suggestions even when we are in the
1913 // middle of a parameter.
1914 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1917 } else if (LHS.isInvalid()) {
1918 for (auto &E : ArgExprs)
1919 Actions.CorrectDelayedTyposInExpr(E);
1925 if (LHS.isInvalid()) {
1926 SkipUntil(tok::r_paren, StopAtSemi);
1927 } else if (Tok.isNot(tok::r_paren)) {
1928 bool HadDelayedTypo = false;
1929 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1930 HadDelayedTypo = true;
1931 for (auto &E : ArgExprs)
1932 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1933 HadDelayedTypo = true;
1934 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1935 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1936 // the unmatched l_paren.
1938 SkipUntil(tok::r_paren, StopAtSemi);
1943 assert((ArgExprs.size() == 0 ||
1944 ArgExprs.size()-1 == CommaLocs.size())&&
1945 "Unexpected number of commas!");
1946 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1947 ArgExprs, Tok.getLocation(),
1956 // postfix-expression: p-e '->' template[opt] id-expression
1957 // postfix-expression: p-e '.' template[opt] id-expression
1958 tok::TokenKind OpKind = Tok.getKind();
1959 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1962 ParsedType ObjectType;
1963 bool MayBePseudoDestructor = false;
1964 Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr;
1966 PreferredType.enterMemAccess(Actions, Tok.getLocation(), OrigLHS);
1968 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1969 Expr *Base = OrigLHS;
1970 const Type* BaseType = Base->getType().getTypePtrOrNull();
1971 if (BaseType && Tok.is(tok::l_paren) &&
1972 (BaseType->isFunctionType() ||
1973 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1974 Diag(OpLoc, diag::err_function_is_not_record)
1975 << OpKind << Base->getSourceRange()
1976 << FixItHint::CreateRemoval(OpLoc);
1977 return ParsePostfixExpressionSuffix(Base);
1980 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1981 OpLoc, OpKind, ObjectType,
1982 MayBePseudoDestructor);
1983 if (LHS.isInvalid())
1986 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1987 /*EnteringContext=*/false,
1988 &MayBePseudoDestructor);
1989 if (SS.isNotEmpty())
1990 ObjectType = nullptr;
1993 if (Tok.is(tok::code_completion)) {
1994 tok::TokenKind CorrectedOpKind =
1995 OpKind == tok::arrow ? tok::period : tok::arrow;
1996 ExprResult CorrectedLHS(/*Invalid=*/true);
1997 if (getLangOpts().CPlusPlus && OrigLHS) {
1998 // FIXME: Creating a TentativeAnalysisScope from outside Sema is a
2000 Sema::TentativeAnalysisScope Trap(Actions);
2001 CorrectedLHS = Actions.ActOnStartCXXMemberReference(
2002 getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
2003 MayBePseudoDestructor);
2006 Expr *Base = LHS.get();
2007 Expr *CorrectedBase = CorrectedLHS.get();
2008 if (!CorrectedBase && !getLangOpts().CPlusPlus)
2009 CorrectedBase = Base;
2011 // Code completion for a member access expression.
2012 Actions.CodeCompleteMemberReferenceExpr(
2013 getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
2014 Base && ExprStatementTokLoc == Base->getBeginLoc(),
2015 PreferredType.get(Tok.getLocation()));
2021 if (MayBePseudoDestructor && !LHS.isInvalid()) {
2022 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
2027 // Either the action has told us that this cannot be a
2028 // pseudo-destructor expression (based on the type of base
2029 // expression), or we didn't see a '~' in the right place. We
2030 // can still parse a destructor name here, but in that case it
2031 // names a real destructor.
2032 // Allow explicit constructor calls in Microsoft mode.
2033 // FIXME: Add support for explicit call of template constructor.
2034 SourceLocation TemplateKWLoc;
2036 if (getLangOpts().ObjC && OpKind == tok::period &&
2037 Tok.is(tok::kw_class)) {
2039 // After a '.' in a member access expression, treat the keyword
2040 // 'class' as if it were an identifier.
2042 // This hack allows property access to the 'class' method because it is
2043 // such a common method name. For other C++ keywords that are
2044 // Objective-C method names, one must use the message send syntax.
2045 IdentifierInfo *Id = Tok.getIdentifierInfo();
2046 SourceLocation Loc = ConsumeToken();
2047 Name.setIdentifier(Id, Loc);
2048 } else if (ParseUnqualifiedId(SS,
2049 /*EnteringContext=*/false,
2050 /*AllowDestructorName=*/true,
2051 /*AllowConstructorName=*/
2052 getLangOpts().MicrosoftExt &&
2054 /*AllowDeductionGuide=*/false,
2055 ObjectType, &TemplateKWLoc, Name)) {
2056 (void)Actions.CorrectDelayedTyposInExpr(LHS);
2060 if (!LHS.isInvalid())
2061 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
2062 OpKind, SS, TemplateKWLoc, Name,
2063 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
2065 if (!LHS.isInvalid() && Tok.is(tok::less))
2066 checkPotentialAngleBracket(LHS);
2069 case tok::plusplus: // postfix-expression: postfix-expression '++'
2070 case tok::minusminus: // postfix-expression: postfix-expression '--'
2071 if (!LHS.isInvalid()) {
2072 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
2073 Tok.getKind(), LHS.get());
2081 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
2082 /// vec_step and we are at the start of an expression or a parenthesized
2083 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
2084 /// expression (isCastExpr == false) or the type (isCastExpr == true).
2087 /// unary-expression: [C99 6.5.3]
2088 /// 'sizeof' unary-expression
2089 /// 'sizeof' '(' type-name ')'
2090 /// [GNU] '__alignof' unary-expression
2091 /// [GNU] '__alignof' '(' type-name ')'
2092 /// [C11] '_Alignof' '(' type-name ')'
2093 /// [C++0x] 'alignof' '(' type-id ')'
2095 /// [GNU] typeof-specifier:
2096 /// typeof ( expressions )
2097 /// typeof ( type-name )
2098 /// [GNU/C++] typeof unary-expression
2100 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
2101 /// vec_step ( expressions )
2102 /// vec_step ( type-name )
2105 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
2108 SourceRange &CastRange) {
2110 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
2111 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
2112 tok::kw___builtin_omp_required_simd_align) &&
2113 "Not a typeof/sizeof/alignof/vec_step expression!");
2117 // If the operand doesn't start with an '(', it must be an expression.
2118 if (Tok.isNot(tok::l_paren)) {
2119 // If construct allows a form without parenthesis, user may forget to put
2120 // pathenthesis around type name.
2121 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2122 tok::kw__Alignof)) {
2123 if (isTypeIdUnambiguously()) {
2124 DeclSpec DS(AttrFactory);
2125 ParseSpecifierQualifierList(DS);
2126 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2127 ParseDeclarator(DeclaratorInfo);
2129 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
2130 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
2131 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
2133 << FixItHint::CreateInsertion(LParenLoc, "(")
2134 << FixItHint::CreateInsertion(RParenLoc, ")");
2141 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
2142 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
2147 Operand = ParseCastExpression(UnaryExprOnly);
2149 // If it starts with a '(', we know that it is either a parenthesized
2150 // type-name, or it is a unary-expression that starts with a compound
2151 // literal, or starts with a primary-expression that is a parenthesized
2153 ParenParseOption ExprType = CastExpr;
2154 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
2156 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
2157 false, CastTy, RParenLoc);
2158 CastRange = SourceRange(LParenLoc, RParenLoc);
2160 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
2162 if (ExprType == CastExpr) {
2167 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
2168 // GNU typeof in C requires the expression to be parenthesized. Not so for
2169 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
2170 // the start of a unary-expression, but doesn't include any postfix
2171 // pieces. Parse these now if present.
2172 if (!Operand.isInvalid())
2173 Operand = ParsePostfixExpressionSuffix(Operand.get());
2177 // If we get here, the operand to the typeof/sizeof/alignof was an expression.
2183 /// Parse a sizeof or alignof expression.
2186 /// unary-expression: [C99 6.5.3]
2187 /// 'sizeof' unary-expression
2188 /// 'sizeof' '(' type-name ')'
2189 /// [C++11] 'sizeof' '...' '(' identifier ')'
2190 /// [GNU] '__alignof' unary-expression
2191 /// [GNU] '__alignof' '(' type-name ')'
2192 /// [C11] '_Alignof' '(' type-name ')'
2193 /// [C++11] 'alignof' '(' type-id ')'
2195 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
2196 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2197 tok::kw__Alignof, tok::kw_vec_step,
2198 tok::kw___builtin_omp_required_simd_align) &&
2199 "Not a sizeof/alignof/vec_step expression!");
2203 // [C++11] 'sizeof' '...' '(' identifier ')'
2204 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
2205 SourceLocation EllipsisLoc = ConsumeToken();
2206 SourceLocation LParenLoc, RParenLoc;
2207 IdentifierInfo *Name = nullptr;
2208 SourceLocation NameLoc;
2209 if (Tok.is(tok::l_paren)) {
2210 BalancedDelimiterTracker T(*this, tok::l_paren);
2212 LParenLoc = T.getOpenLocation();
2213 if (Tok.is(tok::identifier)) {
2214 Name = Tok.getIdentifierInfo();
2215 NameLoc = ConsumeToken();
2217 RParenLoc = T.getCloseLocation();
2218 if (RParenLoc.isInvalid())
2219 RParenLoc = PP.getLocForEndOfToken(NameLoc);
2221 Diag(Tok, diag::err_expected_parameter_pack);
2222 SkipUntil(tok::r_paren, StopAtSemi);
2224 } else if (Tok.is(tok::identifier)) {
2225 Name = Tok.getIdentifierInfo();
2226 NameLoc = ConsumeToken();
2227 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
2228 RParenLoc = PP.getLocForEndOfToken(NameLoc);
2229 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
2231 << FixItHint::CreateInsertion(LParenLoc, "(")
2232 << FixItHint::CreateInsertion(RParenLoc, ")");
2234 Diag(Tok, diag::err_sizeof_parameter_pack);
2240 EnterExpressionEvaluationContext Unevaluated(
2241 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2242 Sema::ReuseLambdaContextDecl);
2244 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
2245 OpTok.getLocation(),
2250 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2251 Diag(OpTok, diag::warn_cxx98_compat_alignof);
2253 EnterExpressionEvaluationContext Unevaluated(
2254 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2255 Sema::ReuseLambdaContextDecl);
2259 SourceRange CastRange;
2260 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
2265 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2266 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2267 ExprKind = UETT_AlignOf;
2268 else if (OpTok.is(tok::kw___alignof))
2269 ExprKind = UETT_PreferredAlignOf;
2270 else if (OpTok.is(tok::kw_vec_step))
2271 ExprKind = UETT_VecStep;
2272 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2273 ExprKind = UETT_OpenMPRequiredSimdAlign;
2276 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2279 CastTy.getAsOpaquePtr(),
2282 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2283 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2285 // If we get here, the operand to the sizeof/alignof was an expression.
2286 if (!Operand.isInvalid())
2287 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2295 /// ParseBuiltinPrimaryExpression
2298 /// primary-expression: [C99 6.5.1]
2299 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2300 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2301 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2303 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2304 /// [GNU] '__builtin_FILE' '(' ')'
2305 /// [GNU] '__builtin_FUNCTION' '(' ')'
2306 /// [GNU] '__builtin_LINE' '(' ')'
2307 /// [CLANG] '__builtin_COLUMN' '(' ')'
2308 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
2310 /// [GNU] offsetof-member-designator:
2311 /// [GNU] identifier
2312 /// [GNU] offsetof-member-designator '.' identifier
2313 /// [GNU] offsetof-member-designator '[' expression ']'
2315 ExprResult Parser::ParseBuiltinPrimaryExpression() {
2317 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2319 tok::TokenKind T = Tok.getKind();
2320 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
2322 // All of these start with an open paren.
2323 if (Tok.isNot(tok::l_paren))
2324 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2327 BalancedDelimiterTracker PT(*this, tok::l_paren);
2333 default: llvm_unreachable("Not a builtin primary expression!");
2334 case tok::kw___builtin_va_arg: {
2335 ExprResult Expr(ParseAssignmentExpression());
2337 if (ExpectAndConsume(tok::comma)) {
2338 SkipUntil(tok::r_paren, StopAtSemi);
2342 TypeResult Ty = ParseTypeName();
2344 if (Tok.isNot(tok::r_paren)) {
2345 Diag(Tok, diag::err_expected) << tok::r_paren;
2349 if (Expr.isInvalid() || Ty.isInvalid())
2352 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2355 case tok::kw___builtin_offsetof: {
2356 SourceLocation TypeLoc = Tok.getLocation();
2357 TypeResult Ty = ParseTypeName();
2358 if (Ty.isInvalid()) {
2359 SkipUntil(tok::r_paren, StopAtSemi);
2363 if (ExpectAndConsume(tok::comma)) {
2364 SkipUntil(tok::r_paren, StopAtSemi);
2368 // We must have at least one identifier here.
2369 if (Tok.isNot(tok::identifier)) {
2370 Diag(Tok, diag::err_expected) << tok::identifier;
2371 SkipUntil(tok::r_paren, StopAtSemi);
2375 // Keep track of the various subcomponents we see.
2376 SmallVector<Sema::OffsetOfComponent, 4> Comps;
2378 Comps.push_back(Sema::OffsetOfComponent());
2379 Comps.back().isBrackets = false;
2380 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2381 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2383 // FIXME: This loop leaks the index expressions on error.
2385 if (Tok.is(tok::period)) {
2386 // offsetof-member-designator: offsetof-member-designator '.' identifier
2387 Comps.push_back(Sema::OffsetOfComponent());
2388 Comps.back().isBrackets = false;
2389 Comps.back().LocStart = ConsumeToken();
2391 if (Tok.isNot(tok::identifier)) {
2392 Diag(Tok, diag::err_expected) << tok::identifier;
2393 SkipUntil(tok::r_paren, StopAtSemi);
2396 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2397 Comps.back().LocEnd = ConsumeToken();
2399 } else if (Tok.is(tok::l_square)) {
2400 if (CheckProhibitedCXX11Attribute())
2403 // offsetof-member-designator: offsetof-member-design '[' expression ']'
2404 Comps.push_back(Sema::OffsetOfComponent());
2405 Comps.back().isBrackets = true;
2406 BalancedDelimiterTracker ST(*this, tok::l_square);
2408 Comps.back().LocStart = ST.getOpenLocation();
2409 Res = ParseExpression();
2410 if (Res.isInvalid()) {
2411 SkipUntil(tok::r_paren, StopAtSemi);
2414 Comps.back().U.E = Res.get();
2417 Comps.back().LocEnd = ST.getCloseLocation();
2419 if (Tok.isNot(tok::r_paren)) {
2422 } else if (Ty.isInvalid()) {
2426 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2428 PT.getCloseLocation());
2435 case tok::kw___builtin_choose_expr: {
2436 ExprResult Cond(ParseAssignmentExpression());
2437 if (Cond.isInvalid()) {
2438 SkipUntil(tok::r_paren, StopAtSemi);
2441 if (ExpectAndConsume(tok::comma)) {
2442 SkipUntil(tok::r_paren, StopAtSemi);
2446 ExprResult Expr1(ParseAssignmentExpression());
2447 if (Expr1.isInvalid()) {
2448 SkipUntil(tok::r_paren, StopAtSemi);
2451 if (ExpectAndConsume(tok::comma)) {
2452 SkipUntil(tok::r_paren, StopAtSemi);
2456 ExprResult Expr2(ParseAssignmentExpression());
2457 if (Expr2.isInvalid()) {
2458 SkipUntil(tok::r_paren, StopAtSemi);
2461 if (Tok.isNot(tok::r_paren)) {
2462 Diag(Tok, diag::err_expected) << tok::r_paren;
2465 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2466 Expr2.get(), ConsumeParen());
2469 case tok::kw___builtin_astype: {
2470 // The first argument is an expression to be converted, followed by a comma.
2471 ExprResult Expr(ParseAssignmentExpression());
2472 if (Expr.isInvalid()) {
2473 SkipUntil(tok::r_paren, StopAtSemi);
2477 if (ExpectAndConsume(tok::comma)) {
2478 SkipUntil(tok::r_paren, StopAtSemi);
2482 // Second argument is the type to bitcast to.
2483 TypeResult DestTy = ParseTypeName();
2484 if (DestTy.isInvalid())
2487 // Attempt to consume the r-paren.
2488 if (Tok.isNot(tok::r_paren)) {
2489 Diag(Tok, diag::err_expected) << tok::r_paren;
2490 SkipUntil(tok::r_paren, StopAtSemi);
2494 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2498 case tok::kw___builtin_convertvector: {
2499 // The first argument is an expression to be converted, followed by a comma.
2500 ExprResult Expr(ParseAssignmentExpression());
2501 if (Expr.isInvalid()) {
2502 SkipUntil(tok::r_paren, StopAtSemi);
2506 if (ExpectAndConsume(tok::comma)) {
2507 SkipUntil(tok::r_paren, StopAtSemi);
2511 // Second argument is the type to bitcast to.
2512 TypeResult DestTy = ParseTypeName();
2513 if (DestTy.isInvalid())
2516 // Attempt to consume the r-paren.
2517 if (Tok.isNot(tok::r_paren)) {
2518 Diag(Tok, diag::err_expected) << tok::r_paren;
2519 SkipUntil(tok::r_paren, StopAtSemi);
2523 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2527 case tok::kw___builtin_COLUMN:
2528 case tok::kw___builtin_FILE:
2529 case tok::kw___builtin_FUNCTION:
2530 case tok::kw___builtin_LINE: {
2531 // Attempt to consume the r-paren.
2532 if (Tok.isNot(tok::r_paren)) {
2533 Diag(Tok, diag::err_expected) << tok::r_paren;
2534 SkipUntil(tok::r_paren, StopAtSemi);
2537 SourceLocExpr::IdentKind Kind = [&] {
2539 case tok::kw___builtin_FILE:
2540 return SourceLocExpr::File;
2541 case tok::kw___builtin_FUNCTION:
2542 return SourceLocExpr::Function;
2543 case tok::kw___builtin_LINE:
2544 return SourceLocExpr::Line;
2545 case tok::kw___builtin_COLUMN:
2546 return SourceLocExpr::Column;
2548 llvm_unreachable("invalid keyword");
2551 Res = Actions.ActOnSourceLocExpr(Kind, StartLoc, ConsumeParen());
2556 if (Res.isInvalid())
2559 // These can be followed by postfix-expr pieces because they are
2560 // primary-expressions.
2561 return ParsePostfixExpressionSuffix(Res.get());
2564 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2565 /// based on what is allowed by ExprType. The actual thing parsed is returned
2566 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2567 /// not the parsed cast-expression.
2570 /// primary-expression: [C99 6.5.1]
2571 /// '(' expression ')'
2572 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2573 /// postfix-expression: [C99 6.5.2]
2574 /// '(' type-name ')' '{' initializer-list '}'
2575 /// '(' type-name ')' '{' initializer-list ',' '}'
2576 /// cast-expression: [C99 6.5.4]
2577 /// '(' type-name ')' cast-expression
2578 /// [ARC] bridged-cast-expression
2579 /// [ARC] bridged-cast-expression:
2580 /// (__bridge type-name) cast-expression
2581 /// (__bridge_transfer type-name) cast-expression
2582 /// (__bridge_retained type-name) cast-expression
2583 /// fold-expression: [C++1z]
2584 /// '(' cast-expression fold-operator '...' ')'
2585 /// '(' '...' fold-operator cast-expression ')'
2586 /// '(' cast-expression fold-operator '...'
2587 /// fold-operator cast-expression ')'
2590 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2591 bool isTypeCast, ParsedType &CastTy,
2592 SourceLocation &RParenLoc) {
2593 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2594 ColonProtectionRAIIObject ColonProtection(*this, false);
2595 BalancedDelimiterTracker T(*this, tok::l_paren);
2596 if (T.consumeOpen())
2598 SourceLocation OpenLoc = T.getOpenLocation();
2600 PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
2602 ExprResult Result(true);
2603 bool isAmbiguousTypeId;
2606 if (Tok.is(tok::code_completion)) {
2607 Actions.CodeCompleteExpression(
2608 getCurScope(), PreferredType.get(Tok.getLocation()),
2609 /*IsParenthesized=*/ExprType >= CompoundLiteral);
2614 // Diagnose use of bridge casts in non-arc mode.
2615 bool BridgeCast = (getLangOpts().ObjC &&
2616 Tok.isOneOf(tok::kw___bridge,
2617 tok::kw___bridge_transfer,
2618 tok::kw___bridge_retained,
2619 tok::kw___bridge_retain));
2620 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2621 if (!TryConsumeToken(tok::kw___bridge)) {
2622 StringRef BridgeCastName = Tok.getName();
2623 SourceLocation BridgeKeywordLoc = ConsumeToken();
2624 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2625 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2627 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2632 // None of these cases should fall through with an invalid Result
2633 // unless they've already reported an error.
2634 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2635 Diag(Tok, diag::ext_gnu_statement_expr);
2637 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2638 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2640 // Find the nearest non-record decl context. Variables declared in a
2641 // statement expression behave as if they were declared in the enclosing
2642 // function, block, or other code construct.
2643 DeclContext *CodeDC = Actions.CurContext;
2644 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2645 CodeDC = CodeDC->getParent();
2646 assert(CodeDC && !CodeDC->isFileContext() &&
2647 "statement expr not in code context");
2649 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2651 Actions.ActOnStartStmtExpr();
2653 StmtResult Stmt(ParseCompoundStatement(true));
2654 ExprType = CompoundStmt;
2656 // If the substmt parsed correctly, build the AST node.
2657 if (!Stmt.isInvalid()) {
2658 Result = Actions.ActOnStmtExpr(getCurScope(), OpenLoc, Stmt.get(),
2661 Actions.ActOnStmtExprError();
2664 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2665 tok::TokenKind tokenKind = Tok.getKind();
2666 SourceLocation BridgeKeywordLoc = ConsumeToken();
2668 // Parse an Objective-C ARC ownership cast expression.
2669 ObjCBridgeCastKind Kind;
2670 if (tokenKind == tok::kw___bridge)
2672 else if (tokenKind == tok::kw___bridge_transfer)
2673 Kind = OBC_BridgeTransfer;
2674 else if (tokenKind == tok::kw___bridge_retained)
2675 Kind = OBC_BridgeRetained;
2677 // As a hopefully temporary workaround, allow __bridge_retain as
2678 // a synonym for __bridge_retained, but only in system headers.
2679 assert(tokenKind == tok::kw___bridge_retain);
2680 Kind = OBC_BridgeRetained;
2681 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2682 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2683 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2684 "__bridge_retained");
2687 TypeResult Ty = ParseTypeName();
2689 ColonProtection.restore();
2690 RParenLoc = T.getCloseLocation();
2692 PreferredType.enterTypeCast(Tok.getLocation(), Ty.get().get());
2693 ExprResult SubExpr = ParseCastExpression(AnyCastExpr);
2695 if (Ty.isInvalid() || SubExpr.isInvalid())
2698 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2699 BridgeKeywordLoc, Ty.get(),
2700 RParenLoc, SubExpr.get());
2701 } else if (ExprType >= CompoundLiteral &&
2702 isTypeIdInParens(isAmbiguousTypeId)) {
2704 // Otherwise, this is a compound literal expression or cast expression.
2706 // In C++, if the type-id is ambiguous we disambiguate based on context.
2707 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2708 // in which case we should treat it as type-id.
2709 // if stopIfCastExpr is false, we need to determine the context past the
2710 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2711 if (isAmbiguousTypeId && !stopIfCastExpr) {
2712 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2714 RParenLoc = T.getCloseLocation();
2718 // Parse the type declarator.
2719 DeclSpec DS(AttrFactory);
2720 ParseSpecifierQualifierList(DS);
2721 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2722 ParseDeclarator(DeclaratorInfo);
2724 // If our type is followed by an identifier and either ':' or ']', then
2725 // this is probably an Objective-C message send where the leading '[' is
2726 // missing. Recover as if that were the case.
2727 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2728 !InMessageExpression && getLangOpts().ObjC &&
2729 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2732 InMessageExpressionRAIIObject InMessage(*this, false);
2733 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2735 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2741 ColonProtection.restore();
2742 RParenLoc = T.getCloseLocation();
2743 if (Tok.is(tok::l_brace)) {
2744 ExprType = CompoundLiteral;
2747 InMessageExpressionRAIIObject InMessage(*this, false);
2748 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2750 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2753 if (Tok.is(tok::l_paren)) {
2754 // This could be OpenCL vector Literals
2755 if (getLangOpts().OpenCL)
2759 InMessageExpressionRAIIObject InMessage(*this, false);
2760 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2766 QualType QT = Ty.get().get().getCanonicalType();
2767 if (QT->isVectorType())
2769 // We parsed '(' vector-type-name ')' followed by '('
2771 // Parse the cast-expression that follows it next.
2772 // isVectorLiteral = true will make sure we don't parse any
2773 // Postfix expression yet
2774 Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
2775 /*isAddressOfOperand=*/false,
2776 /*isTypeCast=*/IsTypeCast,
2777 /*isVectorLiteral=*/true);
2779 if (!Result.isInvalid()) {
2780 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2781 DeclaratorInfo, CastTy,
2782 RParenLoc, Result.get());
2785 // After we performed the cast we can check for postfix-expr pieces.
2786 if (!Result.isInvalid()) {
2787 Result = ParsePostfixExpressionSuffix(Result);
2795 if (ExprType == CastExpr) {
2796 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2798 if (DeclaratorInfo.isInvalidType())
2801 // Note that this doesn't parse the subsequent cast-expression, it just
2802 // returns the parsed type to the callee.
2803 if (stopIfCastExpr) {
2806 InMessageExpressionRAIIObject InMessage(*this, false);
2807 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2810 return ExprResult();
2813 // Reject the cast of super idiom in ObjC.
2814 if (Tok.is(tok::identifier) && getLangOpts().ObjC &&
2815 Tok.getIdentifierInfo() == Ident_super &&
2816 getCurScope()->isInObjcMethodScope() &&
2817 GetLookAheadToken(1).isNot(tok::period)) {
2818 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2819 << SourceRange(OpenLoc, RParenLoc);
2823 PreferredType.enterTypeCast(Tok.getLocation(), CastTy.get());
2824 // Parse the cast-expression that follows it next.
2825 // TODO: For cast expression with CastTy.
2826 Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
2827 /*isAddressOfOperand=*/false,
2828 /*isTypeCast=*/IsTypeCast);
2829 if (!Result.isInvalid()) {
2830 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2831 DeclaratorInfo, CastTy,
2832 RParenLoc, Result.get());
2837 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2840 } else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) &&
2841 isFoldOperator(NextToken().getKind())) {
2842 ExprType = FoldExpr;
2843 return ParseFoldExpression(ExprResult(), T);
2844 } else if (isTypeCast) {
2845 // Parse the expression-list.
2846 InMessageExpressionRAIIObject InMessage(*this, false);
2848 ExprVector ArgExprs;
2849 CommaLocsTy CommaLocs;
2851 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2852 // FIXME: If we ever support comma expressions as operands to
2853 // fold-expressions, we'll need to allow multiple ArgExprs here.
2854 if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
2855 isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
2856 ExprType = FoldExpr;
2857 return ParseFoldExpression(ArgExprs[0], T);
2860 ExprType = SimpleExpr;
2861 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2865 InMessageExpressionRAIIObject InMessage(*this, false);
2867 Result = ParseExpression(MaybeTypeCast);
2868 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2869 // Correct typos in non-C++ code earlier so that implicit-cast-like
2870 // expressions are parsed correctly.
2871 Result = Actions.CorrectDelayedTyposInExpr(Result);
2874 if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
2875 NextToken().is(tok::ellipsis)) {
2876 ExprType = FoldExpr;
2877 return ParseFoldExpression(Result, T);
2879 ExprType = SimpleExpr;
2881 // Don't build a paren expression unless we actually match a ')'.
2882 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2884 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2888 if (Result.isInvalid()) {
2889 SkipUntil(tok::r_paren, StopAtSemi);
2894 RParenLoc = T.getCloseLocation();
2898 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2899 /// and we are at the left brace.
2902 /// postfix-expression: [C99 6.5.2]
2903 /// '(' type-name ')' '{' initializer-list '}'
2904 /// '(' type-name ')' '{' initializer-list ',' '}'
2907 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2908 SourceLocation LParenLoc,
2909 SourceLocation RParenLoc) {
2910 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2911 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2912 Diag(LParenLoc, diag::ext_c99_compound_literal);
2913 ExprResult Result = ParseInitializer();
2914 if (!Result.isInvalid() && Ty)
2915 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2919 /// ParseStringLiteralExpression - This handles the various token types that
2920 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2921 /// translation phase #6].
2924 /// primary-expression: [C99 6.5.1]
2927 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2928 assert(isTokenStringLiteral() && "Not a string literal!");
2930 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2931 // considered to be strings for concatenation purposes.
2932 SmallVector<Token, 4> StringToks;
2935 StringToks.push_back(Tok);
2936 ConsumeStringToken();
2937 } while (isTokenStringLiteral());
2939 // Pass the set of string tokens, ready for concatenation, to the actions.
2940 return Actions.ActOnStringLiteral(StringToks,
2941 AllowUserDefinedLiteral ? getCurScope()
2945 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2949 /// generic-selection:
2950 /// _Generic ( assignment-expression , generic-assoc-list )
2951 /// generic-assoc-list:
2952 /// generic-association
2953 /// generic-assoc-list , generic-association
2954 /// generic-association:
2955 /// type-name : assignment-expression
2956 /// default : assignment-expression
2958 ExprResult Parser::ParseGenericSelectionExpression() {
2959 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2960 if (!getLangOpts().C11)
2961 Diag(Tok, diag::ext_c11_feature) << Tok.getName();
2963 SourceLocation KeyLoc = ConsumeToken();
2964 BalancedDelimiterTracker T(*this, tok::l_paren);
2965 if (T.expectAndConsume())
2968 ExprResult ControllingExpr;
2970 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2972 EnterExpressionEvaluationContext Unevaluated(
2973 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
2975 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2976 if (ControllingExpr.isInvalid()) {
2977 SkipUntil(tok::r_paren, StopAtSemi);
2982 if (ExpectAndConsume(tok::comma)) {
2983 SkipUntil(tok::r_paren, StopAtSemi);
2987 SourceLocation DefaultLoc;
2992 if (Tok.is(tok::kw_default)) {
2993 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2994 // generic association."
2995 if (!DefaultLoc.isInvalid()) {
2996 Diag(Tok, diag::err_duplicate_default_assoc);
2997 Diag(DefaultLoc, diag::note_previous_default_assoc);
2998 SkipUntil(tok::r_paren, StopAtSemi);
3001 DefaultLoc = ConsumeToken();
3004 ColonProtectionRAIIObject X(*this);
3005 TypeResult TR = ParseTypeName();
3006 if (TR.isInvalid()) {
3007 SkipUntil(tok::r_paren, StopAtSemi);
3012 Types.push_back(Ty);
3014 if (ExpectAndConsume(tok::colon)) {
3015 SkipUntil(tok::r_paren, StopAtSemi);
3019 // FIXME: These expressions should be parsed in a potentially potentially
3020 // evaluated context.
3022 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
3023 if (ER.isInvalid()) {
3024 SkipUntil(tok::r_paren, StopAtSemi);
3027 Exprs.push_back(ER.get());
3028 } while (TryConsumeToken(tok::comma));
3031 if (T.getCloseLocation().isInvalid())
3034 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
3035 T.getCloseLocation(),
3036 ControllingExpr.get(),
3040 /// Parse A C++1z fold-expression after the opening paren and optional
3041 /// left-hand-side expression.
3044 /// fold-expression:
3045 /// ( cast-expression fold-operator ... )
3046 /// ( ... fold-operator cast-expression )
3047 /// ( cast-expression fold-operator ... fold-operator cast-expression )
3048 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
3049 BalancedDelimiterTracker &T) {
3050 if (LHS.isInvalid()) {
3055 tok::TokenKind Kind = tok::unknown;
3056 SourceLocation FirstOpLoc;
3057 if (LHS.isUsable()) {
3058 Kind = Tok.getKind();
3059 assert(isFoldOperator(Kind) && "missing fold-operator");
3060 FirstOpLoc = ConsumeToken();
3063 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
3064 SourceLocation EllipsisLoc = ConsumeToken();
3067 if (Tok.isNot(tok::r_paren)) {
3068 if (!isFoldOperator(Tok.getKind()))
3069 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
3071 if (Kind != tok::unknown && Tok.getKind() != Kind)
3072 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
3073 << SourceRange(FirstOpLoc);
3074 Kind = Tok.getKind();
3077 RHS = ParseExpression();
3078 if (RHS.isInvalid()) {
3084 Diag(EllipsisLoc, getLangOpts().CPlusPlus17
3085 ? diag::warn_cxx14_compat_fold_expression
3086 : diag::ext_fold_expression);
3089 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
3090 EllipsisLoc, RHS.get(), T.getCloseLocation());
3093 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
3096 /// argument-expression-list:
3097 /// assignment-expression
3098 /// argument-expression-list , assignment-expression
3100 /// [C++] expression-list:
3101 /// [C++] assignment-expression
3102 /// [C++] expression-list , assignment-expression
3104 /// [C++0x] expression-list:
3105 /// [C++0x] initializer-list
3107 /// [C++0x] initializer-list
3108 /// [C++0x] initializer-clause ...[opt]
3109 /// [C++0x] initializer-list , initializer-clause ...[opt]
3111 /// [C++0x] initializer-clause:
3112 /// [C++0x] assignment-expression
3113 /// [C++0x] braced-init-list
3115 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
3116 SmallVectorImpl<SourceLocation> &CommaLocs,
3117 llvm::function_ref<void()> ExpressionStarts) {
3118 bool SawError = false;
3120 if (ExpressionStarts)
3124 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3125 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3126 Expr = ParseBraceInitializer();
3128 Expr = ParseAssignmentExpression();
3130 if (Tok.is(tok::ellipsis))
3131 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
3132 if (Expr.isInvalid()) {
3133 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
3136 Exprs.push_back(Expr.get());
3139 if (Tok.isNot(tok::comma))
3141 // Move to the next argument, remember where the comma was.
3143 CommaLocs.push_back(ConsumeToken());
3145 checkPotentialAngleBracketDelimiter(Comma);
3148 // Ensure typos get diagnosed when errors were encountered while parsing the
3150 for (auto &E : Exprs) {
3151 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
3152 if (Expr.isUsable()) E = Expr.get();
3158 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
3159 /// used for misc language extensions.
3162 /// simple-expression-list:
3163 /// assignment-expression
3164 /// simple-expression-list , assignment-expression
3167 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
3168 SmallVectorImpl<SourceLocation> &CommaLocs) {
3170 ExprResult Expr = ParseAssignmentExpression();
3171 if (Expr.isInvalid())
3174 Exprs.push_back(Expr.get());
3176 if (Tok.isNot(tok::comma))
3179 // Move to the next argument, remember where the comma was.
3181 CommaLocs.push_back(ConsumeToken());
3183 checkPotentialAngleBracketDelimiter(Comma);
3187 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
3190 /// [clang] block-id:
3191 /// [clang] specifier-qualifier-list block-declarator
3193 void Parser::ParseBlockId(SourceLocation CaretLoc) {
3194 if (Tok.is(tok::code_completion)) {
3195 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
3196 return cutOffParsing();
3199 // Parse the specifier-qualifier-list piece.
3200 DeclSpec DS(AttrFactory);
3201 ParseSpecifierQualifierList(DS);
3203 // Parse the block-declarator.
3204 Declarator DeclaratorInfo(DS, DeclaratorContext::BlockLiteralContext);
3205 DeclaratorInfo.setFunctionDefinitionKind(FDK_Definition);
3206 ParseDeclarator(DeclaratorInfo);
3208 MaybeParseGNUAttributes(DeclaratorInfo);
3210 // Inform sema that we are starting a block.
3211 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
3214 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
3215 /// like ^(int x){ return x+1; }
3219 /// [clang] '^' block-args[opt] compound-statement
3220 /// [clang] '^' block-id compound-statement
3221 /// [clang] block-args:
3222 /// [clang] '(' parameter-list ')'
3224 ExprResult Parser::ParseBlockLiteralExpression() {
3225 assert(Tok.is(tok::caret) && "block literal starts with ^");
3226 SourceLocation CaretLoc = ConsumeToken();
3228 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
3229 "block literal parsing");
3231 // Enter a scope to hold everything within the block. This includes the
3232 // argument decls, decls within the compound expression, etc. This also
3233 // allows determining whether a variable reference inside the block is
3234 // within or outside of the block.
3235 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
3236 Scope::CompoundStmtScope | Scope::DeclScope);
3238 // Inform sema that we are starting a block.
3239 Actions.ActOnBlockStart(CaretLoc, getCurScope());
3241 // Parse the return type if present.
3242 DeclSpec DS(AttrFactory);
3243 Declarator ParamInfo(DS, DeclaratorContext::BlockLiteralContext);
3244 ParamInfo.setFunctionDefinitionKind(FDK_Definition);
3245 // FIXME: Since the return type isn't actually parsed, it can't be used to
3246 // fill ParamInfo with an initial valid range, so do it manually.
3247 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
3249 // If this block has arguments, parse them. There is no ambiguity here with
3250 // the expression case, because the expression case requires a parameter list.
3251 if (Tok.is(tok::l_paren)) {
3252 ParseParenDeclarator(ParamInfo);
3253 // Parse the pieces after the identifier as if we had "int(...)".
3254 // SetIdentifier sets the source range end, but in this case we're past
3256 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
3257 ParamInfo.SetIdentifier(nullptr, CaretLoc);
3258 ParamInfo.SetRangeEnd(Tmp);
3259 if (ParamInfo.isInvalidType()) {
3260 // If there was an error parsing the arguments, they may have
3261 // tried to use ^(x+y) which requires an argument list. Just
3262 // skip the whole block literal.
3263 Actions.ActOnBlockError(CaretLoc, getCurScope());
3267 MaybeParseGNUAttributes(ParamInfo);
3269 // Inform sema that we are starting a block.
3270 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3271 } else if (!Tok.is(tok::l_brace)) {
3272 ParseBlockId(CaretLoc);
3274 // Otherwise, pretend we saw (void).
3275 SourceLocation NoLoc;
3276 ParamInfo.AddTypeInfo(
3277 DeclaratorChunk::getFunction(/*HasProto=*/true,
3278 /*IsAmbiguous=*/false,
3279 /*RParenLoc=*/NoLoc,
3280 /*ArgInfo=*/nullptr,
3282 /*EllipsisLoc=*/NoLoc,
3283 /*RParenLoc=*/NoLoc,
3284 /*RefQualifierIsLvalueRef=*/true,
3285 /*RefQualifierLoc=*/NoLoc,
3286 /*MutableLoc=*/NoLoc, EST_None,
3287 /*ESpecRange=*/SourceRange(),
3288 /*Exceptions=*/nullptr,
3289 /*ExceptionRanges=*/nullptr,
3290 /*NumExceptions=*/0,
3291 /*NoexceptExpr=*/nullptr,
3292 /*ExceptionSpecTokens=*/nullptr,
3293 /*DeclsInPrototype=*/None, CaretLoc,
3294 CaretLoc, ParamInfo),
3297 MaybeParseGNUAttributes(ParamInfo);
3299 // Inform sema that we are starting a block.
3300 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3304 ExprResult Result(true);
3305 if (!Tok.is(tok::l_brace)) {
3306 // Saw something like: ^expr
3307 Diag(Tok, diag::err_expected_expression);
3308 Actions.ActOnBlockError(CaretLoc, getCurScope());
3312 StmtResult Stmt(ParseCompoundStatementBody());
3314 if (!Stmt.isInvalid())
3315 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3317 Actions.ActOnBlockError(CaretLoc, getCurScope());
3321 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3325 ExprResult Parser::ParseObjCBoolLiteral() {
3326 tok::TokenKind Kind = Tok.getKind();
3327 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3330 /// Validate availability spec list, emitting diagnostics if necessary. Returns
3331 /// true if invalid.
3332 static bool CheckAvailabilitySpecList(Parser &P,
3333 ArrayRef<AvailabilitySpec> AvailSpecs) {
3334 llvm::SmallSet<StringRef, 4> Platforms;
3335 bool HasOtherPlatformSpec = false;
3337 for (const auto &Spec : AvailSpecs) {
3338 if (Spec.isOtherPlatformSpec()) {
3339 if (HasOtherPlatformSpec) {
3340 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3344 HasOtherPlatformSpec = true;
3348 bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3350 // Rule out multiple version specs referring to the same platform.
3351 // For example, we emit an error for:
3352 // @available(macos 10.10, macos 10.11, *)
3353 StringRef Platform = Spec.getPlatform();
3354 P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3355 << Spec.getEndLoc() << Platform;
3360 if (!HasOtherPlatformSpec) {
3361 SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3362 P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3363 << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3370 /// Parse availability query specification.
3372 /// availability-spec:
3374 /// identifier version-tuple
3375 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3376 if (Tok.is(tok::star)) {
3377 return AvailabilitySpec(ConsumeToken());
3379 // Parse the platform name.
3380 if (Tok.is(tok::code_completion)) {
3381 Actions.CodeCompleteAvailabilityPlatformName();
3385 if (Tok.isNot(tok::identifier)) {
3386 Diag(Tok, diag::err_avail_query_expected_platform_name);
3390 IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3391 SourceRange VersionRange;
3392 VersionTuple Version = ParseVersionTuple(VersionRange);
3394 if (Version.empty())
3397 StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3398 StringRef Platform =
3399 AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3401 if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3402 Diag(PlatformIdentifier->Loc,
3403 diag::err_avail_query_unrecognized_platform_name)
3408 return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3409 VersionRange.getEnd());
3413 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3414 assert(Tok.is(tok::kw___builtin_available) ||
3415 Tok.isObjCAtKeyword(tok::objc_available));
3417 // Eat the available or __builtin_available.
3420 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3421 if (Parens.expectAndConsume())
3424 SmallVector<AvailabilitySpec, 4> AvailSpecs;
3425 bool HasError = false;
3427 Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3431 AvailSpecs.push_back(*Spec);
3433 if (!TryConsumeToken(tok::comma))
3438 SkipUntil(tok::r_paren, StopAtSemi);
3442 CheckAvailabilitySpecList(*this, AvailSpecs);
3444 if (Parens.consumeClose())
3447 return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3448 Parens.getCloseLocation());