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