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