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