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