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