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