ParseExpr.cpp revision 87d948ecccffea9e9e37d0d053b246e2d6d6c47b
1//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief Provides the Expression parsing implementation.
12///
13/// Expressions in C99 basically consist of a bunch of binary operators with
14/// unary operators and other random stuff at the leaves.
15///
16/// In the C99 grammar, these unary operators bind tightest and are represented
17/// as the 'cast-expression' production.  Everything else is either a binary
18/// operator (e.g. '/') or a ternary operator ("?:").  The unary leaves are
19/// handled by ParseCastExpression, the higher level pieces are handled by
20/// ParseBinaryExpression.
21///
22//===----------------------------------------------------------------------===//
23
24#include "clang/Parse/Parser.h"
25#include "RAIIObjectsForParser.h"
26#include "clang/AST/ASTContext.h"
27#include "clang/Basic/PrettyStackTrace.h"
28#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
30#include "clang/Sema/Scope.h"
31#include "clang/Sema/TypoCorrection.h"
32#include "llvm/ADT/SmallString.h"
33#include "llvm/ADT/SmallVector.h"
34using namespace clang;
35
36/// \brief Simple precedence-based parser for binary/ternary operators.
37///
38/// Note: we diverge from the C99 grammar when parsing the assignment-expression
39/// production.  C99 specifies that the LHS of an assignment operator should be
40/// parsed as a unary-expression, but consistency dictates that it be a
41/// conditional-expession.  In practice, the important thing here is that the
42/// LHS of an assignment has to be an l-value, which productions between
43/// unary-expression and conditional-expression don't produce.  Because we want
44/// consistency, we parse the LHS as a conditional-expression, then check for
45/// l-value-ness in semantic analysis stages.
46///
47/// \verbatim
48///       pm-expression: [C++ 5.5]
49///         cast-expression
50///         pm-expression '.*' cast-expression
51///         pm-expression '->*' cast-expression
52///
53///       multiplicative-expression: [C99 6.5.5]
54///     Note: in C++, apply pm-expression instead of cast-expression
55///         cast-expression
56///         multiplicative-expression '*' cast-expression
57///         multiplicative-expression '/' cast-expression
58///         multiplicative-expression '%' cast-expression
59///
60///       additive-expression: [C99 6.5.6]
61///         multiplicative-expression
62///         additive-expression '+' multiplicative-expression
63///         additive-expression '-' multiplicative-expression
64///
65///       shift-expression: [C99 6.5.7]
66///         additive-expression
67///         shift-expression '<<' additive-expression
68///         shift-expression '>>' additive-expression
69///
70///       relational-expression: [C99 6.5.8]
71///         shift-expression
72///         relational-expression '<' shift-expression
73///         relational-expression '>' shift-expression
74///         relational-expression '<=' shift-expression
75///         relational-expression '>=' shift-expression
76///
77///       equality-expression: [C99 6.5.9]
78///         relational-expression
79///         equality-expression '==' relational-expression
80///         equality-expression '!=' relational-expression
81///
82///       AND-expression: [C99 6.5.10]
83///         equality-expression
84///         AND-expression '&' equality-expression
85///
86///       exclusive-OR-expression: [C99 6.5.11]
87///         AND-expression
88///         exclusive-OR-expression '^' AND-expression
89///
90///       inclusive-OR-expression: [C99 6.5.12]
91///         exclusive-OR-expression
92///         inclusive-OR-expression '|' exclusive-OR-expression
93///
94///       logical-AND-expression: [C99 6.5.13]
95///         inclusive-OR-expression
96///         logical-AND-expression '&&' inclusive-OR-expression
97///
98///       logical-OR-expression: [C99 6.5.14]
99///         logical-AND-expression
100///         logical-OR-expression '||' logical-AND-expression
101///
102///       conditional-expression: [C99 6.5.15]
103///         logical-OR-expression
104///         logical-OR-expression '?' expression ':' conditional-expression
105/// [GNU]   logical-OR-expression '?' ':' conditional-expression
106/// [C++] the third operand is an assignment-expression
107///
108///       assignment-expression: [C99 6.5.16]
109///         conditional-expression
110///         unary-expression assignment-operator assignment-expression
111/// [C++]   throw-expression [C++ 15]
112///
113///       assignment-operator: one of
114///         = *= /= %= += -= <<= >>= &= ^= |=
115///
116///       expression: [C99 6.5.17]
117///         assignment-expression ...[opt]
118///         expression ',' assignment-expression ...[opt]
119/// \endverbatim
120ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
121  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
122  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
123}
124
125/// This routine is called when the '@' is seen and consumed.
126/// Current token is an Identifier and is not a 'try'. This
127/// routine is necessary to disambiguate \@try-statement from,
128/// for example, \@encode-expression.
129///
130ExprResult
131Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
132  ExprResult LHS(ParseObjCAtExpression(AtLoc));
133  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
134}
135
136/// This routine is called when a leading '__extension__' is seen and
137/// consumed.  This is necessary because the token gets consumed in the
138/// process of disambiguating between an expression and a declaration.
139ExprResult
140Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
141  ExprResult LHS(true);
142  {
143    // Silence extension warnings in the sub-expression
144    ExtensionRAIIObject O(Diags);
145
146    LHS = ParseCastExpression(false);
147  }
148
149  if (!LHS.isInvalid())
150    LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
151                               LHS.get());
152
153  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
154}
155
156/// \brief Parse an expr that doesn't include (top-level) commas.
157ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
158  if (Tok.is(tok::code_completion)) {
159    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
160    cutOffParsing();
161    return ExprError();
162  }
163
164  if (Tok.is(tok::kw_throw))
165    return ParseThrowExpression();
166  if (Tok.is(tok::kw_co_yield))
167    return ParseCoyieldExpression();
168
169  ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
170                                       /*isAddressOfOperand=*/false,
171                                       isTypeCast);
172  return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
173}
174
175/// \brief Parse an assignment expression where part of an Objective-C message
176/// send has already been parsed.
177///
178/// In this case \p LBracLoc indicates the location of the '[' of the message
179/// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
180/// the receiver of the message.
181///
182/// Since this handles full assignment-expression's, it handles postfix
183/// expressions and other binary operators for these expressions as well.
184ExprResult
185Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
186                                                    SourceLocation SuperLoc,
187                                                    ParsedType ReceiverType,
188                                                    Expr *ReceiverExpr) {
189  ExprResult R
190    = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
191                                     ReceiverType, ReceiverExpr);
192  R = ParsePostfixExpressionSuffix(R);
193  return ParseRHSOfBinaryExpression(R, prec::Assignment);
194}
195
196
197ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
198  // C++03 [basic.def.odr]p2:
199  //   An expression is potentially evaluated unless it appears where an
200  //   integral constant expression is required (see 5.19) [...].
201  // C++98 and C++11 have no such rule, but this is only a defect in C++98.
202  EnterExpressionEvaluationContext Unevaluated(Actions,
203                                               Sema::ConstantEvaluated);
204
205  ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
206  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
207  return Actions.ActOnConstantExpression(Res);
208}
209
210/// \brief Parse a constraint-expression.
211///
212/// \verbatim
213///       constraint-expression: [Concepts TS temp.constr.decl p1]
214///         logical-or-expression
215/// \endverbatim
216ExprResult Parser::ParseConstraintExpression() {
217  // FIXME: this may erroneously consume a function-body as the braced
218  // initializer list of a compound literal
219  //
220  // FIXME: this may erroneously consume a parenthesized rvalue reference
221  // declarator as a parenthesized address-of-label expression
222  ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
223  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
224
225  return Res;
226}
227
228bool Parser::isNotExpressionStart() {
229  tok::TokenKind K = Tok.getKind();
230  if (K == tok::l_brace || K == tok::r_brace  ||
231      K == tok::kw_for  || K == tok::kw_while ||
232      K == tok::kw_if   || K == tok::kw_else  ||
233      K == tok::kw_goto || K == tok::kw_try)
234    return true;
235  // If this is a decl-specifier, we can't be at the start of an expression.
236  return isKnownToBeDeclarationSpecifier();
237}
238
239static bool isFoldOperator(prec::Level Level) {
240  return Level > prec::Unknown && Level != prec::Conditional;
241}
242static bool isFoldOperator(tok::TokenKind Kind) {
243  return isFoldOperator(getBinOpPrecedence(Kind, false, true));
244}
245
246/// \brief Parse a binary expression that starts with \p LHS and has a
247/// precedence of at least \p MinPrec.
248ExprResult
249Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
250  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
251                                               GreaterThanIsOperator,
252                                               getLangOpts().CPlusPlus11);
253  SourceLocation ColonLoc;
254
255  while (1) {
256    // If this token has a lower precedence than we are allowed to parse (e.g.
257    // because we are called recursively, or because the token is not a binop),
258    // then we are done!
259    if (NextTokPrec < MinPrec)
260      return LHS;
261
262    // Consume the operator, saving the operator token for error reporting.
263    Token OpToken = Tok;
264    ConsumeToken();
265
266    // Bail out when encountering a comma followed by a token which can't
267    // possibly be the start of an expression. For instance:
268    //   int f() { return 1, }
269    // We can't do this before consuming the comma, because
270    // isNotExpressionStart() looks at the token stream.
271    if (OpToken.is(tok::comma) && isNotExpressionStart()) {
272      PP.EnterToken(Tok);
273      Tok = OpToken;
274      return LHS;
275    }
276
277    // If the next token is an ellipsis, then this is a fold-expression. Leave
278    // it alone so we can handle it in the paren expression.
279    if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
280      // FIXME: We can't check this via lookahead before we consume the token
281      // because that tickles a lexer bug.
282      PP.EnterToken(Tok);
283      Tok = OpToken;
284      return LHS;
285    }
286
287    // Special case handling for the ternary operator.
288    ExprResult TernaryMiddle(true);
289    if (NextTokPrec == prec::Conditional) {
290      if (Tok.isNot(tok::colon)) {
291        // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
292        ColonProtectionRAIIObject X(*this);
293
294        // Handle this production specially:
295        //   logical-OR-expression '?' expression ':' conditional-expression
296        // In particular, the RHS of the '?' is 'expression', not
297        // 'logical-OR-expression' as we might expect.
298        TernaryMiddle = ParseExpression();
299        if (TernaryMiddle.isInvalid()) {
300          Actions.CorrectDelayedTyposInExpr(LHS);
301          LHS = ExprError();
302          TernaryMiddle = nullptr;
303        }
304      } else {
305        // Special case handling of "X ? Y : Z" where Y is empty:
306        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
307        TernaryMiddle = nullptr;
308        Diag(Tok, diag::ext_gnu_conditional_expr);
309      }
310
311      if (!TryConsumeToken(tok::colon, ColonLoc)) {
312        // Otherwise, we're missing a ':'.  Assume that this was a typo that
313        // the user forgot. If we're not in a macro expansion, we can suggest
314        // a fixit hint. If there were two spaces before the current token,
315        // suggest inserting the colon in between them, otherwise insert ": ".
316        SourceLocation FILoc = Tok.getLocation();
317        const char *FIText = ": ";
318        const SourceManager &SM = PP.getSourceManager();
319        if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
320          assert(FILoc.isFileID());
321          bool IsInvalid = false;
322          const char *SourcePtr =
323            SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
324          if (!IsInvalid && *SourcePtr == ' ') {
325            SourcePtr =
326              SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
327            if (!IsInvalid && *SourcePtr == ' ') {
328              FILoc = FILoc.getLocWithOffset(-1);
329              FIText = ":";
330            }
331          }
332        }
333
334        Diag(Tok, diag::err_expected)
335            << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
336        Diag(OpToken, diag::note_matching) << tok::question;
337        ColonLoc = Tok.getLocation();
338      }
339    }
340
341    // Code completion for the right-hand side of an assignment expression
342    // goes through a special hook that takes the left-hand side into account.
343    if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
344      Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
345      cutOffParsing();
346      return ExprError();
347    }
348
349    // Parse another leaf here for the RHS of the operator.
350    // ParseCastExpression works here because all RHS expressions in C have it
351    // as a prefix, at least. However, in C++, an assignment-expression could
352    // be a throw-expression, which is not a valid cast-expression.
353    // Therefore we need some special-casing here.
354    // Also note that the third operand of the conditional operator is
355    // an assignment-expression in C++, and in C++11, we can have a
356    // braced-init-list on the RHS of an assignment. For better diagnostics,
357    // parse as if we were allowed braced-init-lists everywhere, and check that
358    // they only appear on the RHS of assignments later.
359    ExprResult RHS;
360    bool RHSIsInitList = false;
361    if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
362      RHS = ParseBraceInitializer();
363      RHSIsInitList = true;
364    } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
365      RHS = ParseAssignmentExpression();
366    else
367      RHS = ParseCastExpression(false);
368
369    if (RHS.isInvalid()) {
370      // FIXME: Errors generated by the delayed typo correction should be
371      // printed before errors from parsing the RHS, not after.
372      Actions.CorrectDelayedTyposInExpr(LHS);
373      if (TernaryMiddle.isUsable())
374        TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
375      LHS = ExprError();
376    }
377
378    // Remember the precedence of this operator and get the precedence of the
379    // operator immediately to the right of the RHS.
380    prec::Level ThisPrec = NextTokPrec;
381    NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
382                                     getLangOpts().CPlusPlus11);
383
384    // Assignment and conditional expressions are right-associative.
385    bool isRightAssoc = ThisPrec == prec::Conditional ||
386                        ThisPrec == prec::Assignment;
387
388    // Get the precedence of the operator to the right of the RHS.  If it binds
389    // more tightly with RHS than we do, evaluate it completely first.
390    if (ThisPrec < NextTokPrec ||
391        (ThisPrec == NextTokPrec && isRightAssoc)) {
392      if (!RHS.isInvalid() && RHSIsInitList) {
393        Diag(Tok, diag::err_init_list_bin_op)
394          << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
395        RHS = ExprError();
396      }
397      // If this is left-associative, only parse things on the RHS that bind
398      // more tightly than the current operator.  If it is left-associative, it
399      // is okay, to bind exactly as tightly.  For example, compile A=B=C=D as
400      // A=(B=(C=D)), where each paren is a level of recursion here.
401      // The function takes ownership of the RHS.
402      RHS = ParseRHSOfBinaryExpression(RHS,
403                            static_cast<prec::Level>(ThisPrec + !isRightAssoc));
404      RHSIsInitList = false;
405
406      if (RHS.isInvalid()) {
407        // FIXME: Errors generated by the delayed typo correction should be
408        // printed before errors from ParseRHSOfBinaryExpression, not after.
409        Actions.CorrectDelayedTyposInExpr(LHS);
410        if (TernaryMiddle.isUsable())
411          TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
412        LHS = ExprError();
413      }
414
415      NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
416                                       getLangOpts().CPlusPlus11);
417    }
418
419    if (!RHS.isInvalid() && RHSIsInitList) {
420      if (ThisPrec == prec::Assignment) {
421        Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
422          << Actions.getExprRange(RHS.get());
423      } else {
424        Diag(OpToken, diag::err_init_list_bin_op)
425          << /*RHS*/1 << PP.getSpelling(OpToken)
426          << Actions.getExprRange(RHS.get());
427        LHS = ExprError();
428      }
429    }
430
431    if (!LHS.isInvalid()) {
432      // Combine the LHS and RHS into the LHS (e.g. build AST).
433      if (TernaryMiddle.isInvalid()) {
434        // If we're using '>>' as an operator within a template
435        // argument list (in C++98), suggest the addition of
436        // parentheses so that the code remains well-formed in C++0x.
437        if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
438          SuggestParentheses(OpToken.getLocation(),
439                             diag::warn_cxx11_right_shift_in_template_arg,
440                         SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
441                                     Actions.getExprRange(RHS.get()).getEnd()));
442
443        LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
444                                 OpToken.getKind(), LHS.get(), RHS.get());
445      } else
446        LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
447                                         LHS.get(), TernaryMiddle.get(),
448                                         RHS.get());
449    } else
450      // Ensure potential typos in the RHS aren't left undiagnosed.
451      Actions.CorrectDelayedTyposInExpr(RHS);
452  }
453}
454
455/// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
456/// parse a unary-expression.
457///
458/// \p isAddressOfOperand exists because an id-expression that is the
459/// operand of address-of gets special treatment due to member pointers.
460///
461ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
462                                       bool isAddressOfOperand,
463                                       TypeCastState isTypeCast) {
464  bool NotCastExpr;
465  ExprResult Res = ParseCastExpression(isUnaryExpression,
466                                       isAddressOfOperand,
467                                       NotCastExpr,
468                                       isTypeCast);
469  if (NotCastExpr)
470    Diag(Tok, diag::err_expected_expression);
471  return Res;
472}
473
474namespace {
475class CastExpressionIdValidator : public CorrectionCandidateCallback {
476 public:
477  CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
478      : NextToken(Next), AllowNonTypes(AllowNonTypes) {
479    WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
480  }
481
482  bool ValidateCandidate(const TypoCorrection &candidate) override {
483    NamedDecl *ND = candidate.getCorrectionDecl();
484    if (!ND)
485      return candidate.isKeyword();
486
487    if (isa<TypeDecl>(ND))
488      return WantTypeSpecifiers;
489
490    if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
491      return false;
492
493    if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
494      return true;
495
496    for (auto *C : candidate) {
497      NamedDecl *ND = C->getUnderlyingDecl();
498      if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
499        return true;
500    }
501    return false;
502  }
503
504 private:
505  Token NextToken;
506  bool AllowNonTypes;
507};
508}
509
510/// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
511/// a unary-expression.
512///
513/// \p isAddressOfOperand exists because an id-expression that is the operand
514/// of address-of gets special treatment due to member pointers. NotCastExpr
515/// is set to true if the token is not the start of a cast-expression, and no
516/// diagnostic is emitted in this case.
517///
518/// \verbatim
519///       cast-expression: [C99 6.5.4]
520///         unary-expression
521///         '(' type-name ')' cast-expression
522///
523///       unary-expression:  [C99 6.5.3]
524///         postfix-expression
525///         '++' unary-expression
526///         '--' unary-expression
527/// [Coro]  'co_await' cast-expression
528///         unary-operator cast-expression
529///         'sizeof' unary-expression
530///         'sizeof' '(' type-name ')'
531/// [C++11] 'sizeof' '...' '(' identifier ')'
532/// [GNU]   '__alignof' unary-expression
533/// [GNU]   '__alignof' '(' type-name ')'
534/// [C11]   '_Alignof' '(' type-name ')'
535/// [C++11] 'alignof' '(' type-id ')'
536/// [GNU]   '&&' identifier
537/// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
538/// [C++]   new-expression
539/// [C++]   delete-expression
540///
541///       unary-operator: one of
542///         '&'  '*'  '+'  '-'  '~'  '!'
543/// [GNU]   '__extension__'  '__real'  '__imag'
544///
545///       primary-expression: [C99 6.5.1]
546/// [C99]   identifier
547/// [C++]   id-expression
548///         constant
549///         string-literal
550/// [C++]   boolean-literal  [C++ 2.13.5]
551/// [C++11] 'nullptr'        [C++11 2.14.7]
552/// [C++11] user-defined-literal
553///         '(' expression ')'
554/// [C11]   generic-selection
555///         '__func__'        [C99 6.4.2.2]
556/// [GNU]   '__FUNCTION__'
557/// [MS]    '__FUNCDNAME__'
558/// [MS]    'L__FUNCTION__'
559/// [GNU]   '__PRETTY_FUNCTION__'
560/// [GNU]   '(' compound-statement ')'
561/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
562/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
563/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
564///                                     assign-expr ')'
565/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
566/// [GNU]   '__null'
567/// [OBJC]  '[' objc-message-expr ']'
568/// [OBJC]  '\@selector' '(' objc-selector-arg ')'
569/// [OBJC]  '\@protocol' '(' identifier ')'
570/// [OBJC]  '\@encode' '(' type-name ')'
571/// [OBJC]  objc-string-literal
572/// [C++]   simple-type-specifier '(' expression-list[opt] ')'      [C++ 5.2.3]
573/// [C++11] simple-type-specifier braced-init-list                  [C++11 5.2.3]
574/// [C++]   typename-specifier '(' expression-list[opt] ')'         [C++ 5.2.3]
575/// [C++11] typename-specifier braced-init-list                     [C++11 5.2.3]
576/// [C++]   'const_cast' '<' type-name '>' '(' expression ')'       [C++ 5.2p1]
577/// [C++]   'dynamic_cast' '<' type-name '>' '(' expression ')'     [C++ 5.2p1]
578/// [C++]   'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
579/// [C++]   'static_cast' '<' type-name '>' '(' expression ')'      [C++ 5.2p1]
580/// [C++]   'typeid' '(' expression ')'                             [C++ 5.2p1]
581/// [C++]   'typeid' '(' type-id ')'                                [C++ 5.2p1]
582/// [C++]   'this'          [C++ 9.3.2]
583/// [G++]   unary-type-trait '(' type-id ')'
584/// [G++]   binary-type-trait '(' type-id ',' type-id ')'           [TODO]
585/// [EMBT]  array-type-trait '(' type-id ',' integer ')'
586/// [clang] '^' block-literal
587///
588///       constant: [C99 6.4.4]
589///         integer-constant
590///         floating-constant
591///         enumeration-constant -> identifier
592///         character-constant
593///
594///       id-expression: [C++ 5.1]
595///                   unqualified-id
596///                   qualified-id
597///
598///       unqualified-id: [C++ 5.1]
599///                   identifier
600///                   operator-function-id
601///                   conversion-function-id
602///                   '~' class-name
603///                   template-id
604///
605///       new-expression: [C++ 5.3.4]
606///                   '::'[opt] 'new' new-placement[opt] new-type-id
607///                                     new-initializer[opt]
608///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
609///                                     new-initializer[opt]
610///
611///       delete-expression: [C++ 5.3.5]
612///                   '::'[opt] 'delete' cast-expression
613///                   '::'[opt] 'delete' '[' ']' cast-expression
614///
615/// [GNU/Embarcadero] unary-type-trait:
616///                   '__is_arithmetic'
617///                   '__is_floating_point'
618///                   '__is_integral'
619///                   '__is_lvalue_expr'
620///                   '__is_rvalue_expr'
621///                   '__is_complete_type'
622///                   '__is_void'
623///                   '__is_array'
624///                   '__is_function'
625///                   '__is_reference'
626///                   '__is_lvalue_reference'
627///                   '__is_rvalue_reference'
628///                   '__is_fundamental'
629///                   '__is_object'
630///                   '__is_scalar'
631///                   '__is_compound'
632///                   '__is_pointer'
633///                   '__is_member_object_pointer'
634///                   '__is_member_function_pointer'
635///                   '__is_member_pointer'
636///                   '__is_const'
637///                   '__is_volatile'
638///                   '__is_trivial'
639///                   '__is_standard_layout'
640///                   '__is_signed'
641///                   '__is_unsigned'
642///
643/// [GNU] unary-type-trait:
644///                   '__has_nothrow_assign'
645///                   '__has_nothrow_copy'
646///                   '__has_nothrow_constructor'
647///                   '__has_trivial_assign'                  [TODO]
648///                   '__has_trivial_copy'                    [TODO]
649///                   '__has_trivial_constructor'
650///                   '__has_trivial_destructor'
651///                   '__has_virtual_destructor'
652///                   '__is_abstract'                         [TODO]
653///                   '__is_class'
654///                   '__is_empty'                            [TODO]
655///                   '__is_enum'
656///                   '__is_final'
657///                   '__is_pod'
658///                   '__is_polymorphic'
659///                   '__is_sealed'                           [MS]
660///                   '__is_trivial'
661///                   '__is_union'
662///
663/// [Clang] unary-type-trait:
664///                   '__trivially_copyable'
665///
666///       binary-type-trait:
667/// [GNU]             '__is_base_of'
668/// [MS]              '__is_convertible_to'
669///                   '__is_convertible'
670///                   '__is_same'
671///
672/// [Embarcadero] array-type-trait:
673///                   '__array_rank'
674///                   '__array_extent'
675///
676/// [Embarcadero] expression-trait:
677///                   '__is_lvalue_expr'
678///                   '__is_rvalue_expr'
679/// \endverbatim
680///
681ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
682                                       bool isAddressOfOperand,
683                                       bool &NotCastExpr,
684                                       TypeCastState isTypeCast) {
685  ExprResult Res;
686  tok::TokenKind SavedKind = Tok.getKind();
687  NotCastExpr = false;
688
689  // This handles all of cast-expression, unary-expression, postfix-expression,
690  // and primary-expression.  We handle them together like this for efficiency
691  // and to simplify handling of an expression starting with a '(' token: which
692  // may be one of a parenthesized expression, cast-expression, compound literal
693  // expression, or statement expression.
694  //
695  // If the parsed tokens consist of a primary-expression, the cases below
696  // break out of the switch;  at the end we call ParsePostfixExpressionSuffix
697  // to handle the postfix expression suffixes.  Cases that cannot be followed
698  // by postfix exprs should return without invoking
699  // ParsePostfixExpressionSuffix.
700  switch (SavedKind) {
701  case tok::l_paren: {
702    // If this expression is limited to being a unary-expression, the parent can
703    // not start a cast expression.
704    ParenParseOption ParenExprType =
705        (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
706                                                        : CastExpr;
707    ParsedType CastTy;
708    SourceLocation RParenLoc;
709    Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
710                               isTypeCast == IsTypeCast, CastTy, RParenLoc);
711
712    switch (ParenExprType) {
713    case SimpleExpr:   break;    // Nothing else to do.
714    case CompoundStmt: break;  // Nothing else to do.
715    case CompoundLiteral:
716      // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
717      // postfix-expression exist, parse them now.
718      break;
719    case CastExpr:
720      // We have parsed the cast-expression and no postfix-expr pieces are
721      // following.
722      return Res;
723    }
724
725    break;
726  }
727
728    // primary-expression
729  case tok::numeric_constant:
730    // constant: integer-constant
731    // constant: floating-constant
732
733    Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
734    ConsumeToken();
735    break;
736
737  case tok::kw_true:
738  case tok::kw_false:
739    return ParseCXXBoolLiteral();
740
741  case tok::kw___objc_yes:
742  case tok::kw___objc_no:
743      return ParseObjCBoolLiteral();
744
745  case tok::kw_nullptr:
746    Diag(Tok, diag::warn_cxx98_compat_nullptr);
747    return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
748
749  case tok::annot_primary_expr:
750    assert(Res.get() == nullptr && "Stray primary-expression annotation?");
751    Res = getExprAnnotation(Tok);
752    ConsumeToken();
753    break;
754
755  case tok::kw___super:
756  case tok::kw_decltype:
757    // Annotate the token and tail recurse.
758    if (TryAnnotateTypeOrScopeToken())
759      return ExprError();
760    assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
761    return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
762
763  case tok::identifier: {      // primary-expression: identifier
764                               // unqualified-id: identifier
765                               // constant: enumeration-constant
766    // Turn a potentially qualified name into a annot_typename or
767    // annot_cxxscope if it would be valid.  This handles things like x::y, etc.
768    if (getLangOpts().CPlusPlus) {
769      // Avoid the unnecessary parse-time lookup in the common case
770      // where the syntax forbids a type.
771      const Token &Next = NextToken();
772
773      // If this identifier was reverted from a token ID, and the next token
774      // is a parenthesis, this is likely to be a use of a type trait. Check
775      // those tokens.
776      if (Next.is(tok::l_paren) &&
777          Tok.is(tok::identifier) &&
778          Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
779        IdentifierInfo *II = Tok.getIdentifierInfo();
780        // Build up the mapping of revertible type traits, for future use.
781        if (RevertibleTypeTraits.empty()) {
782#define RTT_JOIN(X,Y) X##Y
783#define REVERTIBLE_TYPE_TRAIT(Name)                         \
784          RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
785            = RTT_JOIN(tok::kw_,Name)
786
787          REVERTIBLE_TYPE_TRAIT(__is_abstract);
788          REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
789          REVERTIBLE_TYPE_TRAIT(__is_array);
790          REVERTIBLE_TYPE_TRAIT(__is_base_of);
791          REVERTIBLE_TYPE_TRAIT(__is_class);
792          REVERTIBLE_TYPE_TRAIT(__is_complete_type);
793          REVERTIBLE_TYPE_TRAIT(__is_compound);
794          REVERTIBLE_TYPE_TRAIT(__is_const);
795          REVERTIBLE_TYPE_TRAIT(__is_constructible);
796          REVERTIBLE_TYPE_TRAIT(__is_convertible);
797          REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
798          REVERTIBLE_TYPE_TRAIT(__is_destructible);
799          REVERTIBLE_TYPE_TRAIT(__is_empty);
800          REVERTIBLE_TYPE_TRAIT(__is_enum);
801          REVERTIBLE_TYPE_TRAIT(__is_floating_point);
802          REVERTIBLE_TYPE_TRAIT(__is_final);
803          REVERTIBLE_TYPE_TRAIT(__is_function);
804          REVERTIBLE_TYPE_TRAIT(__is_fundamental);
805          REVERTIBLE_TYPE_TRAIT(__is_integral);
806          REVERTIBLE_TYPE_TRAIT(__is_interface_class);
807          REVERTIBLE_TYPE_TRAIT(__is_literal);
808          REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
809          REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
810          REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
811          REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
812          REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
813          REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
814          REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
815          REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
816          REVERTIBLE_TYPE_TRAIT(__is_object);
817          REVERTIBLE_TYPE_TRAIT(__is_pod);
818          REVERTIBLE_TYPE_TRAIT(__is_pointer);
819          REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
820          REVERTIBLE_TYPE_TRAIT(__is_reference);
821          REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
822          REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
823          REVERTIBLE_TYPE_TRAIT(__is_same);
824          REVERTIBLE_TYPE_TRAIT(__is_scalar);
825          REVERTIBLE_TYPE_TRAIT(__is_sealed);
826          REVERTIBLE_TYPE_TRAIT(__is_signed);
827          REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
828          REVERTIBLE_TYPE_TRAIT(__is_trivial);
829          REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
830          REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
831          REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
832          REVERTIBLE_TYPE_TRAIT(__is_union);
833          REVERTIBLE_TYPE_TRAIT(__is_unsigned);
834          REVERTIBLE_TYPE_TRAIT(__is_void);
835          REVERTIBLE_TYPE_TRAIT(__is_volatile);
836#undef REVERTIBLE_TYPE_TRAIT
837#undef RTT_JOIN
838        }
839
840        // If we find that this is in fact the name of a type trait,
841        // update the token kind in place and parse again to treat it as
842        // the appropriate kind of type trait.
843        llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
844          = RevertibleTypeTraits.find(II);
845        if (Known != RevertibleTypeTraits.end()) {
846          Tok.setKind(Known->second);
847          return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
848                                     NotCastExpr, isTypeCast);
849        }
850      }
851
852      if ((!ColonIsSacred && Next.is(tok::colon)) ||
853          Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
854                       tok::l_brace)) {
855        // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
856        if (TryAnnotateTypeOrScopeToken())
857          return ExprError();
858        if (!Tok.is(tok::identifier))
859          return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
860      }
861    }
862
863    // Consume the identifier so that we can see if it is followed by a '(' or
864    // '.'.
865    IdentifierInfo &II = *Tok.getIdentifierInfo();
866    SourceLocation ILoc = ConsumeToken();
867
868    // Support 'Class.property' and 'super.property' notation.
869    if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
870        (Actions.getTypeName(II, ILoc, getCurScope()) ||
871         // Allow the base to be 'super' if in an objc-method.
872         (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
873      ConsumeToken();
874
875      // Allow either an identifier or the keyword 'class' (in C++).
876      if (Tok.isNot(tok::identifier) &&
877          !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
878        Diag(Tok, diag::err_expected_property_name);
879        return ExprError();
880      }
881      IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
882      SourceLocation PropertyLoc = ConsumeToken();
883
884      Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
885                                              ILoc, PropertyLoc);
886      break;
887    }
888
889    // In an Objective-C method, if we have "super" followed by an identifier,
890    // the token sequence is ill-formed. However, if there's a ':' or ']' after
891    // that identifier, this is probably a message send with a missing open
892    // bracket. Treat it as such.
893    if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
894        getCurScope()->isInObjcMethodScope() &&
895        ((Tok.is(tok::identifier) &&
896         (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
897         Tok.is(tok::code_completion))) {
898      Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
899                                           nullptr);
900      break;
901    }
902
903    // If we have an Objective-C class name followed by an identifier
904    // and either ':' or ']', this is an Objective-C class message
905    // send that's missing the opening '['. Recovery
906    // appropriately. Also take this path if we're performing code
907    // completion after an Objective-C class name.
908    if (getLangOpts().ObjC1 &&
909        ((Tok.is(tok::identifier) && !InMessageExpression) ||
910         Tok.is(tok::code_completion))) {
911      const Token& Next = NextToken();
912      if (Tok.is(tok::code_completion) ||
913          Next.is(tok::colon) || Next.is(tok::r_square))
914        if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
915          if (Typ.get()->isObjCObjectOrInterfaceType()) {
916            // Fake up a Declarator to use with ActOnTypeName.
917            DeclSpec DS(AttrFactory);
918            DS.SetRangeStart(ILoc);
919            DS.SetRangeEnd(ILoc);
920            const char *PrevSpec = nullptr;
921            unsigned DiagID;
922            DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
923                               Actions.getASTContext().getPrintingPolicy());
924
925            Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
926            TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
927                                                  DeclaratorInfo);
928            if (Ty.isInvalid())
929              break;
930
931            Res = ParseObjCMessageExpressionBody(SourceLocation(),
932                                                 SourceLocation(),
933                                                 Ty.get(), nullptr);
934            break;
935          }
936    }
937
938    // Make sure to pass down the right value for isAddressOfOperand.
939    if (isAddressOfOperand && isPostfixExpressionSuffixStart())
940      isAddressOfOperand = false;
941
942    // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
943    // need to know whether or not this identifier is a function designator or
944    // not.
945    UnqualifiedId Name;
946    CXXScopeSpec ScopeSpec;
947    SourceLocation TemplateKWLoc;
948    Token Replacement;
949    auto Validator = llvm::make_unique<CastExpressionIdValidator>(
950        Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
951    Validator->IsAddressOfOperand = isAddressOfOperand;
952    if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
953      Validator->WantExpressionKeywords = false;
954      Validator->WantRemainingKeywords = false;
955    } else {
956      Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
957    }
958    Name.setIdentifier(&II, ILoc);
959    Res = Actions.ActOnIdExpression(
960        getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
961        isAddressOfOperand, std::move(Validator),
962        /*IsInlineAsmIdentifier=*/false,
963        Tok.is(tok::r_paren) ? nullptr : &Replacement);
964    if (!Res.isInvalid() && !Res.get()) {
965      UnconsumeToken(Replacement);
966      return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
967                                 NotCastExpr, isTypeCast);
968    }
969    break;
970  }
971  case tok::char_constant:     // constant: character-constant
972  case tok::wide_char_constant:
973  case tok::utf8_char_constant:
974  case tok::utf16_char_constant:
975  case tok::utf32_char_constant:
976    Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
977    ConsumeToken();
978    break;
979  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
980  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
981  case tok::kw___FUNCDNAME__:   // primary-expression: __FUNCDNAME__ [MS]
982  case tok::kw___FUNCSIG__:     // primary-expression: __FUNCSIG__ [MS]
983  case tok::kw_L__FUNCTION__:   // primary-expression: L__FUNCTION__ [MS]
984  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
985    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
986    ConsumeToken();
987    break;
988  case tok::string_literal:    // primary-expression: string-literal
989  case tok::wide_string_literal:
990  case tok::utf8_string_literal:
991  case tok::utf16_string_literal:
992  case tok::utf32_string_literal:
993    Res = ParseStringLiteralExpression(true);
994    break;
995  case tok::kw__Generic:   // primary-expression: generic-selection [C11 6.5.1]
996    Res = ParseGenericSelectionExpression();
997    break;
998  case tok::kw___builtin_va_arg:
999  case tok::kw___builtin_offsetof:
1000  case tok::kw___builtin_choose_expr:
1001  case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1002  case tok::kw___builtin_convertvector:
1003    return ParseBuiltinPrimaryExpression();
1004  case tok::kw___null:
1005    return Actions.ActOnGNUNullExpr(ConsumeToken());
1006
1007  case tok::plusplus:      // unary-expression: '++' unary-expression [C99]
1008  case tok::minusminus: {  // unary-expression: '--' unary-expression [C99]
1009    // C++ [expr.unary] has:
1010    //   unary-expression:
1011    //     ++ cast-expression
1012    //     -- cast-expression
1013    SourceLocation SavedLoc = ConsumeToken();
1014    // One special case is implicitly handled here: if the preceding tokens are
1015    // an ambiguous cast expression, such as "(T())++", then we recurse to
1016    // determine whether the '++' is prefix or postfix.
1017    Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1018                              /*isAddressOfOperand*/false, NotCastExpr,
1019                              NotTypeCast);
1020    if (!Res.isInvalid())
1021      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1022    return Res;
1023  }
1024  case tok::amp: {         // unary-expression: '&' cast-expression
1025    // Special treatment because of member pointers
1026    SourceLocation SavedLoc = ConsumeToken();
1027    Res = ParseCastExpression(false, true);
1028    if (!Res.isInvalid())
1029      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1030    return Res;
1031  }
1032
1033  case tok::star:          // unary-expression: '*' cast-expression
1034  case tok::plus:          // unary-expression: '+' cast-expression
1035  case tok::minus:         // unary-expression: '-' cast-expression
1036  case tok::tilde:         // unary-expression: '~' cast-expression
1037  case tok::exclaim:       // unary-expression: '!' cast-expression
1038  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
1039  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
1040    SourceLocation SavedLoc = ConsumeToken();
1041    Res = ParseCastExpression(false);
1042    if (!Res.isInvalid())
1043      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1044    return Res;
1045  }
1046
1047  case tok::kw_co_await: {  // unary-expression: 'co_await' cast-expression
1048    SourceLocation CoawaitLoc = ConsumeToken();
1049    Res = ParseCastExpression(false);
1050    if (!Res.isInvalid())
1051      Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1052    return Res;
1053  }
1054
1055  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1056    // __extension__ silences extension warnings in the subexpression.
1057    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1058    SourceLocation SavedLoc = ConsumeToken();
1059    Res = ParseCastExpression(false);
1060    if (!Res.isInvalid())
1061      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1062    return Res;
1063  }
1064  case tok::kw__Alignof:   // unary-expression: '_Alignof' '(' type-name ')'
1065    if (!getLangOpts().C11)
1066      Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1067    // fallthrough
1068  case tok::kw_alignof:    // unary-expression: 'alignof' '(' type-id ')'
1069  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
1070                           // unary-expression: '__alignof' '(' type-name ')'
1071  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
1072                           // unary-expression: 'sizeof' '(' type-name ')'
1073  case tok::kw_vec_step:   // unary-expression: OpenCL 'vec_step' expression
1074  // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1075  case tok::kw___builtin_omp_required_simd_align:
1076    return ParseUnaryExprOrTypeTraitExpression();
1077  case tok::ampamp: {      // unary-expression: '&&' identifier
1078    SourceLocation AmpAmpLoc = ConsumeToken();
1079    if (Tok.isNot(tok::identifier))
1080      return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1081
1082    if (getCurScope()->getFnParent() == nullptr)
1083      return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1084
1085    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1086    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1087                                                Tok.getLocation());
1088    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1089    ConsumeToken();
1090    return Res;
1091  }
1092  case tok::kw_const_cast:
1093  case tok::kw_dynamic_cast:
1094  case tok::kw_reinterpret_cast:
1095  case tok::kw_static_cast:
1096    Res = ParseCXXCasts();
1097    break;
1098  case tok::kw_typeid:
1099    Res = ParseCXXTypeid();
1100    break;
1101  case tok::kw___uuidof:
1102    Res = ParseCXXUuidof();
1103    break;
1104  case tok::kw_this:
1105    Res = ParseCXXThis();
1106    break;
1107
1108  case tok::annot_typename:
1109    if (isStartOfObjCClassMessageMissingOpenBracket()) {
1110      ParsedType Type = getTypeAnnotation(Tok);
1111
1112      // Fake up a Declarator to use with ActOnTypeName.
1113      DeclSpec DS(AttrFactory);
1114      DS.SetRangeStart(Tok.getLocation());
1115      DS.SetRangeEnd(Tok.getLastLoc());
1116
1117      const char *PrevSpec = nullptr;
1118      unsigned DiagID;
1119      DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1120                         PrevSpec, DiagID, Type,
1121                         Actions.getASTContext().getPrintingPolicy());
1122
1123      Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1124      TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1125      if (Ty.isInvalid())
1126        break;
1127
1128      ConsumeToken();
1129      Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1130                                           Ty.get(), nullptr);
1131      break;
1132    }
1133    // Fall through
1134
1135  case tok::annot_decltype:
1136  case tok::kw_char:
1137  case tok::kw_wchar_t:
1138  case tok::kw_char16_t:
1139  case tok::kw_char32_t:
1140  case tok::kw_bool:
1141  case tok::kw_short:
1142  case tok::kw_int:
1143  case tok::kw_long:
1144  case tok::kw___int64:
1145  case tok::kw___int128:
1146  case tok::kw_signed:
1147  case tok::kw_unsigned:
1148  case tok::kw_half:
1149  case tok::kw_float:
1150  case tok::kw_double:
1151  case tok::kw_void:
1152  case tok::kw_typename:
1153  case tok::kw_typeof:
1154  case tok::kw___vector: {
1155    if (!getLangOpts().CPlusPlus) {
1156      Diag(Tok, diag::err_expected_expression);
1157      return ExprError();
1158    }
1159
1160    if (SavedKind == tok::kw_typename) {
1161      // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1162      //                     typename-specifier braced-init-list
1163      if (TryAnnotateTypeOrScopeToken())
1164        return ExprError();
1165
1166      if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1167        // We are trying to parse a simple-type-specifier but might not get such
1168        // a token after error recovery.
1169        return ExprError();
1170    }
1171
1172    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1173    //                     simple-type-specifier braced-init-list
1174    //
1175    DeclSpec DS(AttrFactory);
1176
1177    ParseCXXSimpleTypeSpecifier(DS);
1178    if (Tok.isNot(tok::l_paren) &&
1179        (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1180      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1181                         << DS.getSourceRange());
1182
1183    if (Tok.is(tok::l_brace))
1184      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1185
1186    Res = ParseCXXTypeConstructExpression(DS);
1187    break;
1188  }
1189
1190  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1191    // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1192    // (We can end up in this situation after tentative parsing.)
1193    if (TryAnnotateTypeOrScopeToken())
1194      return ExprError();
1195    if (!Tok.is(tok::annot_cxxscope))
1196      return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1197                                 NotCastExpr, isTypeCast);
1198
1199    Token Next = NextToken();
1200    if (Next.is(tok::annot_template_id)) {
1201      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1202      if (TemplateId->Kind == TNK_Type_template) {
1203        // We have a qualified template-id that we know refers to a
1204        // type, translate it into a type and continue parsing as a
1205        // cast expression.
1206        CXXScopeSpec SS;
1207        ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1208                                       /*EnteringContext=*/false);
1209        AnnotateTemplateIdTokenAsType();
1210        return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1211                                   NotCastExpr, isTypeCast);
1212      }
1213    }
1214
1215    // Parse as an id-expression.
1216    Res = ParseCXXIdExpression(isAddressOfOperand);
1217    break;
1218  }
1219
1220  case tok::annot_template_id: { // [C++]          template-id
1221    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1222    if (TemplateId->Kind == TNK_Type_template) {
1223      // We have a template-id that we know refers to a type,
1224      // translate it into a type and continue parsing as a cast
1225      // expression.
1226      AnnotateTemplateIdTokenAsType();
1227      return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1228                                 NotCastExpr, isTypeCast);
1229    }
1230
1231    // Fall through to treat the template-id as an id-expression.
1232  }
1233
1234  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1235    Res = ParseCXXIdExpression(isAddressOfOperand);
1236    break;
1237
1238  case tok::coloncolon: {
1239    // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
1240    // annotates the token, tail recurse.
1241    if (TryAnnotateTypeOrScopeToken())
1242      return ExprError();
1243    if (!Tok.is(tok::coloncolon))
1244      return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1245
1246    // ::new -> [C++] new-expression
1247    // ::delete -> [C++] delete-expression
1248    SourceLocation CCLoc = ConsumeToken();
1249    if (Tok.is(tok::kw_new))
1250      return ParseCXXNewExpression(true, CCLoc);
1251    if (Tok.is(tok::kw_delete))
1252      return ParseCXXDeleteExpression(true, CCLoc);
1253
1254    // This is not a type name or scope specifier, it is an invalid expression.
1255    Diag(CCLoc, diag::err_expected_expression);
1256    return ExprError();
1257  }
1258
1259  case tok::kw_new: // [C++] new-expression
1260    return ParseCXXNewExpression(false, Tok.getLocation());
1261
1262  case tok::kw_delete: // [C++] delete-expression
1263    return ParseCXXDeleteExpression(false, Tok.getLocation());
1264
1265  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1266    Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1267    SourceLocation KeyLoc = ConsumeToken();
1268    BalancedDelimiterTracker T(*this, tok::l_paren);
1269
1270    if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1271      return ExprError();
1272    // C++11 [expr.unary.noexcept]p1:
1273    //   The noexcept operator determines whether the evaluation of its operand,
1274    //   which is an unevaluated operand, can throw an exception.
1275    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1276    ExprResult Result = ParseExpression();
1277
1278    T.consumeClose();
1279
1280    if (!Result.isInvalid())
1281      Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1282                                         Result.get(), T.getCloseLocation());
1283    return Result;
1284  }
1285
1286#define TYPE_TRAIT(N,Spelling,K) \
1287  case tok::kw_##Spelling:
1288#include "clang/Basic/TokenKinds.def"
1289    return ParseTypeTrait();
1290
1291  case tok::kw___array_rank:
1292  case tok::kw___array_extent:
1293    return ParseArrayTypeTrait();
1294
1295  case tok::kw___is_lvalue_expr:
1296  case tok::kw___is_rvalue_expr:
1297    return ParseExpressionTrait();
1298
1299  case tok::at: {
1300    SourceLocation AtLoc = ConsumeToken();
1301    return ParseObjCAtExpression(AtLoc);
1302  }
1303  case tok::caret:
1304    Res = ParseBlockLiteralExpression();
1305    break;
1306  case tok::code_completion: {
1307    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1308    cutOffParsing();
1309    return ExprError();
1310  }
1311  case tok::l_square:
1312    if (getLangOpts().CPlusPlus11) {
1313      if (getLangOpts().ObjC1) {
1314        // C++11 lambda expressions and Objective-C message sends both start with a
1315        // square bracket.  There are three possibilities here:
1316        // we have a valid lambda expression, we have an invalid lambda
1317        // expression, or we have something that doesn't appear to be a lambda.
1318        // If we're in the last case, we fall back to ParseObjCMessageExpression.
1319        Res = TryParseLambdaExpression();
1320        if (!Res.isInvalid() && !Res.get())
1321          Res = ParseObjCMessageExpression();
1322        break;
1323      }
1324      Res = ParseLambdaExpression();
1325      break;
1326    }
1327    if (getLangOpts().ObjC1) {
1328      Res = ParseObjCMessageExpression();
1329      break;
1330    }
1331    // FALL THROUGH.
1332  default:
1333    NotCastExpr = true;
1334    return ExprError();
1335  }
1336
1337  // These can be followed by postfix-expr pieces.
1338  return ParsePostfixExpressionSuffix(Res);
1339}
1340
1341/// \brief Once the leading part of a postfix-expression is parsed, this
1342/// method parses any suffixes that apply.
1343///
1344/// \verbatim
1345///       postfix-expression: [C99 6.5.2]
1346///         primary-expression
1347///         postfix-expression '[' expression ']'
1348///         postfix-expression '[' braced-init-list ']'
1349///         postfix-expression '(' argument-expression-list[opt] ')'
1350///         postfix-expression '.' identifier
1351///         postfix-expression '->' identifier
1352///         postfix-expression '++'
1353///         postfix-expression '--'
1354///         '(' type-name ')' '{' initializer-list '}'
1355///         '(' type-name ')' '{' initializer-list ',' '}'
1356///
1357///       argument-expression-list: [C99 6.5.2]
1358///         argument-expression ...[opt]
1359///         argument-expression-list ',' assignment-expression ...[opt]
1360/// \endverbatim
1361ExprResult
1362Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1363  // Now that the primary-expression piece of the postfix-expression has been
1364  // parsed, see if there are any postfix-expression pieces here.
1365  SourceLocation Loc;
1366  while (1) {
1367    switch (Tok.getKind()) {
1368    case tok::code_completion:
1369      if (InMessageExpression)
1370        return LHS;
1371
1372      Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1373      cutOffParsing();
1374      return ExprError();
1375
1376    case tok::identifier:
1377      // If we see identifier: after an expression, and we're not already in a
1378      // message send, then this is probably a message send with a missing
1379      // opening bracket '['.
1380      if (getLangOpts().ObjC1 && !InMessageExpression &&
1381          (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1382        LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1383                                             ParsedType(), LHS.get());
1384        break;
1385      }
1386
1387      // Fall through; this isn't a message send.
1388
1389    default:  // Not a postfix-expression suffix.
1390      return LHS;
1391    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
1392      // If we have a array postfix expression that starts on a new line and
1393      // Objective-C is enabled, it is highly likely that the user forgot a
1394      // semicolon after the base expression and that the array postfix-expr is
1395      // actually another message send.  In this case, do some look-ahead to see
1396      // if the contents of the square brackets are obviously not a valid
1397      // expression and recover by pretending there is no suffix.
1398      if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1399          isSimpleObjCMessageExpression())
1400        return LHS;
1401
1402      // Reject array indices starting with a lambda-expression. '[[' is
1403      // reserved for attributes.
1404      if (CheckProhibitedCXX11Attribute())
1405        return ExprError();
1406
1407      BalancedDelimiterTracker T(*this, tok::l_square);
1408      T.consumeOpen();
1409      Loc = T.getOpenLocation();
1410      ExprResult Idx, Length;
1411      SourceLocation ColonLoc;
1412      if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1413        Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1414        Idx = ParseBraceInitializer();
1415      } else if (getLangOpts().OpenMP) {
1416        ColonProtectionRAIIObject RAII(*this);
1417        // Parse [: or [ expr or [ expr :
1418        if (!Tok.is(tok::colon)) {
1419          // [ expr
1420          Idx = ParseExpression();
1421        }
1422        if (Tok.is(tok::colon)) {
1423          // Consume ':'
1424          ColonLoc = ConsumeToken();
1425          if (Tok.isNot(tok::r_square))
1426            Length = ParseExpression();
1427        }
1428      } else
1429        Idx = ParseExpression();
1430
1431      SourceLocation RLoc = Tok.getLocation();
1432
1433      if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1434          Tok.is(tok::r_square)) {
1435        if (ColonLoc.isValid()) {
1436          LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1437                                                 ColonLoc, Length.get(), RLoc);
1438        } else {
1439          LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1440                                                Idx.get(), RLoc);
1441        }
1442      } else {
1443        (void)Actions.CorrectDelayedTyposInExpr(LHS);
1444        (void)Actions.CorrectDelayedTyposInExpr(Idx);
1445        (void)Actions.CorrectDelayedTyposInExpr(Length);
1446        LHS = ExprError();
1447        Idx = ExprError();
1448      }
1449
1450      // Match the ']'.
1451      T.consumeClose();
1452      break;
1453    }
1454
1455    case tok::l_paren:         // p-e: p-e '(' argument-expression-list[opt] ')'
1456    case tok::lesslessless: {  // p-e: p-e '<<<' argument-expression-list '>>>'
1457                               //   '(' argument-expression-list[opt] ')'
1458      tok::TokenKind OpKind = Tok.getKind();
1459      InMessageExpressionRAIIObject InMessage(*this, false);
1460
1461      Expr *ExecConfig = nullptr;
1462
1463      BalancedDelimiterTracker PT(*this, tok::l_paren);
1464
1465      if (OpKind == tok::lesslessless) {
1466        ExprVector ExecConfigExprs;
1467        CommaLocsTy ExecConfigCommaLocs;
1468        SourceLocation OpenLoc = ConsumeToken();
1469
1470        if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1471          (void)Actions.CorrectDelayedTyposInExpr(LHS);
1472          LHS = ExprError();
1473        }
1474
1475        SourceLocation CloseLoc;
1476        if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1477        } else if (LHS.isInvalid()) {
1478          SkipUntil(tok::greatergreatergreater, StopAtSemi);
1479        } else {
1480          // There was an error closing the brackets
1481          Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1482          Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1483          SkipUntil(tok::greatergreatergreater, StopAtSemi);
1484          LHS = ExprError();
1485        }
1486
1487        if (!LHS.isInvalid()) {
1488          if (ExpectAndConsume(tok::l_paren))
1489            LHS = ExprError();
1490          else
1491            Loc = PrevTokLocation;
1492        }
1493
1494        if (!LHS.isInvalid()) {
1495          ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1496                                    OpenLoc,
1497                                    ExecConfigExprs,
1498                                    CloseLoc);
1499          if (ECResult.isInvalid())
1500            LHS = ExprError();
1501          else
1502            ExecConfig = ECResult.get();
1503        }
1504      } else {
1505        PT.consumeOpen();
1506        Loc = PT.getOpenLocation();
1507      }
1508
1509      ExprVector ArgExprs;
1510      CommaLocsTy CommaLocs;
1511
1512      if (Tok.is(tok::code_completion)) {
1513        Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1514        cutOffParsing();
1515        return ExprError();
1516      }
1517
1518      if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1519        if (Tok.isNot(tok::r_paren)) {
1520          if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1521                Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1522             })) {
1523            (void)Actions.CorrectDelayedTyposInExpr(LHS);
1524            LHS = ExprError();
1525          } else if (LHS.isInvalid()) {
1526            for (auto &E : ArgExprs)
1527              Actions.CorrectDelayedTyposInExpr(E);
1528          }
1529        }
1530      }
1531
1532      // Match the ')'.
1533      if (LHS.isInvalid()) {
1534        SkipUntil(tok::r_paren, StopAtSemi);
1535      } else if (Tok.isNot(tok::r_paren)) {
1536        bool HadDelayedTypo = false;
1537        if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1538          HadDelayedTypo = true;
1539        for (auto &E : ArgExprs)
1540          if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1541            HadDelayedTypo = true;
1542        // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1543        // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1544        // the unmatched l_paren.
1545        if (HadDelayedTypo)
1546          SkipUntil(tok::r_paren, StopAtSemi);
1547        else
1548          PT.consumeClose();
1549        LHS = ExprError();
1550      } else {
1551        assert((ArgExprs.size() == 0 ||
1552                ArgExprs.size()-1 == CommaLocs.size())&&
1553               "Unexpected number of commas!");
1554        LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1555                                    ArgExprs, Tok.getLocation(),
1556                                    ExecConfig);
1557        PT.consumeClose();
1558      }
1559
1560      break;
1561    }
1562    case tok::arrow:
1563    case tok::period: {
1564      // postfix-expression: p-e '->' template[opt] id-expression
1565      // postfix-expression: p-e '.' template[opt] id-expression
1566      tok::TokenKind OpKind = Tok.getKind();
1567      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
1568
1569      CXXScopeSpec SS;
1570      ParsedType ObjectType;
1571      bool MayBePseudoDestructor = false;
1572      if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1573        Expr *Base = LHS.get();
1574        const Type* BaseType = Base->getType().getTypePtrOrNull();
1575        if (BaseType && Tok.is(tok::l_paren) &&
1576            (BaseType->isFunctionType() ||
1577             BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1578          Diag(OpLoc, diag::err_function_is_not_record)
1579              << OpKind << Base->getSourceRange()
1580              << FixItHint::CreateRemoval(OpLoc);
1581          return ParsePostfixExpressionSuffix(Base);
1582        }
1583
1584        LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1585                                                   OpLoc, OpKind, ObjectType,
1586                                                   MayBePseudoDestructor);
1587        if (LHS.isInvalid())
1588          break;
1589
1590        ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1591                                       /*EnteringContext=*/false,
1592                                       &MayBePseudoDestructor);
1593        if (SS.isNotEmpty())
1594          ObjectType = ParsedType();
1595      }
1596
1597      if (Tok.is(tok::code_completion)) {
1598        // Code completion for a member access expression.
1599        Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1600                                                OpLoc, OpKind == tok::arrow);
1601
1602        cutOffParsing();
1603        return ExprError();
1604      }
1605
1606      if (MayBePseudoDestructor && !LHS.isInvalid()) {
1607        LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1608                                       ObjectType);
1609        break;
1610      }
1611
1612      // Either the action has told us that this cannot be a
1613      // pseudo-destructor expression (based on the type of base
1614      // expression), or we didn't see a '~' in the right place. We
1615      // can still parse a destructor name here, but in that case it
1616      // names a real destructor.
1617      // Allow explicit constructor calls in Microsoft mode.
1618      // FIXME: Add support for explicit call of template constructor.
1619      SourceLocation TemplateKWLoc;
1620      UnqualifiedId Name;
1621      if (getLangOpts().ObjC2 && OpKind == tok::period &&
1622          Tok.is(tok::kw_class)) {
1623        // Objective-C++:
1624        //   After a '.' in a member access expression, treat the keyword
1625        //   'class' as if it were an identifier.
1626        //
1627        // This hack allows property access to the 'class' method because it is
1628        // such a common method name. For other C++ keywords that are
1629        // Objective-C method names, one must use the message send syntax.
1630        IdentifierInfo *Id = Tok.getIdentifierInfo();
1631        SourceLocation Loc = ConsumeToken();
1632        Name.setIdentifier(Id, Loc);
1633      } else if (ParseUnqualifiedId(SS,
1634                                    /*EnteringContext=*/false,
1635                                    /*AllowDestructorName=*/true,
1636                                    /*AllowConstructorName=*/
1637                                      getLangOpts().MicrosoftExt,
1638                                    ObjectType, TemplateKWLoc, Name)) {
1639        (void)Actions.CorrectDelayedTyposInExpr(LHS);
1640        LHS = ExprError();
1641      }
1642
1643      if (!LHS.isInvalid())
1644        LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1645                                            OpKind, SS, TemplateKWLoc, Name,
1646                                 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1647                                                   : nullptr);
1648      break;
1649    }
1650    case tok::plusplus:    // postfix-expression: postfix-expression '++'
1651    case tok::minusminus:  // postfix-expression: postfix-expression '--'
1652      if (!LHS.isInvalid()) {
1653        LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1654                                          Tok.getKind(), LHS.get());
1655      }
1656      ConsumeToken();
1657      break;
1658    }
1659  }
1660}
1661
1662/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1663/// vec_step and we are at the start of an expression or a parenthesized
1664/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1665/// expression (isCastExpr == false) or the type (isCastExpr == true).
1666///
1667/// \verbatim
1668///       unary-expression:  [C99 6.5.3]
1669///         'sizeof' unary-expression
1670///         'sizeof' '(' type-name ')'
1671/// [GNU]   '__alignof' unary-expression
1672/// [GNU]   '__alignof' '(' type-name ')'
1673/// [C11]   '_Alignof' '(' type-name ')'
1674/// [C++0x] 'alignof' '(' type-id ')'
1675///
1676/// [GNU]   typeof-specifier:
1677///           typeof ( expressions )
1678///           typeof ( type-name )
1679/// [GNU/C++] typeof unary-expression
1680///
1681/// [OpenCL 1.1 6.11.12] vec_step built-in function:
1682///           vec_step ( expressions )
1683///           vec_step ( type-name )
1684/// \endverbatim
1685ExprResult
1686Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1687                                           bool &isCastExpr,
1688                                           ParsedType &CastTy,
1689                                           SourceRange &CastRange) {
1690
1691  assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1692                       tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1693                       tok::kw___builtin_omp_required_simd_align) &&
1694         "Not a typeof/sizeof/alignof/vec_step expression!");
1695
1696  ExprResult Operand;
1697
1698  // If the operand doesn't start with an '(', it must be an expression.
1699  if (Tok.isNot(tok::l_paren)) {
1700    // If construct allows a form without parenthesis, user may forget to put
1701    // pathenthesis around type name.
1702    if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1703                      tok::kw__Alignof)) {
1704      if (isTypeIdUnambiguously()) {
1705        DeclSpec DS(AttrFactory);
1706        ParseSpecifierQualifierList(DS);
1707        Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1708        ParseDeclarator(DeclaratorInfo);
1709
1710        SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1711        SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1712        Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1713          << OpTok.getName()
1714          << FixItHint::CreateInsertion(LParenLoc, "(")
1715          << FixItHint::CreateInsertion(RParenLoc, ")");
1716        isCastExpr = true;
1717        return ExprEmpty();
1718      }
1719    }
1720
1721    isCastExpr = false;
1722    if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1723      Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1724                                          << tok::l_paren;
1725      return ExprError();
1726    }
1727
1728    Operand = ParseCastExpression(true/*isUnaryExpression*/);
1729  } else {
1730    // If it starts with a '(', we know that it is either a parenthesized
1731    // type-name, or it is a unary-expression that starts with a compound
1732    // literal, or starts with a primary-expression that is a parenthesized
1733    // expression.
1734    ParenParseOption ExprType = CastExpr;
1735    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1736
1737    Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1738                                   false, CastTy, RParenLoc);
1739    CastRange = SourceRange(LParenLoc, RParenLoc);
1740
1741    // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1742    // a type.
1743    if (ExprType == CastExpr) {
1744      isCastExpr = true;
1745      return ExprEmpty();
1746    }
1747
1748    if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1749      // GNU typeof in C requires the expression to be parenthesized. Not so for
1750      // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1751      // the start of a unary-expression, but doesn't include any postfix
1752      // pieces. Parse these now if present.
1753      if (!Operand.isInvalid())
1754        Operand = ParsePostfixExpressionSuffix(Operand.get());
1755    }
1756  }
1757
1758  // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1759  isCastExpr = false;
1760  return Operand;
1761}
1762
1763
1764/// \brief Parse a sizeof or alignof expression.
1765///
1766/// \verbatim
1767///       unary-expression:  [C99 6.5.3]
1768///         'sizeof' unary-expression
1769///         'sizeof' '(' type-name ')'
1770/// [C++11] 'sizeof' '...' '(' identifier ')'
1771/// [GNU]   '__alignof' unary-expression
1772/// [GNU]   '__alignof' '(' type-name ')'
1773/// [C11]   '_Alignof' '(' type-name ')'
1774/// [C++11] 'alignof' '(' type-id ')'
1775/// \endverbatim
1776ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1777  assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1778                     tok::kw__Alignof, tok::kw_vec_step,
1779                     tok::kw___builtin_omp_required_simd_align) &&
1780         "Not a sizeof/alignof/vec_step expression!");
1781  Token OpTok = Tok;
1782  ConsumeToken();
1783
1784  // [C++11] 'sizeof' '...' '(' identifier ')'
1785  if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1786    SourceLocation EllipsisLoc = ConsumeToken();
1787    SourceLocation LParenLoc, RParenLoc;
1788    IdentifierInfo *Name = nullptr;
1789    SourceLocation NameLoc;
1790    if (Tok.is(tok::l_paren)) {
1791      BalancedDelimiterTracker T(*this, tok::l_paren);
1792      T.consumeOpen();
1793      LParenLoc = T.getOpenLocation();
1794      if (Tok.is(tok::identifier)) {
1795        Name = Tok.getIdentifierInfo();
1796        NameLoc = ConsumeToken();
1797        T.consumeClose();
1798        RParenLoc = T.getCloseLocation();
1799        if (RParenLoc.isInvalid())
1800          RParenLoc = PP.getLocForEndOfToken(NameLoc);
1801      } else {
1802        Diag(Tok, diag::err_expected_parameter_pack);
1803        SkipUntil(tok::r_paren, StopAtSemi);
1804      }
1805    } else if (Tok.is(tok::identifier)) {
1806      Name = Tok.getIdentifierInfo();
1807      NameLoc = ConsumeToken();
1808      LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1809      RParenLoc = PP.getLocForEndOfToken(NameLoc);
1810      Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1811        << Name
1812        << FixItHint::CreateInsertion(LParenLoc, "(")
1813        << FixItHint::CreateInsertion(RParenLoc, ")");
1814    } else {
1815      Diag(Tok, diag::err_sizeof_parameter_pack);
1816    }
1817
1818    if (!Name)
1819      return ExprError();
1820
1821    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1822                                                 Sema::ReuseLambdaContextDecl);
1823
1824    return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1825                                                OpTok.getLocation(),
1826                                                *Name, NameLoc,
1827                                                RParenLoc);
1828  }
1829
1830  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1831    Diag(OpTok, diag::warn_cxx98_compat_alignof);
1832
1833  EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1834                                               Sema::ReuseLambdaContextDecl);
1835
1836  bool isCastExpr;
1837  ParsedType CastTy;
1838  SourceRange CastRange;
1839  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1840                                                          isCastExpr,
1841                                                          CastTy,
1842                                                          CastRange);
1843
1844  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1845  if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1846    ExprKind = UETT_AlignOf;
1847  else if (OpTok.is(tok::kw_vec_step))
1848    ExprKind = UETT_VecStep;
1849  else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
1850    ExprKind = UETT_OpenMPRequiredSimdAlign;
1851
1852  if (isCastExpr)
1853    return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1854                                                 ExprKind,
1855                                                 /*isType=*/true,
1856                                                 CastTy.getAsOpaquePtr(),
1857                                                 CastRange);
1858
1859  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1860    Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1861
1862  // If we get here, the operand to the sizeof/alignof was an expresion.
1863  if (!Operand.isInvalid())
1864    Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1865                                                    ExprKind,
1866                                                    /*isType=*/false,
1867                                                    Operand.get(),
1868                                                    CastRange);
1869  return Operand;
1870}
1871
1872/// ParseBuiltinPrimaryExpression
1873///
1874/// \verbatim
1875///       primary-expression: [C99 6.5.1]
1876/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1877/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1878/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1879///                                     assign-expr ')'
1880/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1881/// [OCL]   '__builtin_astype' '(' assignment-expression ',' type-name ')'
1882///
1883/// [GNU] offsetof-member-designator:
1884/// [GNU]   identifier
1885/// [GNU]   offsetof-member-designator '.' identifier
1886/// [GNU]   offsetof-member-designator '[' expression ']'
1887/// \endverbatim
1888ExprResult Parser::ParseBuiltinPrimaryExpression() {
1889  ExprResult Res;
1890  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1891
1892  tok::TokenKind T = Tok.getKind();
1893  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
1894
1895  // All of these start with an open paren.
1896  if (Tok.isNot(tok::l_paren))
1897    return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
1898                                                         << tok::l_paren);
1899
1900  BalancedDelimiterTracker PT(*this, tok::l_paren);
1901  PT.consumeOpen();
1902
1903  // TODO: Build AST.
1904
1905  switch (T) {
1906  default: llvm_unreachable("Not a builtin primary expression!");
1907  case tok::kw___builtin_va_arg: {
1908    ExprResult Expr(ParseAssignmentExpression());
1909
1910    if (ExpectAndConsume(tok::comma)) {
1911      SkipUntil(tok::r_paren, StopAtSemi);
1912      Expr = ExprError();
1913    }
1914
1915    TypeResult Ty = ParseTypeName();
1916
1917    if (Tok.isNot(tok::r_paren)) {
1918      Diag(Tok, diag::err_expected) << tok::r_paren;
1919      Expr = ExprError();
1920    }
1921
1922    if (Expr.isInvalid() || Ty.isInvalid())
1923      Res = ExprError();
1924    else
1925      Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
1926    break;
1927  }
1928  case tok::kw___builtin_offsetof: {
1929    SourceLocation TypeLoc = Tok.getLocation();
1930    TypeResult Ty = ParseTypeName();
1931    if (Ty.isInvalid()) {
1932      SkipUntil(tok::r_paren, StopAtSemi);
1933      return ExprError();
1934    }
1935
1936    if (ExpectAndConsume(tok::comma)) {
1937      SkipUntil(tok::r_paren, StopAtSemi);
1938      return ExprError();
1939    }
1940
1941    // We must have at least one identifier here.
1942    if (Tok.isNot(tok::identifier)) {
1943      Diag(Tok, diag::err_expected) << tok::identifier;
1944      SkipUntil(tok::r_paren, StopAtSemi);
1945      return ExprError();
1946    }
1947
1948    // Keep track of the various subcomponents we see.
1949    SmallVector<Sema::OffsetOfComponent, 4> Comps;
1950
1951    Comps.push_back(Sema::OffsetOfComponent());
1952    Comps.back().isBrackets = false;
1953    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1954    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1955
1956    // FIXME: This loop leaks the index expressions on error.
1957    while (1) {
1958      if (Tok.is(tok::period)) {
1959        // offsetof-member-designator: offsetof-member-designator '.' identifier
1960        Comps.push_back(Sema::OffsetOfComponent());
1961        Comps.back().isBrackets = false;
1962        Comps.back().LocStart = ConsumeToken();
1963
1964        if (Tok.isNot(tok::identifier)) {
1965          Diag(Tok, diag::err_expected) << tok::identifier;
1966          SkipUntil(tok::r_paren, StopAtSemi);
1967          return ExprError();
1968        }
1969        Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1970        Comps.back().LocEnd = ConsumeToken();
1971
1972      } else if (Tok.is(tok::l_square)) {
1973        if (CheckProhibitedCXX11Attribute())
1974          return ExprError();
1975
1976        // offsetof-member-designator: offsetof-member-design '[' expression ']'
1977        Comps.push_back(Sema::OffsetOfComponent());
1978        Comps.back().isBrackets = true;
1979        BalancedDelimiterTracker ST(*this, tok::l_square);
1980        ST.consumeOpen();
1981        Comps.back().LocStart = ST.getOpenLocation();
1982        Res = ParseExpression();
1983        if (Res.isInvalid()) {
1984          SkipUntil(tok::r_paren, StopAtSemi);
1985          return Res;
1986        }
1987        Comps.back().U.E = Res.get();
1988
1989        ST.consumeClose();
1990        Comps.back().LocEnd = ST.getCloseLocation();
1991      } else {
1992        if (Tok.isNot(tok::r_paren)) {
1993          PT.consumeClose();
1994          Res = ExprError();
1995        } else if (Ty.isInvalid()) {
1996          Res = ExprError();
1997        } else {
1998          PT.consumeClose();
1999          Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2000                                             Ty.get(), Comps,
2001                                             PT.getCloseLocation());
2002        }
2003        break;
2004      }
2005    }
2006    break;
2007  }
2008  case tok::kw___builtin_choose_expr: {
2009    ExprResult Cond(ParseAssignmentExpression());
2010    if (Cond.isInvalid()) {
2011      SkipUntil(tok::r_paren, StopAtSemi);
2012      return Cond;
2013    }
2014    if (ExpectAndConsume(tok::comma)) {
2015      SkipUntil(tok::r_paren, StopAtSemi);
2016      return ExprError();
2017    }
2018
2019    ExprResult Expr1(ParseAssignmentExpression());
2020    if (Expr1.isInvalid()) {
2021      SkipUntil(tok::r_paren, StopAtSemi);
2022      return Expr1;
2023    }
2024    if (ExpectAndConsume(tok::comma)) {
2025      SkipUntil(tok::r_paren, StopAtSemi);
2026      return ExprError();
2027    }
2028
2029    ExprResult Expr2(ParseAssignmentExpression());
2030    if (Expr2.isInvalid()) {
2031      SkipUntil(tok::r_paren, StopAtSemi);
2032      return Expr2;
2033    }
2034    if (Tok.isNot(tok::r_paren)) {
2035      Diag(Tok, diag::err_expected) << tok::r_paren;
2036      return ExprError();
2037    }
2038    Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2039                                  Expr2.get(), ConsumeParen());
2040    break;
2041  }
2042  case tok::kw___builtin_astype: {
2043    // The first argument is an expression to be converted, followed by a comma.
2044    ExprResult Expr(ParseAssignmentExpression());
2045    if (Expr.isInvalid()) {
2046      SkipUntil(tok::r_paren, StopAtSemi);
2047      return ExprError();
2048    }
2049
2050    if (ExpectAndConsume(tok::comma)) {
2051      SkipUntil(tok::r_paren, StopAtSemi);
2052      return ExprError();
2053    }
2054
2055    // Second argument is the type to bitcast to.
2056    TypeResult DestTy = ParseTypeName();
2057    if (DestTy.isInvalid())
2058      return ExprError();
2059
2060    // Attempt to consume the r-paren.
2061    if (Tok.isNot(tok::r_paren)) {
2062      Diag(Tok, diag::err_expected) << tok::r_paren;
2063      SkipUntil(tok::r_paren, StopAtSemi);
2064      return ExprError();
2065    }
2066
2067    Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2068                                  ConsumeParen());
2069    break;
2070  }
2071  case tok::kw___builtin_convertvector: {
2072    // The first argument is an expression to be converted, followed by a comma.
2073    ExprResult Expr(ParseAssignmentExpression());
2074    if (Expr.isInvalid()) {
2075      SkipUntil(tok::r_paren, StopAtSemi);
2076      return ExprError();
2077    }
2078
2079    if (ExpectAndConsume(tok::comma)) {
2080      SkipUntil(tok::r_paren, StopAtSemi);
2081      return ExprError();
2082    }
2083
2084    // Second argument is the type to bitcast to.
2085    TypeResult DestTy = ParseTypeName();
2086    if (DestTy.isInvalid())
2087      return ExprError();
2088
2089    // Attempt to consume the r-paren.
2090    if (Tok.isNot(tok::r_paren)) {
2091      Diag(Tok, diag::err_expected) << tok::r_paren;
2092      SkipUntil(tok::r_paren, StopAtSemi);
2093      return ExprError();
2094    }
2095
2096    Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2097                                         ConsumeParen());
2098    break;
2099  }
2100  }
2101
2102  if (Res.isInvalid())
2103    return ExprError();
2104
2105  // These can be followed by postfix-expr pieces because they are
2106  // primary-expressions.
2107  return ParsePostfixExpressionSuffix(Res.get());
2108}
2109
2110/// ParseParenExpression - This parses the unit that starts with a '(' token,
2111/// based on what is allowed by ExprType.  The actual thing parsed is returned
2112/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2113/// not the parsed cast-expression.
2114///
2115/// \verbatim
2116///       primary-expression: [C99 6.5.1]
2117///         '(' expression ')'
2118/// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
2119///       postfix-expression: [C99 6.5.2]
2120///         '(' type-name ')' '{' initializer-list '}'
2121///         '(' type-name ')' '{' initializer-list ',' '}'
2122///       cast-expression: [C99 6.5.4]
2123///         '(' type-name ')' cast-expression
2124/// [ARC]   bridged-cast-expression
2125/// [ARC] bridged-cast-expression:
2126///         (__bridge type-name) cast-expression
2127///         (__bridge_transfer type-name) cast-expression
2128///         (__bridge_retained type-name) cast-expression
2129///       fold-expression: [C++1z]
2130///         '(' cast-expression fold-operator '...' ')'
2131///         '(' '...' fold-operator cast-expression ')'
2132///         '(' cast-expression fold-operator '...'
2133///                 fold-operator cast-expression ')'
2134/// \endverbatim
2135ExprResult
2136Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2137                             bool isTypeCast, ParsedType &CastTy,
2138                             SourceLocation &RParenLoc) {
2139  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2140  ColonProtectionRAIIObject ColonProtection(*this, false);
2141  BalancedDelimiterTracker T(*this, tok::l_paren);
2142  if (T.consumeOpen())
2143    return ExprError();
2144  SourceLocation OpenLoc = T.getOpenLocation();
2145
2146  ExprResult Result(true);
2147  bool isAmbiguousTypeId;
2148  CastTy = ParsedType();
2149
2150  if (Tok.is(tok::code_completion)) {
2151    Actions.CodeCompleteOrdinaryName(getCurScope(),
2152                 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2153                                            : Sema::PCC_Expression);
2154    cutOffParsing();
2155    return ExprError();
2156  }
2157
2158  // Diagnose use of bridge casts in non-arc mode.
2159  bool BridgeCast = (getLangOpts().ObjC2 &&
2160                     Tok.isOneOf(tok::kw___bridge,
2161                                 tok::kw___bridge_transfer,
2162                                 tok::kw___bridge_retained,
2163                                 tok::kw___bridge_retain));
2164  if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2165    if (!TryConsumeToken(tok::kw___bridge)) {
2166      StringRef BridgeCastName = Tok.getName();
2167      SourceLocation BridgeKeywordLoc = ConsumeToken();
2168      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2169        Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2170          << BridgeCastName
2171          << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2172    }
2173    BridgeCast = false;
2174  }
2175
2176  // None of these cases should fall through with an invalid Result
2177  // unless they've already reported an error.
2178  if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2179    Diag(Tok, diag::ext_gnu_statement_expr);
2180
2181    if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2182      Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2183    } else {
2184      // Find the nearest non-record decl context. Variables declared in a
2185      // statement expression behave as if they were declared in the enclosing
2186      // function, block, or other code construct.
2187      DeclContext *CodeDC = Actions.CurContext;
2188      while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2189        CodeDC = CodeDC->getParent();
2190        assert(CodeDC && !CodeDC->isFileContext() &&
2191               "statement expr not in code context");
2192      }
2193      Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2194
2195      Actions.ActOnStartStmtExpr();
2196
2197      StmtResult Stmt(ParseCompoundStatement(true));
2198      ExprType = CompoundStmt;
2199
2200      // If the substmt parsed correctly, build the AST node.
2201      if (!Stmt.isInvalid()) {
2202        Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2203      } else {
2204        Actions.ActOnStmtExprError();
2205      }
2206    }
2207  } else if (ExprType >= CompoundLiteral && BridgeCast) {
2208    tok::TokenKind tokenKind = Tok.getKind();
2209    SourceLocation BridgeKeywordLoc = ConsumeToken();
2210
2211    // Parse an Objective-C ARC ownership cast expression.
2212    ObjCBridgeCastKind Kind;
2213    if (tokenKind == tok::kw___bridge)
2214      Kind = OBC_Bridge;
2215    else if (tokenKind == tok::kw___bridge_transfer)
2216      Kind = OBC_BridgeTransfer;
2217    else if (tokenKind == tok::kw___bridge_retained)
2218      Kind = OBC_BridgeRetained;
2219    else {
2220      // As a hopefully temporary workaround, allow __bridge_retain as
2221      // a synonym for __bridge_retained, but only in system headers.
2222      assert(tokenKind == tok::kw___bridge_retain);
2223      Kind = OBC_BridgeRetained;
2224      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2225        Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2226          << FixItHint::CreateReplacement(BridgeKeywordLoc,
2227                                          "__bridge_retained");
2228    }
2229
2230    TypeResult Ty = ParseTypeName();
2231    T.consumeClose();
2232    ColonProtection.restore();
2233    RParenLoc = T.getCloseLocation();
2234    ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2235
2236    if (Ty.isInvalid() || SubExpr.isInvalid())
2237      return ExprError();
2238
2239    return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2240                                        BridgeKeywordLoc, Ty.get(),
2241                                        RParenLoc, SubExpr.get());
2242  } else if (ExprType >= CompoundLiteral &&
2243             isTypeIdInParens(isAmbiguousTypeId)) {
2244
2245    // Otherwise, this is a compound literal expression or cast expression.
2246
2247    // In C++, if the type-id is ambiguous we disambiguate based on context.
2248    // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2249    // in which case we should treat it as type-id.
2250    // if stopIfCastExpr is false, we need to determine the context past the
2251    // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2252    if (isAmbiguousTypeId && !stopIfCastExpr) {
2253      ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2254                                                        ColonProtection);
2255      RParenLoc = T.getCloseLocation();
2256      return res;
2257    }
2258
2259    // Parse the type declarator.
2260    DeclSpec DS(AttrFactory);
2261    ParseSpecifierQualifierList(DS);
2262    Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2263    ParseDeclarator(DeclaratorInfo);
2264
2265    // If our type is followed by an identifier and either ':' or ']', then
2266    // this is probably an Objective-C message send where the leading '[' is
2267    // missing. Recover as if that were the case.
2268    if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2269        !InMessageExpression && getLangOpts().ObjC1 &&
2270        (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2271      TypeResult Ty;
2272      {
2273        InMessageExpressionRAIIObject InMessage(*this, false);
2274        Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2275      }
2276      Result = ParseObjCMessageExpressionBody(SourceLocation(),
2277                                              SourceLocation(),
2278                                              Ty.get(), nullptr);
2279    } else {
2280      // Match the ')'.
2281      T.consumeClose();
2282      ColonProtection.restore();
2283      RParenLoc = T.getCloseLocation();
2284      if (Tok.is(tok::l_brace)) {
2285        ExprType = CompoundLiteral;
2286        TypeResult Ty;
2287        {
2288          InMessageExpressionRAIIObject InMessage(*this, false);
2289          Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2290        }
2291        return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2292      }
2293
2294      if (ExprType == CastExpr) {
2295        // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2296
2297        if (DeclaratorInfo.isInvalidType())
2298          return ExprError();
2299
2300        // Note that this doesn't parse the subsequent cast-expression, it just
2301        // returns the parsed type to the callee.
2302        if (stopIfCastExpr) {
2303          TypeResult Ty;
2304          {
2305            InMessageExpressionRAIIObject InMessage(*this, false);
2306            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2307          }
2308          CastTy = Ty.get();
2309          return ExprResult();
2310        }
2311
2312        // Reject the cast of super idiom in ObjC.
2313        if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2314            Tok.getIdentifierInfo() == Ident_super &&
2315            getCurScope()->isInObjcMethodScope() &&
2316            GetLookAheadToken(1).isNot(tok::period)) {
2317          Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2318            << SourceRange(OpenLoc, RParenLoc);
2319          return ExprError();
2320        }
2321
2322        // Parse the cast-expression that follows it next.
2323        // TODO: For cast expression with CastTy.
2324        Result = ParseCastExpression(/*isUnaryExpression=*/false,
2325                                     /*isAddressOfOperand=*/false,
2326                                     /*isTypeCast=*/IsTypeCast);
2327        if (!Result.isInvalid()) {
2328          Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2329                                         DeclaratorInfo, CastTy,
2330                                         RParenLoc, Result.get());
2331        }
2332        return Result;
2333      }
2334
2335      Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2336      return ExprError();
2337    }
2338  } else if (Tok.is(tok::ellipsis) &&
2339             isFoldOperator(NextToken().getKind())) {
2340    return ParseFoldExpression(ExprResult(), T);
2341  } else if (isTypeCast) {
2342    // Parse the expression-list.
2343    InMessageExpressionRAIIObject InMessage(*this, false);
2344
2345    ExprVector ArgExprs;
2346    CommaLocsTy CommaLocs;
2347
2348    if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2349      // FIXME: If we ever support comma expressions as operands to
2350      // fold-expressions, we'll need to allow multiple ArgExprs here.
2351      if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2352          NextToken().is(tok::ellipsis))
2353        return ParseFoldExpression(Result, T);
2354
2355      ExprType = SimpleExpr;
2356      Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2357                                          ArgExprs);
2358    }
2359  } else {
2360    InMessageExpressionRAIIObject InMessage(*this, false);
2361
2362    Result = ParseExpression(MaybeTypeCast);
2363    if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2364      // Correct typos in non-C++ code earlier so that implicit-cast-like
2365      // expressions are parsed correctly.
2366      Result = Actions.CorrectDelayedTyposInExpr(Result);
2367    }
2368    ExprType = SimpleExpr;
2369
2370    if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2371      return ParseFoldExpression(Result, T);
2372
2373    // Don't build a paren expression unless we actually match a ')'.
2374    if (!Result.isInvalid() && Tok.is(tok::r_paren))
2375      Result =
2376          Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2377  }
2378
2379  // Match the ')'.
2380  if (Result.isInvalid()) {
2381    SkipUntil(tok::r_paren, StopAtSemi);
2382    return ExprError();
2383  }
2384
2385  T.consumeClose();
2386  RParenLoc = T.getCloseLocation();
2387  return Result;
2388}
2389
2390/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2391/// and we are at the left brace.
2392///
2393/// \verbatim
2394///       postfix-expression: [C99 6.5.2]
2395///         '(' type-name ')' '{' initializer-list '}'
2396///         '(' type-name ')' '{' initializer-list ',' '}'
2397/// \endverbatim
2398ExprResult
2399Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2400                                       SourceLocation LParenLoc,
2401                                       SourceLocation RParenLoc) {
2402  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2403  if (!getLangOpts().C99)   // Compound literals don't exist in C90.
2404    Diag(LParenLoc, diag::ext_c99_compound_literal);
2405  ExprResult Result = ParseInitializer();
2406  if (!Result.isInvalid() && Ty)
2407    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2408  return Result;
2409}
2410
2411/// ParseStringLiteralExpression - This handles the various token types that
2412/// form string literals, and also handles string concatenation [C99 5.1.1.2,
2413/// translation phase #6].
2414///
2415/// \verbatim
2416///       primary-expression: [C99 6.5.1]
2417///         string-literal
2418/// \verbatim
2419ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2420  assert(isTokenStringLiteral() && "Not a string literal!");
2421
2422  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
2423  // considered to be strings for concatenation purposes.
2424  SmallVector<Token, 4> StringToks;
2425
2426  do {
2427    StringToks.push_back(Tok);
2428    ConsumeStringToken();
2429  } while (isTokenStringLiteral());
2430
2431  // Pass the set of string tokens, ready for concatenation, to the actions.
2432  return Actions.ActOnStringLiteral(StringToks,
2433                                    AllowUserDefinedLiteral ? getCurScope()
2434                                                            : nullptr);
2435}
2436
2437/// ParseGenericSelectionExpression - Parse a C11 generic-selection
2438/// [C11 6.5.1.1].
2439///
2440/// \verbatim
2441///    generic-selection:
2442///           _Generic ( assignment-expression , generic-assoc-list )
2443///    generic-assoc-list:
2444///           generic-association
2445///           generic-assoc-list , generic-association
2446///    generic-association:
2447///           type-name : assignment-expression
2448///           default : assignment-expression
2449/// \endverbatim
2450ExprResult Parser::ParseGenericSelectionExpression() {
2451  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2452  SourceLocation KeyLoc = ConsumeToken();
2453
2454  if (!getLangOpts().C11)
2455    Diag(KeyLoc, diag::ext_c11_generic_selection);
2456
2457  BalancedDelimiterTracker T(*this, tok::l_paren);
2458  if (T.expectAndConsume())
2459    return ExprError();
2460
2461  ExprResult ControllingExpr;
2462  {
2463    // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2464    // not evaluated."
2465    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2466    ControllingExpr =
2467        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2468    if (ControllingExpr.isInvalid()) {
2469      SkipUntil(tok::r_paren, StopAtSemi);
2470      return ExprError();
2471    }
2472  }
2473
2474  if (ExpectAndConsume(tok::comma)) {
2475    SkipUntil(tok::r_paren, StopAtSemi);
2476    return ExprError();
2477  }
2478
2479  SourceLocation DefaultLoc;
2480  TypeVector Types;
2481  ExprVector Exprs;
2482  do {
2483    ParsedType Ty;
2484    if (Tok.is(tok::kw_default)) {
2485      // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2486      // generic association."
2487      if (!DefaultLoc.isInvalid()) {
2488        Diag(Tok, diag::err_duplicate_default_assoc);
2489        Diag(DefaultLoc, diag::note_previous_default_assoc);
2490        SkipUntil(tok::r_paren, StopAtSemi);
2491        return ExprError();
2492      }
2493      DefaultLoc = ConsumeToken();
2494      Ty = ParsedType();
2495    } else {
2496      ColonProtectionRAIIObject X(*this);
2497      TypeResult TR = ParseTypeName();
2498      if (TR.isInvalid()) {
2499        SkipUntil(tok::r_paren, StopAtSemi);
2500        return ExprError();
2501      }
2502      Ty = TR.get();
2503    }
2504    Types.push_back(Ty);
2505
2506    if (ExpectAndConsume(tok::colon)) {
2507      SkipUntil(tok::r_paren, StopAtSemi);
2508      return ExprError();
2509    }
2510
2511    // FIXME: These expressions should be parsed in a potentially potentially
2512    // evaluated context.
2513    ExprResult ER(
2514        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2515    if (ER.isInvalid()) {
2516      SkipUntil(tok::r_paren, StopAtSemi);
2517      return ExprError();
2518    }
2519    Exprs.push_back(ER.get());
2520  } while (TryConsumeToken(tok::comma));
2521
2522  T.consumeClose();
2523  if (T.getCloseLocation().isInvalid())
2524    return ExprError();
2525
2526  return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2527                                           T.getCloseLocation(),
2528                                           ControllingExpr.get(),
2529                                           Types, Exprs);
2530}
2531
2532/// \brief Parse A C++1z fold-expression after the opening paren and optional
2533/// left-hand-side expression.
2534///
2535/// \verbatim
2536///   fold-expression:
2537///       ( cast-expression fold-operator ... )
2538///       ( ... fold-operator cast-expression )
2539///       ( cast-expression fold-operator ... fold-operator cast-expression )
2540ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2541                                       BalancedDelimiterTracker &T) {
2542  if (LHS.isInvalid()) {
2543    T.skipToEnd();
2544    return true;
2545  }
2546
2547  tok::TokenKind Kind = tok::unknown;
2548  SourceLocation FirstOpLoc;
2549  if (LHS.isUsable()) {
2550    Kind = Tok.getKind();
2551    assert(isFoldOperator(Kind) && "missing fold-operator");
2552    FirstOpLoc = ConsumeToken();
2553  }
2554
2555  assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2556  SourceLocation EllipsisLoc = ConsumeToken();
2557
2558  ExprResult RHS;
2559  if (Tok.isNot(tok::r_paren)) {
2560    if (!isFoldOperator(Tok.getKind()))
2561      return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2562
2563    if (Kind != tok::unknown && Tok.getKind() != Kind)
2564      Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2565        << SourceRange(FirstOpLoc);
2566    Kind = Tok.getKind();
2567    ConsumeToken();
2568
2569    RHS = ParseExpression();
2570    if (RHS.isInvalid()) {
2571      T.skipToEnd();
2572      return true;
2573    }
2574  }
2575
2576  Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
2577                        ? diag::warn_cxx14_compat_fold_expression
2578                        : diag::ext_fold_expression);
2579
2580  T.consumeClose();
2581  return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2582                                  EllipsisLoc, RHS.get(), T.getCloseLocation());
2583}
2584
2585/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2586///
2587/// \verbatim
2588///       argument-expression-list:
2589///         assignment-expression
2590///         argument-expression-list , assignment-expression
2591///
2592/// [C++] expression-list:
2593/// [C++]   assignment-expression
2594/// [C++]   expression-list , assignment-expression
2595///
2596/// [C++0x] expression-list:
2597/// [C++0x]   initializer-list
2598///
2599/// [C++0x] initializer-list
2600/// [C++0x]   initializer-clause ...[opt]
2601/// [C++0x]   initializer-list , initializer-clause ...[opt]
2602///
2603/// [C++0x] initializer-clause:
2604/// [C++0x]   assignment-expression
2605/// [C++0x]   braced-init-list
2606/// \endverbatim
2607bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2608                                 SmallVectorImpl<SourceLocation> &CommaLocs,
2609                                 std::function<void()> Completer) {
2610  bool SawError = false;
2611  while (1) {
2612    if (Tok.is(tok::code_completion)) {
2613      if (Completer)
2614        Completer();
2615      else
2616        Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2617      cutOffParsing();
2618      return true;
2619    }
2620
2621    ExprResult Expr;
2622    if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2623      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2624      Expr = ParseBraceInitializer();
2625    } else
2626      Expr = ParseAssignmentExpression();
2627
2628    if (Tok.is(tok::ellipsis))
2629      Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2630    if (Expr.isInvalid()) {
2631      SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2632      SawError = true;
2633    } else {
2634      Exprs.push_back(Expr.get());
2635    }
2636
2637    if (Tok.isNot(tok::comma))
2638      break;
2639    // Move to the next argument, remember where the comma was.
2640    CommaLocs.push_back(ConsumeToken());
2641  }
2642  if (SawError) {
2643    // Ensure typos get diagnosed when errors were encountered while parsing the
2644    // expression list.
2645    for (auto &E : Exprs) {
2646      ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2647      if (Expr.isUsable()) E = Expr.get();
2648    }
2649  }
2650  return SawError;
2651}
2652
2653/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2654/// used for misc language extensions.
2655///
2656/// \verbatim
2657///       simple-expression-list:
2658///         assignment-expression
2659///         simple-expression-list , assignment-expression
2660/// \endverbatim
2661bool
2662Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2663                                  SmallVectorImpl<SourceLocation> &CommaLocs) {
2664  while (1) {
2665    ExprResult Expr = ParseAssignmentExpression();
2666    if (Expr.isInvalid())
2667      return true;
2668
2669    Exprs.push_back(Expr.get());
2670
2671    if (Tok.isNot(tok::comma))
2672      return false;
2673
2674    // Move to the next argument, remember where the comma was.
2675    CommaLocs.push_back(ConsumeToken());
2676  }
2677}
2678
2679/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2680///
2681/// \verbatim
2682/// [clang] block-id:
2683/// [clang]   specifier-qualifier-list block-declarator
2684/// \endverbatim
2685void Parser::ParseBlockId(SourceLocation CaretLoc) {
2686  if (Tok.is(tok::code_completion)) {
2687    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2688    return cutOffParsing();
2689  }
2690
2691  // Parse the specifier-qualifier-list piece.
2692  DeclSpec DS(AttrFactory);
2693  ParseSpecifierQualifierList(DS);
2694
2695  // Parse the block-declarator.
2696  Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2697  ParseDeclarator(DeclaratorInfo);
2698
2699  MaybeParseGNUAttributes(DeclaratorInfo);
2700
2701  // Inform sema that we are starting a block.
2702  Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2703}
2704
2705/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2706/// like ^(int x){ return x+1; }
2707///
2708/// \verbatim
2709///         block-literal:
2710/// [clang]   '^' block-args[opt] compound-statement
2711/// [clang]   '^' block-id compound-statement
2712/// [clang] block-args:
2713/// [clang]   '(' parameter-list ')'
2714/// \endverbatim
2715ExprResult Parser::ParseBlockLiteralExpression() {
2716  assert(Tok.is(tok::caret) && "block literal starts with ^");
2717  SourceLocation CaretLoc = ConsumeToken();
2718
2719  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2720                                "block literal parsing");
2721
2722  // Enter a scope to hold everything within the block.  This includes the
2723  // argument decls, decls within the compound expression, etc.  This also
2724  // allows determining whether a variable reference inside the block is
2725  // within or outside of the block.
2726  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2727                              Scope::DeclScope);
2728
2729  // Inform sema that we are starting a block.
2730  Actions.ActOnBlockStart(CaretLoc, getCurScope());
2731
2732  // Parse the return type if present.
2733  DeclSpec DS(AttrFactory);
2734  Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2735  // FIXME: Since the return type isn't actually parsed, it can't be used to
2736  // fill ParamInfo with an initial valid range, so do it manually.
2737  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2738
2739  // If this block has arguments, parse them.  There is no ambiguity here with
2740  // the expression case, because the expression case requires a parameter list.
2741  if (Tok.is(tok::l_paren)) {
2742    ParseParenDeclarator(ParamInfo);
2743    // Parse the pieces after the identifier as if we had "int(...)".
2744    // SetIdentifier sets the source range end, but in this case we're past
2745    // that location.
2746    SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2747    ParamInfo.SetIdentifier(nullptr, CaretLoc);
2748    ParamInfo.SetRangeEnd(Tmp);
2749    if (ParamInfo.isInvalidType()) {
2750      // If there was an error parsing the arguments, they may have
2751      // tried to use ^(x+y) which requires an argument list.  Just
2752      // skip the whole block literal.
2753      Actions.ActOnBlockError(CaretLoc, getCurScope());
2754      return ExprError();
2755    }
2756
2757    MaybeParseGNUAttributes(ParamInfo);
2758
2759    // Inform sema that we are starting a block.
2760    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2761  } else if (!Tok.is(tok::l_brace)) {
2762    ParseBlockId(CaretLoc);
2763  } else {
2764    // Otherwise, pretend we saw (void).
2765    ParsedAttributes attrs(AttrFactory);
2766    SourceLocation NoLoc;
2767    ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2768                                             /*IsAmbiguous=*/false,
2769                                             /*RParenLoc=*/NoLoc,
2770                                             /*ArgInfo=*/nullptr,
2771                                             /*NumArgs=*/0,
2772                                             /*EllipsisLoc=*/NoLoc,
2773                                             /*RParenLoc=*/NoLoc,
2774                                             /*TypeQuals=*/0,
2775                                             /*RefQualifierIsLvalueRef=*/true,
2776                                             /*RefQualifierLoc=*/NoLoc,
2777                                             /*ConstQualifierLoc=*/NoLoc,
2778                                             /*VolatileQualifierLoc=*/NoLoc,
2779                                             /*RestrictQualifierLoc=*/NoLoc,
2780                                             /*MutableLoc=*/NoLoc,
2781                                             EST_None,
2782                                             /*ESpecRange=*/SourceRange(),
2783                                             /*Exceptions=*/nullptr,
2784                                             /*ExceptionRanges=*/nullptr,
2785                                             /*NumExceptions=*/0,
2786                                             /*NoexceptExpr=*/nullptr,
2787                                             /*ExceptionSpecTokens=*/nullptr,
2788                                             CaretLoc, CaretLoc,
2789                                             ParamInfo),
2790                          attrs, CaretLoc);
2791
2792    MaybeParseGNUAttributes(ParamInfo);
2793
2794    // Inform sema that we are starting a block.
2795    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2796  }
2797
2798
2799  ExprResult Result(true);
2800  if (!Tok.is(tok::l_brace)) {
2801    // Saw something like: ^expr
2802    Diag(Tok, diag::err_expected_expression);
2803    Actions.ActOnBlockError(CaretLoc, getCurScope());
2804    return ExprError();
2805  }
2806
2807  StmtResult Stmt(ParseCompoundStatementBody());
2808  BlockScope.Exit();
2809  if (!Stmt.isInvalid())
2810    Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2811  else
2812    Actions.ActOnBlockError(CaretLoc, getCurScope());
2813  return Result;
2814}
2815
2816/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2817///
2818///         '__objc_yes'
2819///         '__objc_no'
2820ExprResult Parser::ParseObjCBoolLiteral() {
2821  tok::TokenKind Kind = Tok.getKind();
2822  return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
2823}
2824