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