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