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