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