xref: /freebsd/contrib/llvm-project/clang/lib/Parse/ParseExpr.cpp (revision 1f1e2261e341e6ca6862f82261066ef1705f0a7a)
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     cutOffParsing();
163     Actions.CodeCompleteExpression(getCurScope(),
164                                    PreferredType.get(Tok.getLocation()));
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 (true) {
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_primary_expr:
1011   case tok::annot_overload_set:
1012     Res = getExprAnnotation(Tok);
1013     if (!Res.isInvalid() && Tok.getKind() == tok::annot_overload_set)
1014       Res = Actions.ActOnNameClassifiedAsOverloadSet(getCurScope(), Res.get());
1015     ConsumeAnnotationToken();
1016     if (!Res.isInvalid() && Tok.is(tok::less))
1017       checkPotentialAngleBracket(Res);
1018     break;
1019 
1020   case tok::annot_non_type:
1021   case tok::annot_non_type_dependent:
1022   case tok::annot_non_type_undeclared: {
1023     CXXScopeSpec SS;
1024     Token Replacement;
1025     Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
1026     assert(!Res.isUnset() &&
1027            "should not perform typo correction on annotation token");
1028     break;
1029   }
1030 
1031   case tok::kw___super:
1032   case tok::kw_decltype:
1033     // Annotate the token and tail recurse.
1034     if (TryAnnotateTypeOrScopeToken())
1035       return ExprError();
1036     assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
1037     return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1038                                isVectorLiteral, NotPrimaryExpression);
1039 
1040   case tok::identifier: {      // primary-expression: identifier
1041                                // unqualified-id: identifier
1042                                // constant: enumeration-constant
1043     // Turn a potentially qualified name into a annot_typename or
1044     // annot_cxxscope if it would be valid.  This handles things like x::y, etc.
1045     if (getLangOpts().CPlusPlus) {
1046       // Avoid the unnecessary parse-time lookup in the common case
1047       // where the syntax forbids a type.
1048       const Token &Next = NextToken();
1049 
1050       // If this identifier was reverted from a token ID, and the next token
1051       // is a parenthesis, this is likely to be a use of a type trait. Check
1052       // those tokens.
1053       if (Next.is(tok::l_paren) &&
1054           Tok.is(tok::identifier) &&
1055           Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
1056         IdentifierInfo *II = Tok.getIdentifierInfo();
1057         // Build up the mapping of revertible type traits, for future use.
1058         if (RevertibleTypeTraits.empty()) {
1059 #define RTT_JOIN(X,Y) X##Y
1060 #define REVERTIBLE_TYPE_TRAIT(Name)                         \
1061           RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
1062             = RTT_JOIN(tok::kw_,Name)
1063 
1064           REVERTIBLE_TYPE_TRAIT(__is_abstract);
1065           REVERTIBLE_TYPE_TRAIT(__is_aggregate);
1066           REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
1067           REVERTIBLE_TYPE_TRAIT(__is_array);
1068           REVERTIBLE_TYPE_TRAIT(__is_assignable);
1069           REVERTIBLE_TYPE_TRAIT(__is_base_of);
1070           REVERTIBLE_TYPE_TRAIT(__is_class);
1071           REVERTIBLE_TYPE_TRAIT(__is_complete_type);
1072           REVERTIBLE_TYPE_TRAIT(__is_compound);
1073           REVERTIBLE_TYPE_TRAIT(__is_const);
1074           REVERTIBLE_TYPE_TRAIT(__is_constructible);
1075           REVERTIBLE_TYPE_TRAIT(__is_convertible);
1076           REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
1077           REVERTIBLE_TYPE_TRAIT(__is_destructible);
1078           REVERTIBLE_TYPE_TRAIT(__is_empty);
1079           REVERTIBLE_TYPE_TRAIT(__is_enum);
1080           REVERTIBLE_TYPE_TRAIT(__is_floating_point);
1081           REVERTIBLE_TYPE_TRAIT(__is_final);
1082           REVERTIBLE_TYPE_TRAIT(__is_function);
1083           REVERTIBLE_TYPE_TRAIT(__is_fundamental);
1084           REVERTIBLE_TYPE_TRAIT(__is_integral);
1085           REVERTIBLE_TYPE_TRAIT(__is_interface_class);
1086           REVERTIBLE_TYPE_TRAIT(__is_literal);
1087           REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
1088           REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
1089           REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
1090           REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
1091           REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
1092           REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
1093           REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
1094           REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
1095           REVERTIBLE_TYPE_TRAIT(__is_object);
1096           REVERTIBLE_TYPE_TRAIT(__is_pod);
1097           REVERTIBLE_TYPE_TRAIT(__is_pointer);
1098           REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
1099           REVERTIBLE_TYPE_TRAIT(__is_reference);
1100           REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
1101           REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
1102           REVERTIBLE_TYPE_TRAIT(__is_same);
1103           REVERTIBLE_TYPE_TRAIT(__is_scalar);
1104           REVERTIBLE_TYPE_TRAIT(__is_sealed);
1105           REVERTIBLE_TYPE_TRAIT(__is_signed);
1106           REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
1107           REVERTIBLE_TYPE_TRAIT(__is_trivial);
1108           REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
1109           REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
1110           REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
1111           REVERTIBLE_TYPE_TRAIT(__is_union);
1112           REVERTIBLE_TYPE_TRAIT(__is_unsigned);
1113           REVERTIBLE_TYPE_TRAIT(__is_void);
1114           REVERTIBLE_TYPE_TRAIT(__is_volatile);
1115 #undef REVERTIBLE_TYPE_TRAIT
1116 #undef RTT_JOIN
1117         }
1118 
1119         // If we find that this is in fact the name of a type trait,
1120         // update the token kind in place and parse again to treat it as
1121         // the appropriate kind of type trait.
1122         llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
1123           = RevertibleTypeTraits.find(II);
1124         if (Known != RevertibleTypeTraits.end()) {
1125           Tok.setKind(Known->second);
1126           return ParseCastExpression(ParseKind, isAddressOfOperand,
1127                                      NotCastExpr, isTypeCast,
1128                                      isVectorLiteral, NotPrimaryExpression);
1129         }
1130       }
1131 
1132       if ((!ColonIsSacred && Next.is(tok::colon)) ||
1133           Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
1134                        tok::l_brace)) {
1135         // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1136         if (TryAnnotateTypeOrScopeToken())
1137           return ExprError();
1138         if (!Tok.is(tok::identifier))
1139           return ParseCastExpression(ParseKind, isAddressOfOperand,
1140                                      NotCastExpr, isTypeCast,
1141                                      isVectorLiteral,
1142                                      NotPrimaryExpression);
1143       }
1144     }
1145 
1146     // Consume the identifier so that we can see if it is followed by a '(' or
1147     // '.'.
1148     IdentifierInfo &II = *Tok.getIdentifierInfo();
1149     SourceLocation ILoc = ConsumeToken();
1150 
1151     // Support 'Class.property' and 'super.property' notation.
1152     if (getLangOpts().ObjC && Tok.is(tok::period) &&
1153         (Actions.getTypeName(II, ILoc, getCurScope()) ||
1154          // Allow the base to be 'super' if in an objc-method.
1155          (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
1156       ConsumeToken();
1157 
1158       if (Tok.is(tok::code_completion) && &II != Ident_super) {
1159         cutOffParsing();
1160         Actions.CodeCompleteObjCClassPropertyRefExpr(
1161             getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
1162         return ExprError();
1163       }
1164       // Allow either an identifier or the keyword 'class' (in C++).
1165       if (Tok.isNot(tok::identifier) &&
1166           !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
1167         Diag(Tok, diag::err_expected_property_name);
1168         return ExprError();
1169       }
1170       IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
1171       SourceLocation PropertyLoc = ConsumeToken();
1172 
1173       Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
1174                                               ILoc, PropertyLoc);
1175       break;
1176     }
1177 
1178     // In an Objective-C method, if we have "super" followed by an identifier,
1179     // the token sequence is ill-formed. However, if there's a ':' or ']' after
1180     // that identifier, this is probably a message send with a missing open
1181     // bracket. Treat it as such.
1182     if (getLangOpts().ObjC && &II == Ident_super && !InMessageExpression &&
1183         getCurScope()->isInObjcMethodScope() &&
1184         ((Tok.is(tok::identifier) &&
1185          (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
1186          Tok.is(tok::code_completion))) {
1187       Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
1188                                            nullptr);
1189       break;
1190     }
1191 
1192     // If we have an Objective-C class name followed by an identifier
1193     // and either ':' or ']', this is an Objective-C class message
1194     // send that's missing the opening '['. Recovery
1195     // appropriately. Also take this path if we're performing code
1196     // completion after an Objective-C class name.
1197     if (getLangOpts().ObjC &&
1198         ((Tok.is(tok::identifier) && !InMessageExpression) ||
1199          Tok.is(tok::code_completion))) {
1200       const Token& Next = NextToken();
1201       if (Tok.is(tok::code_completion) ||
1202           Next.is(tok::colon) || Next.is(tok::r_square))
1203         if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
1204           if (Typ.get()->isObjCObjectOrInterfaceType()) {
1205             // Fake up a Declarator to use with ActOnTypeName.
1206             DeclSpec DS(AttrFactory);
1207             DS.SetRangeStart(ILoc);
1208             DS.SetRangeEnd(ILoc);
1209             const char *PrevSpec = nullptr;
1210             unsigned DiagID;
1211             DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1212                                Actions.getASTContext().getPrintingPolicy());
1213 
1214             Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
1215             TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1216                                                   DeclaratorInfo);
1217             if (Ty.isInvalid())
1218               break;
1219 
1220             Res = ParseObjCMessageExpressionBody(SourceLocation(),
1221                                                  SourceLocation(),
1222                                                  Ty.get(), nullptr);
1223             break;
1224           }
1225     }
1226 
1227     // Make sure to pass down the right value for isAddressOfOperand.
1228     if (isAddressOfOperand && isPostfixExpressionSuffixStart())
1229       isAddressOfOperand = false;
1230 
1231     // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1232     // need to know whether or not this identifier is a function designator or
1233     // not.
1234     UnqualifiedId Name;
1235     CXXScopeSpec ScopeSpec;
1236     SourceLocation TemplateKWLoc;
1237     Token Replacement;
1238     CastExpressionIdValidator Validator(
1239         /*Next=*/Tok,
1240         /*AllowTypes=*/isTypeCast != NotTypeCast,
1241         /*AllowNonTypes=*/isTypeCast != IsTypeCast);
1242     Validator.IsAddressOfOperand = isAddressOfOperand;
1243     if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1244       Validator.WantExpressionKeywords = false;
1245       Validator.WantRemainingKeywords = false;
1246     } else {
1247       Validator.WantRemainingKeywords = Tok.isNot(tok::r_paren);
1248     }
1249     Name.setIdentifier(&II, ILoc);
1250     Res = Actions.ActOnIdExpression(
1251         getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1252         isAddressOfOperand, &Validator,
1253         /*IsInlineAsmIdentifier=*/false,
1254         Tok.is(tok::r_paren) ? nullptr : &Replacement);
1255     if (!Res.isInvalid() && Res.isUnset()) {
1256       UnconsumeToken(Replacement);
1257       return ParseCastExpression(ParseKind, isAddressOfOperand,
1258                                  NotCastExpr, isTypeCast,
1259                                  /*isVectorLiteral=*/false,
1260                                  NotPrimaryExpression);
1261     }
1262     if (!Res.isInvalid() && Tok.is(tok::less))
1263       checkPotentialAngleBracket(Res);
1264     break;
1265   }
1266   case tok::char_constant:     // constant: character-constant
1267   case tok::wide_char_constant:
1268   case tok::utf8_char_constant:
1269   case tok::utf16_char_constant:
1270   case tok::utf32_char_constant:
1271     Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1272     ConsumeToken();
1273     break;
1274   case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
1275   case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
1276   case tok::kw___FUNCDNAME__:   // primary-expression: __FUNCDNAME__ [MS]
1277   case tok::kw___FUNCSIG__:     // primary-expression: __FUNCSIG__ [MS]
1278   case tok::kw_L__FUNCTION__:   // primary-expression: L__FUNCTION__ [MS]
1279   case tok::kw_L__FUNCSIG__:    // primary-expression: L__FUNCSIG__ [MS]
1280   case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
1281     Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1282     ConsumeToken();
1283     break;
1284   case tok::string_literal:    // primary-expression: string-literal
1285   case tok::wide_string_literal:
1286   case tok::utf8_string_literal:
1287   case tok::utf16_string_literal:
1288   case tok::utf32_string_literal:
1289     Res = ParseStringLiteralExpression(true);
1290     break;
1291   case tok::kw__Generic:   // primary-expression: generic-selection [C11 6.5.1]
1292     Res = ParseGenericSelectionExpression();
1293     break;
1294   case tok::kw___builtin_available:
1295     Res = ParseAvailabilityCheckExpr(Tok.getLocation());
1296     break;
1297   case tok::kw___builtin_va_arg:
1298   case tok::kw___builtin_offsetof:
1299   case tok::kw___builtin_choose_expr:
1300   case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1301   case tok::kw___builtin_convertvector:
1302   case tok::kw___builtin_COLUMN:
1303   case tok::kw___builtin_FILE:
1304   case tok::kw___builtin_FUNCTION:
1305   case tok::kw___builtin_LINE:
1306     if (NotPrimaryExpression)
1307       *NotPrimaryExpression = true;
1308     // This parses the complete suffix; we can return early.
1309     return ParseBuiltinPrimaryExpression();
1310   case tok::kw___null:
1311     Res = Actions.ActOnGNUNullExpr(ConsumeToken());
1312     break;
1313 
1314   case tok::plusplus:      // unary-expression: '++' unary-expression [C99]
1315   case tok::minusminus: {  // unary-expression: '--' unary-expression [C99]
1316     if (NotPrimaryExpression)
1317       *NotPrimaryExpression = true;
1318     // C++ [expr.unary] has:
1319     //   unary-expression:
1320     //     ++ cast-expression
1321     //     -- cast-expression
1322     Token SavedTok = Tok;
1323     ConsumeToken();
1324 
1325     PreferredType.enterUnary(Actions, Tok.getLocation(), SavedTok.getKind(),
1326                              SavedTok.getLocation());
1327     // One special case is implicitly handled here: if the preceding tokens are
1328     // an ambiguous cast expression, such as "(T())++", then we recurse to
1329     // determine whether the '++' is prefix or postfix.
1330     Res = ParseCastExpression(getLangOpts().CPlusPlus ?
1331                                   UnaryExprOnly : AnyCastExpr,
1332                               /*isAddressOfOperand*/false, NotCastExpr,
1333                               NotTypeCast);
1334     if (NotCastExpr) {
1335       // If we return with NotCastExpr = true, we must not consume any tokens,
1336       // so put the token back where we found it.
1337       assert(Res.isInvalid());
1338       UnconsumeToken(SavedTok);
1339       return ExprError();
1340     }
1341     if (!Res.isInvalid()) {
1342       Expr *Arg = Res.get();
1343       Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1344                                  SavedKind, Arg);
1345       if (Res.isInvalid())
1346         Res = Actions.CreateRecoveryExpr(SavedTok.getLocation(),
1347                                          Arg->getEndLoc(), Arg);
1348     }
1349     return Res;
1350   }
1351   case tok::amp: {         // unary-expression: '&' cast-expression
1352     if (NotPrimaryExpression)
1353       *NotPrimaryExpression = true;
1354     // Special treatment because of member pointers
1355     SourceLocation SavedLoc = ConsumeToken();
1356     PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
1357     Res = ParseCastExpression(AnyCastExpr, true);
1358     if (!Res.isInvalid()) {
1359       Expr *Arg = Res.get();
1360       Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1361       if (Res.isInvalid())
1362         Res = Actions.CreateRecoveryExpr(Tok.getLocation(), Arg->getEndLoc(),
1363                                          Arg);
1364     }
1365     return Res;
1366   }
1367 
1368   case tok::star:          // unary-expression: '*' cast-expression
1369   case tok::plus:          // unary-expression: '+' cast-expression
1370   case tok::minus:         // unary-expression: '-' cast-expression
1371   case tok::tilde:         // unary-expression: '~' cast-expression
1372   case tok::exclaim:       // unary-expression: '!' cast-expression
1373   case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
1374   case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
1375     if (NotPrimaryExpression)
1376       *NotPrimaryExpression = true;
1377     SourceLocation SavedLoc = ConsumeToken();
1378     PreferredType.enterUnary(Actions, Tok.getLocation(), SavedKind, SavedLoc);
1379     Res = ParseCastExpression(AnyCastExpr);
1380     if (!Res.isInvalid()) {
1381       Expr *Arg = Res.get();
1382       Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1383       if (Res.isInvalid())
1384         Res = Actions.CreateRecoveryExpr(SavedLoc, Arg->getEndLoc(), Arg);
1385     }
1386     return Res;
1387   }
1388 
1389   case tok::kw_co_await: {  // unary-expression: 'co_await' cast-expression
1390     if (NotPrimaryExpression)
1391       *NotPrimaryExpression = true;
1392     SourceLocation CoawaitLoc = ConsumeToken();
1393     Res = ParseCastExpression(AnyCastExpr);
1394     if (!Res.isInvalid())
1395       Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1396     return Res;
1397   }
1398 
1399   case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1400     // __extension__ silences extension warnings in the subexpression.
1401     if (NotPrimaryExpression)
1402       *NotPrimaryExpression = true;
1403     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1404     SourceLocation SavedLoc = ConsumeToken();
1405     Res = ParseCastExpression(AnyCastExpr);
1406     if (!Res.isInvalid())
1407       Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1408     return Res;
1409   }
1410   case tok::kw__Alignof:   // unary-expression: '_Alignof' '(' type-name ')'
1411     if (!getLangOpts().C11)
1412       Diag(Tok, diag::ext_c11_feature) << Tok.getName();
1413     LLVM_FALLTHROUGH;
1414   case tok::kw_alignof:    // unary-expression: 'alignof' '(' type-id ')'
1415   case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
1416                            // unary-expression: '__alignof' '(' type-name ')'
1417   case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
1418                            // unary-expression: 'sizeof' '(' type-name ')'
1419   case tok::kw_vec_step:   // unary-expression: OpenCL 'vec_step' expression
1420   // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1421   case tok::kw___builtin_omp_required_simd_align:
1422     if (NotPrimaryExpression)
1423       *NotPrimaryExpression = true;
1424     AllowSuffix = false;
1425     Res = ParseUnaryExprOrTypeTraitExpression();
1426     break;
1427   case tok::ampamp: {      // unary-expression: '&&' identifier
1428     if (NotPrimaryExpression)
1429       *NotPrimaryExpression = true;
1430     SourceLocation AmpAmpLoc = ConsumeToken();
1431     if (Tok.isNot(tok::identifier))
1432       return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1433 
1434     if (getCurScope()->getFnParent() == nullptr)
1435       return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1436 
1437     Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1438     LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1439                                                 Tok.getLocation());
1440     Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1441     ConsumeToken();
1442     AllowSuffix = false;
1443     break;
1444   }
1445   case tok::kw_const_cast:
1446   case tok::kw_dynamic_cast:
1447   case tok::kw_reinterpret_cast:
1448   case tok::kw_static_cast:
1449   case tok::kw_addrspace_cast:
1450     if (NotPrimaryExpression)
1451       *NotPrimaryExpression = true;
1452     Res = ParseCXXCasts();
1453     break;
1454   case tok::kw___builtin_bit_cast:
1455     if (NotPrimaryExpression)
1456       *NotPrimaryExpression = true;
1457     Res = ParseBuiltinBitCast();
1458     break;
1459   case tok::kw_typeid:
1460     if (NotPrimaryExpression)
1461       *NotPrimaryExpression = true;
1462     Res = ParseCXXTypeid();
1463     break;
1464   case tok::kw___uuidof:
1465     if (NotPrimaryExpression)
1466       *NotPrimaryExpression = true;
1467     Res = ParseCXXUuidof();
1468     break;
1469   case tok::kw_this:
1470     Res = ParseCXXThis();
1471     break;
1472   case tok::kw___builtin_sycl_unique_stable_name:
1473     Res = ParseSYCLUniqueStableNameExpression();
1474     break;
1475 
1476   case tok::annot_typename:
1477     if (isStartOfObjCClassMessageMissingOpenBracket()) {
1478       TypeResult Type = getTypeAnnotation(Tok);
1479 
1480       // Fake up a Declarator to use with ActOnTypeName.
1481       DeclSpec DS(AttrFactory);
1482       DS.SetRangeStart(Tok.getLocation());
1483       DS.SetRangeEnd(Tok.getLastLoc());
1484 
1485       const char *PrevSpec = nullptr;
1486       unsigned DiagID;
1487       DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1488                          PrevSpec, DiagID, Type,
1489                          Actions.getASTContext().getPrintingPolicy());
1490 
1491       Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
1492       TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1493       if (Ty.isInvalid())
1494         break;
1495 
1496       ConsumeAnnotationToken();
1497       Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1498                                            Ty.get(), nullptr);
1499       break;
1500     }
1501     LLVM_FALLTHROUGH;
1502 
1503   case tok::annot_decltype:
1504   case tok::kw_char:
1505   case tok::kw_wchar_t:
1506   case tok::kw_char8_t:
1507   case tok::kw_char16_t:
1508   case tok::kw_char32_t:
1509   case tok::kw_bool:
1510   case tok::kw_short:
1511   case tok::kw_int:
1512   case tok::kw_long:
1513   case tok::kw___int64:
1514   case tok::kw___int128:
1515   case tok::kw__ExtInt:
1516   case tok::kw__BitInt:
1517   case tok::kw_signed:
1518   case tok::kw_unsigned:
1519   case tok::kw_half:
1520   case tok::kw_float:
1521   case tok::kw_double:
1522   case tok::kw___bf16:
1523   case tok::kw__Float16:
1524   case tok::kw___float128:
1525   case tok::kw___ibm128:
1526   case tok::kw_void:
1527   case tok::kw_typename:
1528   case tok::kw_typeof:
1529   case tok::kw___vector:
1530 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1531 #include "clang/Basic/OpenCLImageTypes.def"
1532   {
1533     if (!getLangOpts().CPlusPlus) {
1534       Diag(Tok, diag::err_expected_expression);
1535       return ExprError();
1536     }
1537 
1538     // Everything henceforth is a postfix-expression.
1539     if (NotPrimaryExpression)
1540       *NotPrimaryExpression = true;
1541 
1542     if (SavedKind == tok::kw_typename) {
1543       // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1544       //                     typename-specifier braced-init-list
1545       if (TryAnnotateTypeOrScopeToken())
1546         return ExprError();
1547 
1548       if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1549         // We are trying to parse a simple-type-specifier but might not get such
1550         // a token after error recovery.
1551         return ExprError();
1552     }
1553 
1554     // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1555     //                     simple-type-specifier braced-init-list
1556     //
1557     DeclSpec DS(AttrFactory);
1558 
1559     ParseCXXSimpleTypeSpecifier(DS);
1560     if (Tok.isNot(tok::l_paren) &&
1561         (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1562       return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1563                          << DS.getSourceRange());
1564 
1565     if (Tok.is(tok::l_brace))
1566       Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1567 
1568     Res = ParseCXXTypeConstructExpression(DS);
1569     break;
1570   }
1571 
1572   case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1573     // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1574     // (We can end up in this situation after tentative parsing.)
1575     if (TryAnnotateTypeOrScopeToken())
1576       return ExprError();
1577     if (!Tok.is(tok::annot_cxxscope))
1578       return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1579                                  isTypeCast, isVectorLiteral,
1580                                  NotPrimaryExpression);
1581 
1582     Token Next = NextToken();
1583     if (Next.is(tok::annot_template_id)) {
1584       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1585       if (TemplateId->Kind == TNK_Type_template) {
1586         // We have a qualified template-id that we know refers to a
1587         // type, translate it into a type and continue parsing as a
1588         // cast expression.
1589         CXXScopeSpec SS;
1590         ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1591                                        /*ObjectHasErrors=*/false,
1592                                        /*EnteringContext=*/false);
1593         AnnotateTemplateIdTokenAsType(SS);
1594         return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1595                                    isTypeCast, isVectorLiteral,
1596                                    NotPrimaryExpression);
1597       }
1598     }
1599 
1600     // Parse as an id-expression.
1601     Res = ParseCXXIdExpression(isAddressOfOperand);
1602     break;
1603   }
1604 
1605   case tok::annot_template_id: { // [C++]          template-id
1606     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1607     if (TemplateId->Kind == TNK_Type_template) {
1608       // We have a template-id that we know refers to a type,
1609       // translate it into a type and continue parsing as a cast
1610       // expression.
1611       CXXScopeSpec SS;
1612       AnnotateTemplateIdTokenAsType(SS);
1613       return ParseCastExpression(ParseKind, isAddressOfOperand,
1614                                  NotCastExpr, isTypeCast, isVectorLiteral,
1615                                  NotPrimaryExpression);
1616     }
1617 
1618     // Fall through to treat the template-id as an id-expression.
1619     LLVM_FALLTHROUGH;
1620   }
1621 
1622   case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1623     Res = ParseCXXIdExpression(isAddressOfOperand);
1624     break;
1625 
1626   case tok::coloncolon: {
1627     // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
1628     // annotates the token, tail recurse.
1629     if (TryAnnotateTypeOrScopeToken())
1630       return ExprError();
1631     if (!Tok.is(tok::coloncolon))
1632       return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1633                                  isVectorLiteral, NotPrimaryExpression);
1634 
1635     // ::new -> [C++] new-expression
1636     // ::delete -> [C++] delete-expression
1637     SourceLocation CCLoc = ConsumeToken();
1638     if (Tok.is(tok::kw_new)) {
1639       if (NotPrimaryExpression)
1640         *NotPrimaryExpression = true;
1641       Res = ParseCXXNewExpression(true, CCLoc);
1642       AllowSuffix = false;
1643       break;
1644     }
1645     if (Tok.is(tok::kw_delete)) {
1646       if (NotPrimaryExpression)
1647         *NotPrimaryExpression = true;
1648       Res = ParseCXXDeleteExpression(true, CCLoc);
1649       AllowSuffix = false;
1650       break;
1651     }
1652 
1653     // This is not a type name or scope specifier, it is an invalid expression.
1654     Diag(CCLoc, diag::err_expected_expression);
1655     return ExprError();
1656   }
1657 
1658   case tok::kw_new: // [C++] new-expression
1659     if (NotPrimaryExpression)
1660       *NotPrimaryExpression = true;
1661     Res = ParseCXXNewExpression(false, Tok.getLocation());
1662     AllowSuffix = false;
1663     break;
1664 
1665   case tok::kw_delete: // [C++] delete-expression
1666     if (NotPrimaryExpression)
1667       *NotPrimaryExpression = true;
1668     Res = ParseCXXDeleteExpression(false, Tok.getLocation());
1669     AllowSuffix = false;
1670     break;
1671 
1672   case tok::kw_requires: // [C++2a] requires-expression
1673     Res = ParseRequiresExpression();
1674     AllowSuffix = false;
1675     break;
1676 
1677   case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1678     if (NotPrimaryExpression)
1679       *NotPrimaryExpression = true;
1680     Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1681     SourceLocation KeyLoc = ConsumeToken();
1682     BalancedDelimiterTracker T(*this, tok::l_paren);
1683 
1684     if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1685       return ExprError();
1686     // C++11 [expr.unary.noexcept]p1:
1687     //   The noexcept operator determines whether the evaluation of its operand,
1688     //   which is an unevaluated operand, can throw an exception.
1689     EnterExpressionEvaluationContext Unevaluated(
1690         Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1691     Res = ParseExpression();
1692 
1693     T.consumeClose();
1694 
1695     if (!Res.isInvalid())
1696       Res = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Res.get(),
1697                                       T.getCloseLocation());
1698     AllowSuffix = false;
1699     break;
1700   }
1701 
1702 #define TYPE_TRAIT(N,Spelling,K) \
1703   case tok::kw_##Spelling:
1704 #include "clang/Basic/TokenKinds.def"
1705     Res = ParseTypeTrait();
1706     break;
1707 
1708   case tok::kw___array_rank:
1709   case tok::kw___array_extent:
1710     if (NotPrimaryExpression)
1711       *NotPrimaryExpression = true;
1712     Res = ParseArrayTypeTrait();
1713     break;
1714 
1715   case tok::kw___is_lvalue_expr:
1716   case tok::kw___is_rvalue_expr:
1717     if (NotPrimaryExpression)
1718       *NotPrimaryExpression = true;
1719     Res = ParseExpressionTrait();
1720     break;
1721 
1722   case tok::at: {
1723     if (NotPrimaryExpression)
1724       *NotPrimaryExpression = true;
1725     SourceLocation AtLoc = ConsumeToken();
1726     return ParseObjCAtExpression(AtLoc);
1727   }
1728   case tok::caret:
1729     Res = ParseBlockLiteralExpression();
1730     break;
1731   case tok::code_completion: {
1732     cutOffParsing();
1733     Actions.CodeCompleteExpression(getCurScope(),
1734                                    PreferredType.get(Tok.getLocation()));
1735     return ExprError();
1736   }
1737   case tok::l_square:
1738     if (getLangOpts().CPlusPlus11) {
1739       if (getLangOpts().ObjC) {
1740         // C++11 lambda expressions and Objective-C message sends both start with a
1741         // square bracket.  There are three possibilities here:
1742         // we have a valid lambda expression, we have an invalid lambda
1743         // expression, or we have something that doesn't appear to be a lambda.
1744         // If we're in the last case, we fall back to ParseObjCMessageExpression.
1745         Res = TryParseLambdaExpression();
1746         if (!Res.isInvalid() && !Res.get()) {
1747           // We assume Objective-C++ message expressions are not
1748           // primary-expressions.
1749           if (NotPrimaryExpression)
1750             *NotPrimaryExpression = true;
1751           Res = ParseObjCMessageExpression();
1752         }
1753         break;
1754       }
1755       Res = ParseLambdaExpression();
1756       break;
1757     }
1758     if (getLangOpts().ObjC) {
1759       Res = ParseObjCMessageExpression();
1760       break;
1761     }
1762     LLVM_FALLTHROUGH;
1763   default:
1764     NotCastExpr = true;
1765     return ExprError();
1766   }
1767 
1768   // Check to see whether Res is a function designator only. If it is and we
1769   // are compiling for OpenCL, we need to return an error as this implies
1770   // that the address of the function is being taken, which is illegal in CL.
1771 
1772   if (ParseKind == PrimaryExprOnly)
1773     // This is strictly a primary-expression - no postfix-expr pieces should be
1774     // parsed.
1775     return Res;
1776 
1777   if (!AllowSuffix) {
1778     // FIXME: Don't parse a primary-expression suffix if we encountered a parse
1779     // error already.
1780     if (Res.isInvalid())
1781       return Res;
1782 
1783     switch (Tok.getKind()) {
1784     case tok::l_square:
1785     case tok::l_paren:
1786     case tok::plusplus:
1787     case tok::minusminus:
1788       // "expected ';'" or similar is probably the right diagnostic here. Let
1789       // the caller decide what to do.
1790       if (Tok.isAtStartOfLine())
1791         return Res;
1792 
1793       LLVM_FALLTHROUGH;
1794     case tok::period:
1795     case tok::arrow:
1796       break;
1797 
1798     default:
1799       return Res;
1800     }
1801 
1802     // This was a unary-expression for which a postfix-expression suffix is
1803     // not permitted by the grammar (eg, a sizeof expression or
1804     // new-expression or similar). Diagnose but parse the suffix anyway.
1805     Diag(Tok.getLocation(), diag::err_postfix_after_unary_requires_parens)
1806         << Tok.getKind() << Res.get()->getSourceRange()
1807         << FixItHint::CreateInsertion(Res.get()->getBeginLoc(), "(")
1808         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(PrevTokLocation),
1809                                       ")");
1810   }
1811 
1812   // These can be followed by postfix-expr pieces.
1813   PreferredType = SavedType;
1814   Res = ParsePostfixExpressionSuffix(Res);
1815   if (getLangOpts().OpenCL &&
1816       !getActions().getOpenCLOptions().isAvailableOption(
1817           "__cl_clang_function_pointers", getLangOpts()))
1818     if (Expr *PostfixExpr = Res.get()) {
1819       QualType Ty = PostfixExpr->getType();
1820       if (!Ty.isNull() && Ty->isFunctionType()) {
1821         Diag(PostfixExpr->getExprLoc(),
1822              diag::err_opencl_taking_function_address_parser);
1823         return ExprError();
1824       }
1825     }
1826 
1827   return Res;
1828 }
1829 
1830 /// Once the leading part of a postfix-expression is parsed, this
1831 /// method parses any suffixes that apply.
1832 ///
1833 /// \verbatim
1834 ///       postfix-expression: [C99 6.5.2]
1835 ///         primary-expression
1836 ///         postfix-expression '[' expression ']'
1837 ///         postfix-expression '[' braced-init-list ']'
1838 ///         postfix-expression '(' argument-expression-list[opt] ')'
1839 ///         postfix-expression '.' identifier
1840 ///         postfix-expression '->' identifier
1841 ///         postfix-expression '++'
1842 ///         postfix-expression '--'
1843 ///         '(' type-name ')' '{' initializer-list '}'
1844 ///         '(' type-name ')' '{' initializer-list ',' '}'
1845 ///
1846 ///       argument-expression-list: [C99 6.5.2]
1847 ///         argument-expression ...[opt]
1848 ///         argument-expression-list ',' assignment-expression ...[opt]
1849 /// \endverbatim
1850 ExprResult
1851 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1852   // Now that the primary-expression piece of the postfix-expression has been
1853   // parsed, see if there are any postfix-expression pieces here.
1854   SourceLocation Loc;
1855   auto SavedType = PreferredType;
1856   while (true) {
1857     // Each iteration relies on preferred type for the whole expression.
1858     PreferredType = SavedType;
1859     switch (Tok.getKind()) {
1860     case tok::code_completion:
1861       if (InMessageExpression)
1862         return LHS;
1863 
1864       cutOffParsing();
1865       Actions.CodeCompletePostfixExpression(
1866           getCurScope(), LHS, PreferredType.get(Tok.getLocation()));
1867       return ExprError();
1868 
1869     case tok::identifier:
1870       // If we see identifier: after an expression, and we're not already in a
1871       // message send, then this is probably a message send with a missing
1872       // opening bracket '['.
1873       if (getLangOpts().ObjC && !InMessageExpression &&
1874           (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1875         LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1876                                              nullptr, LHS.get());
1877         break;
1878       }
1879       // Fall through; this isn't a message send.
1880       LLVM_FALLTHROUGH;
1881 
1882     default:  // Not a postfix-expression suffix.
1883       return LHS;
1884     case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
1885       // If we have a array postfix expression that starts on a new line and
1886       // Objective-C is enabled, it is highly likely that the user forgot a
1887       // semicolon after the base expression and that the array postfix-expr is
1888       // actually another message send.  In this case, do some look-ahead to see
1889       // if the contents of the square brackets are obviously not a valid
1890       // expression and recover by pretending there is no suffix.
1891       if (getLangOpts().ObjC && Tok.isAtStartOfLine() &&
1892           isSimpleObjCMessageExpression())
1893         return LHS;
1894 
1895       // Reject array indices starting with a lambda-expression. '[[' is
1896       // reserved for attributes.
1897       if (CheckProhibitedCXX11Attribute()) {
1898         (void)Actions.CorrectDelayedTyposInExpr(LHS);
1899         return ExprError();
1900       }
1901 
1902       BalancedDelimiterTracker T(*this, tok::l_square);
1903       T.consumeOpen();
1904       Loc = T.getOpenLocation();
1905       ExprResult Idx, Length, Stride;
1906       SourceLocation ColonLocFirst, ColonLocSecond;
1907       PreferredType.enterSubscript(Actions, Tok.getLocation(), LHS.get());
1908       if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1909         Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1910         Idx = ParseBraceInitializer();
1911       } else if (getLangOpts().OpenMP) {
1912         ColonProtectionRAIIObject RAII(*this);
1913         // Parse [: or [ expr or [ expr :
1914         if (!Tok.is(tok::colon)) {
1915           // [ expr
1916           Idx = ParseExpression();
1917         }
1918         if (Tok.is(tok::colon)) {
1919           // Consume ':'
1920           ColonLocFirst = ConsumeToken();
1921           if (Tok.isNot(tok::r_square) &&
1922               (getLangOpts().OpenMP < 50 ||
1923                ((Tok.isNot(tok::colon) && getLangOpts().OpenMP >= 50))))
1924             Length = ParseExpression();
1925         }
1926         if (getLangOpts().OpenMP >= 50 &&
1927             (OMPClauseKind == llvm::omp::Clause::OMPC_to ||
1928              OMPClauseKind == llvm::omp::Clause::OMPC_from) &&
1929             Tok.is(tok::colon)) {
1930           // Consume ':'
1931           ColonLocSecond = ConsumeToken();
1932           if (Tok.isNot(tok::r_square)) {
1933             Stride = ParseExpression();
1934           }
1935         }
1936       } else
1937         Idx = ParseExpression();
1938 
1939       SourceLocation RLoc = Tok.getLocation();
1940 
1941       LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1942       Idx = Actions.CorrectDelayedTyposInExpr(Idx);
1943       Length = Actions.CorrectDelayedTyposInExpr(Length);
1944       if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1945           !Stride.isInvalid() && Tok.is(tok::r_square)) {
1946         if (ColonLocFirst.isValid() || ColonLocSecond.isValid()) {
1947           LHS = Actions.ActOnOMPArraySectionExpr(
1948               LHS.get(), Loc, Idx.get(), ColonLocFirst, ColonLocSecond,
1949               Length.get(), Stride.get(), RLoc);
1950         } else {
1951           LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1952                                                 Idx.get(), RLoc);
1953         }
1954       } else {
1955         LHS = ExprError();
1956         Idx = ExprError();
1957       }
1958 
1959       // Match the ']'.
1960       T.consumeClose();
1961       break;
1962     }
1963 
1964     case tok::l_paren:         // p-e: p-e '(' argument-expression-list[opt] ')'
1965     case tok::lesslessless: {  // p-e: p-e '<<<' argument-expression-list '>>>'
1966                                //   '(' argument-expression-list[opt] ')'
1967       tok::TokenKind OpKind = Tok.getKind();
1968       InMessageExpressionRAIIObject InMessage(*this, false);
1969 
1970       Expr *ExecConfig = nullptr;
1971 
1972       BalancedDelimiterTracker PT(*this, tok::l_paren);
1973 
1974       if (OpKind == tok::lesslessless) {
1975         ExprVector ExecConfigExprs;
1976         CommaLocsTy ExecConfigCommaLocs;
1977         SourceLocation OpenLoc = ConsumeToken();
1978 
1979         if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1980           (void)Actions.CorrectDelayedTyposInExpr(LHS);
1981           LHS = ExprError();
1982         }
1983 
1984         SourceLocation CloseLoc;
1985         if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1986         } else if (LHS.isInvalid()) {
1987           SkipUntil(tok::greatergreatergreater, StopAtSemi);
1988         } else {
1989           // There was an error closing the brackets
1990           Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1991           Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1992           SkipUntil(tok::greatergreatergreater, StopAtSemi);
1993           LHS = ExprError();
1994         }
1995 
1996         if (!LHS.isInvalid()) {
1997           if (ExpectAndConsume(tok::l_paren))
1998             LHS = ExprError();
1999           else
2000             Loc = PrevTokLocation;
2001         }
2002 
2003         if (!LHS.isInvalid()) {
2004           ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
2005                                     OpenLoc,
2006                                     ExecConfigExprs,
2007                                     CloseLoc);
2008           if (ECResult.isInvalid())
2009             LHS = ExprError();
2010           else
2011             ExecConfig = ECResult.get();
2012         }
2013       } else {
2014         PT.consumeOpen();
2015         Loc = PT.getOpenLocation();
2016       }
2017 
2018       ExprVector ArgExprs;
2019       CommaLocsTy CommaLocs;
2020       auto RunSignatureHelp = [&]() -> QualType {
2021         QualType PreferredType = Actions.ProduceCallSignatureHelp(
2022             LHS.get(), ArgExprs, PT.getOpenLocation());
2023         CalledSignatureHelp = true;
2024         return PreferredType;
2025       };
2026       if (OpKind == tok::l_paren || !LHS.isInvalid()) {
2027         if (Tok.isNot(tok::r_paren)) {
2028           if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
2029                 PreferredType.enterFunctionArgument(Tok.getLocation(),
2030                                                     RunSignatureHelp);
2031               })) {
2032             (void)Actions.CorrectDelayedTyposInExpr(LHS);
2033             // If we got an error when parsing expression list, we don't call
2034             // the CodeCompleteCall handler inside the parser. So call it here
2035             // to make sure we get overload suggestions even when we are in the
2036             // middle of a parameter.
2037             if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
2038               RunSignatureHelp();
2039             LHS = ExprError();
2040           } else if (LHS.isInvalid()) {
2041             for (auto &E : ArgExprs)
2042               Actions.CorrectDelayedTyposInExpr(E);
2043           }
2044         }
2045       }
2046 
2047       // Match the ')'.
2048       if (LHS.isInvalid()) {
2049         SkipUntil(tok::r_paren, StopAtSemi);
2050       } else if (Tok.isNot(tok::r_paren)) {
2051         bool HadDelayedTypo = false;
2052         if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
2053           HadDelayedTypo = true;
2054         for (auto &E : ArgExprs)
2055           if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
2056             HadDelayedTypo = true;
2057         // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
2058         // instead of PT.consumeClose() to avoid emitting extra diagnostics for
2059         // the unmatched l_paren.
2060         if (HadDelayedTypo)
2061           SkipUntil(tok::r_paren, StopAtSemi);
2062         else
2063           PT.consumeClose();
2064         LHS = ExprError();
2065       } else {
2066         assert(
2067             (ArgExprs.size() == 0 || ArgExprs.size() - 1 == CommaLocs.size()) &&
2068             "Unexpected number of commas!");
2069         Expr *Fn = LHS.get();
2070         SourceLocation RParLoc = Tok.getLocation();
2071         LHS = Actions.ActOnCallExpr(getCurScope(), Fn, Loc, ArgExprs, RParLoc,
2072                                     ExecConfig);
2073         if (LHS.isInvalid()) {
2074           ArgExprs.insert(ArgExprs.begin(), Fn);
2075           LHS =
2076               Actions.CreateRecoveryExpr(Fn->getBeginLoc(), RParLoc, ArgExprs);
2077         }
2078         PT.consumeClose();
2079       }
2080 
2081       break;
2082     }
2083     case tok::arrow:
2084     case tok::period: {
2085       // postfix-expression: p-e '->' template[opt] id-expression
2086       // postfix-expression: p-e '.' template[opt] id-expression
2087       tok::TokenKind OpKind = Tok.getKind();
2088       SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
2089 
2090       CXXScopeSpec SS;
2091       ParsedType ObjectType;
2092       bool MayBePseudoDestructor = false;
2093       Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr;
2094 
2095       PreferredType.enterMemAccess(Actions, Tok.getLocation(), OrigLHS);
2096 
2097       if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
2098         Expr *Base = OrigLHS;
2099         const Type* BaseType = Base->getType().getTypePtrOrNull();
2100         if (BaseType && Tok.is(tok::l_paren) &&
2101             (BaseType->isFunctionType() ||
2102              BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
2103           Diag(OpLoc, diag::err_function_is_not_record)
2104               << OpKind << Base->getSourceRange()
2105               << FixItHint::CreateRemoval(OpLoc);
2106           return ParsePostfixExpressionSuffix(Base);
2107         }
2108 
2109         LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, OpLoc,
2110                                                    OpKind, ObjectType,
2111                                                    MayBePseudoDestructor);
2112         if (LHS.isInvalid()) {
2113           // Clang will try to perform expression based completion as a
2114           // fallback, which is confusing in case of member references. So we
2115           // stop here without any completions.
2116           if (Tok.is(tok::code_completion)) {
2117             cutOffParsing();
2118             return ExprError();
2119           }
2120           break;
2121         }
2122         ParseOptionalCXXScopeSpecifier(
2123             SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2124             /*EnteringContext=*/false, &MayBePseudoDestructor);
2125         if (SS.isNotEmpty())
2126           ObjectType = nullptr;
2127       }
2128 
2129       if (Tok.is(tok::code_completion)) {
2130         tok::TokenKind CorrectedOpKind =
2131             OpKind == tok::arrow ? tok::period : tok::arrow;
2132         ExprResult CorrectedLHS(/*Invalid=*/true);
2133         if (getLangOpts().CPlusPlus && OrigLHS) {
2134           // FIXME: Creating a TentativeAnalysisScope from outside Sema is a
2135           // hack.
2136           Sema::TentativeAnalysisScope Trap(Actions);
2137           CorrectedLHS = Actions.ActOnStartCXXMemberReference(
2138               getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
2139               MayBePseudoDestructor);
2140         }
2141 
2142         Expr *Base = LHS.get();
2143         Expr *CorrectedBase = CorrectedLHS.get();
2144         if (!CorrectedBase && !getLangOpts().CPlusPlus)
2145           CorrectedBase = Base;
2146 
2147         // Code completion for a member access expression.
2148         cutOffParsing();
2149         Actions.CodeCompleteMemberReferenceExpr(
2150             getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
2151             Base && ExprStatementTokLoc == Base->getBeginLoc(),
2152             PreferredType.get(Tok.getLocation()));
2153 
2154         return ExprError();
2155       }
2156 
2157       if (MayBePseudoDestructor && !LHS.isInvalid()) {
2158         LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
2159                                        ObjectType);
2160         break;
2161       }
2162 
2163       // Either the action has told us that this cannot be a
2164       // pseudo-destructor expression (based on the type of base
2165       // expression), or we didn't see a '~' in the right place. We
2166       // can still parse a destructor name here, but in that case it
2167       // names a real destructor.
2168       // Allow explicit constructor calls in Microsoft mode.
2169       // FIXME: Add support for explicit call of template constructor.
2170       SourceLocation TemplateKWLoc;
2171       UnqualifiedId Name;
2172       if (getLangOpts().ObjC && OpKind == tok::period &&
2173           Tok.is(tok::kw_class)) {
2174         // Objective-C++:
2175         //   After a '.' in a member access expression, treat the keyword
2176         //   'class' as if it were an identifier.
2177         //
2178         // This hack allows property access to the 'class' method because it is
2179         // such a common method name. For other C++ keywords that are
2180         // Objective-C method names, one must use the message send syntax.
2181         IdentifierInfo *Id = Tok.getIdentifierInfo();
2182         SourceLocation Loc = ConsumeToken();
2183         Name.setIdentifier(Id, Loc);
2184       } else if (ParseUnqualifiedId(
2185                      SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2186                      /*EnteringContext=*/false,
2187                      /*AllowDestructorName=*/true,
2188                      /*AllowConstructorName=*/
2189                      getLangOpts().MicrosoftExt && SS.isNotEmpty(),
2190                      /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) {
2191         (void)Actions.CorrectDelayedTyposInExpr(LHS);
2192         LHS = ExprError();
2193       }
2194 
2195       if (!LHS.isInvalid())
2196         LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
2197                                             OpKind, SS, TemplateKWLoc, Name,
2198                                  CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
2199                                                    : nullptr);
2200       if (!LHS.isInvalid()) {
2201         if (Tok.is(tok::less))
2202           checkPotentialAngleBracket(LHS);
2203       } else if (OrigLHS && Name.isValid()) {
2204         // Preserve the LHS if the RHS is an invalid member.
2205         LHS = Actions.CreateRecoveryExpr(OrigLHS->getBeginLoc(),
2206                                          Name.getEndLoc(), {OrigLHS});
2207       }
2208       break;
2209     }
2210     case tok::plusplus:    // postfix-expression: postfix-expression '++'
2211     case tok::minusminus:  // postfix-expression: postfix-expression '--'
2212       if (!LHS.isInvalid()) {
2213         Expr *Arg = LHS.get();
2214         LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
2215                                           Tok.getKind(), Arg);
2216         if (LHS.isInvalid())
2217           LHS = Actions.CreateRecoveryExpr(Arg->getBeginLoc(),
2218                                            Tok.getLocation(), Arg);
2219       }
2220       ConsumeToken();
2221       break;
2222     }
2223   }
2224 }
2225 
2226 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
2227 /// vec_step and we are at the start of an expression or a parenthesized
2228 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
2229 /// expression (isCastExpr == false) or the type (isCastExpr == true).
2230 ///
2231 /// \verbatim
2232 ///       unary-expression:  [C99 6.5.3]
2233 ///         'sizeof' unary-expression
2234 ///         'sizeof' '(' type-name ')'
2235 /// [GNU]   '__alignof' unary-expression
2236 /// [GNU]   '__alignof' '(' type-name ')'
2237 /// [C11]   '_Alignof' '(' type-name ')'
2238 /// [C++0x] 'alignof' '(' type-id ')'
2239 ///
2240 /// [GNU]   typeof-specifier:
2241 ///           typeof ( expressions )
2242 ///           typeof ( type-name )
2243 /// [GNU/C++] typeof unary-expression
2244 ///
2245 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
2246 ///           vec_step ( expressions )
2247 ///           vec_step ( type-name )
2248 /// \endverbatim
2249 ExprResult
2250 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
2251                                            bool &isCastExpr,
2252                                            ParsedType &CastTy,
2253                                            SourceRange &CastRange) {
2254 
2255   assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
2256                        tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
2257                        tok::kw___builtin_omp_required_simd_align) &&
2258          "Not a typeof/sizeof/alignof/vec_step expression!");
2259 
2260   ExprResult Operand;
2261 
2262   // If the operand doesn't start with an '(', it must be an expression.
2263   if (Tok.isNot(tok::l_paren)) {
2264     // If construct allows a form without parenthesis, user may forget to put
2265     // pathenthesis around type name.
2266     if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2267                       tok::kw__Alignof)) {
2268       if (isTypeIdUnambiguously()) {
2269         DeclSpec DS(AttrFactory);
2270         ParseSpecifierQualifierList(DS);
2271         Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
2272         ParseDeclarator(DeclaratorInfo);
2273 
2274         SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
2275         SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
2276         if (LParenLoc.isInvalid() || RParenLoc.isInvalid()) {
2277           Diag(OpTok.getLocation(),
2278                diag::err_expected_parentheses_around_typename)
2279               << OpTok.getName();
2280         } else {
2281           Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
2282               << OpTok.getName() << FixItHint::CreateInsertion(LParenLoc, "(")
2283               << FixItHint::CreateInsertion(RParenLoc, ")");
2284         }
2285         isCastExpr = true;
2286         return ExprEmpty();
2287       }
2288     }
2289 
2290     isCastExpr = false;
2291     if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
2292       Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
2293                                           << tok::l_paren;
2294       return ExprError();
2295     }
2296 
2297     Operand = ParseCastExpression(UnaryExprOnly);
2298   } else {
2299     // If it starts with a '(', we know that it is either a parenthesized
2300     // type-name, or it is a unary-expression that starts with a compound
2301     // literal, or starts with a primary-expression that is a parenthesized
2302     // expression.
2303     ParenParseOption ExprType = CastExpr;
2304     SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
2305 
2306     Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
2307                                    false, CastTy, RParenLoc);
2308     CastRange = SourceRange(LParenLoc, RParenLoc);
2309 
2310     // If ParseParenExpression parsed a '(typename)' sequence only, then this is
2311     // a type.
2312     if (ExprType == CastExpr) {
2313       isCastExpr = true;
2314       return ExprEmpty();
2315     }
2316 
2317     if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
2318       // GNU typeof in C requires the expression to be parenthesized. Not so for
2319       // sizeof/alignof or in C++. Therefore, the parenthesized expression is
2320       // the start of a unary-expression, but doesn't include any postfix
2321       // pieces. Parse these now if present.
2322       if (!Operand.isInvalid())
2323         Operand = ParsePostfixExpressionSuffix(Operand.get());
2324     }
2325   }
2326 
2327   // If we get here, the operand to the typeof/sizeof/alignof was an expression.
2328   isCastExpr = false;
2329   return Operand;
2330 }
2331 
2332 /// Parse a __builtin_sycl_unique_stable_name expression.  Accepts a type-id as
2333 /// a parameter.
2334 ExprResult Parser::ParseSYCLUniqueStableNameExpression() {
2335   assert(Tok.is(tok::kw___builtin_sycl_unique_stable_name) &&
2336          "Not __builtin_sycl_unique_stable_name");
2337 
2338   SourceLocation OpLoc = ConsumeToken();
2339   BalancedDelimiterTracker T(*this, tok::l_paren);
2340 
2341   // __builtin_sycl_unique_stable_name expressions are always parenthesized.
2342   if (T.expectAndConsume(diag::err_expected_lparen_after,
2343                          "__builtin_sycl_unique_stable_name"))
2344     return ExprError();
2345 
2346   TypeResult Ty = ParseTypeName();
2347 
2348   if (Ty.isInvalid()) {
2349     T.skipToEnd();
2350     return ExprError();
2351   }
2352 
2353   if (T.consumeClose())
2354     return ExprError();
2355 
2356   return Actions.ActOnSYCLUniqueStableNameExpr(OpLoc, T.getOpenLocation(),
2357                                                T.getCloseLocation(), Ty.get());
2358 }
2359 
2360 /// Parse a sizeof or alignof expression.
2361 ///
2362 /// \verbatim
2363 ///       unary-expression:  [C99 6.5.3]
2364 ///         'sizeof' unary-expression
2365 ///         'sizeof' '(' type-name ')'
2366 /// [C++11] 'sizeof' '...' '(' identifier ')'
2367 /// [GNU]   '__alignof' unary-expression
2368 /// [GNU]   '__alignof' '(' type-name ')'
2369 /// [C11]   '_Alignof' '(' type-name ')'
2370 /// [C++11] 'alignof' '(' type-id ')'
2371 /// \endverbatim
2372 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
2373   assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2374                      tok::kw__Alignof, tok::kw_vec_step,
2375                      tok::kw___builtin_omp_required_simd_align) &&
2376          "Not a sizeof/alignof/vec_step expression!");
2377   Token OpTok = Tok;
2378   ConsumeToken();
2379 
2380   // [C++11] 'sizeof' '...' '(' identifier ')'
2381   if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
2382     SourceLocation EllipsisLoc = ConsumeToken();
2383     SourceLocation LParenLoc, RParenLoc;
2384     IdentifierInfo *Name = nullptr;
2385     SourceLocation NameLoc;
2386     if (Tok.is(tok::l_paren)) {
2387       BalancedDelimiterTracker T(*this, tok::l_paren);
2388       T.consumeOpen();
2389       LParenLoc = T.getOpenLocation();
2390       if (Tok.is(tok::identifier)) {
2391         Name = Tok.getIdentifierInfo();
2392         NameLoc = ConsumeToken();
2393         T.consumeClose();
2394         RParenLoc = T.getCloseLocation();
2395         if (RParenLoc.isInvalid())
2396           RParenLoc = PP.getLocForEndOfToken(NameLoc);
2397       } else {
2398         Diag(Tok, diag::err_expected_parameter_pack);
2399         SkipUntil(tok::r_paren, StopAtSemi);
2400       }
2401     } else if (Tok.is(tok::identifier)) {
2402       Name = Tok.getIdentifierInfo();
2403       NameLoc = ConsumeToken();
2404       LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
2405       RParenLoc = PP.getLocForEndOfToken(NameLoc);
2406       Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
2407         << Name
2408         << FixItHint::CreateInsertion(LParenLoc, "(")
2409         << FixItHint::CreateInsertion(RParenLoc, ")");
2410     } else {
2411       Diag(Tok, diag::err_sizeof_parameter_pack);
2412     }
2413 
2414     if (!Name)
2415       return ExprError();
2416 
2417     EnterExpressionEvaluationContext Unevaluated(
2418         Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2419         Sema::ReuseLambdaContextDecl);
2420 
2421     return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
2422                                                 OpTok.getLocation(),
2423                                                 *Name, NameLoc,
2424                                                 RParenLoc);
2425   }
2426 
2427   if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2428     Diag(OpTok, diag::warn_cxx98_compat_alignof);
2429 
2430   EnterExpressionEvaluationContext Unevaluated(
2431       Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2432       Sema::ReuseLambdaContextDecl);
2433 
2434   bool isCastExpr;
2435   ParsedType CastTy;
2436   SourceRange CastRange;
2437   ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
2438                                                           isCastExpr,
2439                                                           CastTy,
2440                                                           CastRange);
2441 
2442   UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2443   if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2444     ExprKind = UETT_AlignOf;
2445   else if (OpTok.is(tok::kw___alignof))
2446     ExprKind = UETT_PreferredAlignOf;
2447   else if (OpTok.is(tok::kw_vec_step))
2448     ExprKind = UETT_VecStep;
2449   else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2450     ExprKind = UETT_OpenMPRequiredSimdAlign;
2451 
2452   if (isCastExpr)
2453     return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2454                                                  ExprKind,
2455                                                  /*IsType=*/true,
2456                                                  CastTy.getAsOpaquePtr(),
2457                                                  CastRange);
2458 
2459   if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2460     Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2461 
2462   // If we get here, the operand to the sizeof/alignof was an expression.
2463   if (!Operand.isInvalid())
2464     Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2465                                                     ExprKind,
2466                                                     /*IsType=*/false,
2467                                                     Operand.get(),
2468                                                     CastRange);
2469   return Operand;
2470 }
2471 
2472 /// ParseBuiltinPrimaryExpression
2473 ///
2474 /// \verbatim
2475 ///       primary-expression: [C99 6.5.1]
2476 /// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2477 /// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2478 /// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2479 ///                                     assign-expr ')'
2480 /// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2481 /// [GNU]   '__builtin_FILE' '(' ')'
2482 /// [GNU]   '__builtin_FUNCTION' '(' ')'
2483 /// [GNU]   '__builtin_LINE' '(' ')'
2484 /// [CLANG] '__builtin_COLUMN' '(' ')'
2485 /// [OCL]   '__builtin_astype' '(' assignment-expression ',' type-name ')'
2486 ///
2487 /// [GNU] offsetof-member-designator:
2488 /// [GNU]   identifier
2489 /// [GNU]   offsetof-member-designator '.' identifier
2490 /// [GNU]   offsetof-member-designator '[' expression ']'
2491 /// \endverbatim
2492 ExprResult Parser::ParseBuiltinPrimaryExpression() {
2493   ExprResult Res;
2494   const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2495 
2496   tok::TokenKind T = Tok.getKind();
2497   SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
2498 
2499   // All of these start with an open paren.
2500   if (Tok.isNot(tok::l_paren))
2501     return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2502                                                          << tok::l_paren);
2503 
2504   BalancedDelimiterTracker PT(*this, tok::l_paren);
2505   PT.consumeOpen();
2506 
2507   // TODO: Build AST.
2508 
2509   switch (T) {
2510   default: llvm_unreachable("Not a builtin primary expression!");
2511   case tok::kw___builtin_va_arg: {
2512     ExprResult Expr(ParseAssignmentExpression());
2513 
2514     if (ExpectAndConsume(tok::comma)) {
2515       SkipUntil(tok::r_paren, StopAtSemi);
2516       Expr = ExprError();
2517     }
2518 
2519     TypeResult Ty = ParseTypeName();
2520 
2521     if (Tok.isNot(tok::r_paren)) {
2522       Diag(Tok, diag::err_expected) << tok::r_paren;
2523       Expr = ExprError();
2524     }
2525 
2526     if (Expr.isInvalid() || Ty.isInvalid())
2527       Res = ExprError();
2528     else
2529       Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2530     break;
2531   }
2532   case tok::kw___builtin_offsetof: {
2533     SourceLocation TypeLoc = Tok.getLocation();
2534     TypeResult Ty = ParseTypeName();
2535     if (Ty.isInvalid()) {
2536       SkipUntil(tok::r_paren, StopAtSemi);
2537       return ExprError();
2538     }
2539 
2540     if (ExpectAndConsume(tok::comma)) {
2541       SkipUntil(tok::r_paren, StopAtSemi);
2542       return ExprError();
2543     }
2544 
2545     // We must have at least one identifier here.
2546     if (Tok.isNot(tok::identifier)) {
2547       Diag(Tok, diag::err_expected) << tok::identifier;
2548       SkipUntil(tok::r_paren, StopAtSemi);
2549       return ExprError();
2550     }
2551 
2552     // Keep track of the various subcomponents we see.
2553     SmallVector<Sema::OffsetOfComponent, 4> Comps;
2554 
2555     Comps.push_back(Sema::OffsetOfComponent());
2556     Comps.back().isBrackets = false;
2557     Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2558     Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2559 
2560     // FIXME: This loop leaks the index expressions on error.
2561     while (true) {
2562       if (Tok.is(tok::period)) {
2563         // offsetof-member-designator: offsetof-member-designator '.' identifier
2564         Comps.push_back(Sema::OffsetOfComponent());
2565         Comps.back().isBrackets = false;
2566         Comps.back().LocStart = ConsumeToken();
2567 
2568         if (Tok.isNot(tok::identifier)) {
2569           Diag(Tok, diag::err_expected) << tok::identifier;
2570           SkipUntil(tok::r_paren, StopAtSemi);
2571           return ExprError();
2572         }
2573         Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2574         Comps.back().LocEnd = ConsumeToken();
2575 
2576       } else if (Tok.is(tok::l_square)) {
2577         if (CheckProhibitedCXX11Attribute())
2578           return ExprError();
2579 
2580         // offsetof-member-designator: offsetof-member-design '[' expression ']'
2581         Comps.push_back(Sema::OffsetOfComponent());
2582         Comps.back().isBrackets = true;
2583         BalancedDelimiterTracker ST(*this, tok::l_square);
2584         ST.consumeOpen();
2585         Comps.back().LocStart = ST.getOpenLocation();
2586         Res = ParseExpression();
2587         if (Res.isInvalid()) {
2588           SkipUntil(tok::r_paren, StopAtSemi);
2589           return Res;
2590         }
2591         Comps.back().U.E = Res.get();
2592 
2593         ST.consumeClose();
2594         Comps.back().LocEnd = ST.getCloseLocation();
2595       } else {
2596         if (Tok.isNot(tok::r_paren)) {
2597           PT.consumeClose();
2598           Res = ExprError();
2599         } else if (Ty.isInvalid()) {
2600           Res = ExprError();
2601         } else {
2602           PT.consumeClose();
2603           Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2604                                              Ty.get(), Comps,
2605                                              PT.getCloseLocation());
2606         }
2607         break;
2608       }
2609     }
2610     break;
2611   }
2612   case tok::kw___builtin_choose_expr: {
2613     ExprResult Cond(ParseAssignmentExpression());
2614     if (Cond.isInvalid()) {
2615       SkipUntil(tok::r_paren, StopAtSemi);
2616       return Cond;
2617     }
2618     if (ExpectAndConsume(tok::comma)) {
2619       SkipUntil(tok::r_paren, StopAtSemi);
2620       return ExprError();
2621     }
2622 
2623     ExprResult Expr1(ParseAssignmentExpression());
2624     if (Expr1.isInvalid()) {
2625       SkipUntil(tok::r_paren, StopAtSemi);
2626       return Expr1;
2627     }
2628     if (ExpectAndConsume(tok::comma)) {
2629       SkipUntil(tok::r_paren, StopAtSemi);
2630       return ExprError();
2631     }
2632 
2633     ExprResult Expr2(ParseAssignmentExpression());
2634     if (Expr2.isInvalid()) {
2635       SkipUntil(tok::r_paren, StopAtSemi);
2636       return Expr2;
2637     }
2638     if (Tok.isNot(tok::r_paren)) {
2639       Diag(Tok, diag::err_expected) << tok::r_paren;
2640       return ExprError();
2641     }
2642     Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2643                                   Expr2.get(), ConsumeParen());
2644     break;
2645   }
2646   case tok::kw___builtin_astype: {
2647     // The first argument is an expression to be converted, followed by a comma.
2648     ExprResult Expr(ParseAssignmentExpression());
2649     if (Expr.isInvalid()) {
2650       SkipUntil(tok::r_paren, StopAtSemi);
2651       return ExprError();
2652     }
2653 
2654     if (ExpectAndConsume(tok::comma)) {
2655       SkipUntil(tok::r_paren, StopAtSemi);
2656       return ExprError();
2657     }
2658 
2659     // Second argument is the type to bitcast to.
2660     TypeResult DestTy = ParseTypeName();
2661     if (DestTy.isInvalid())
2662       return ExprError();
2663 
2664     // Attempt to consume the r-paren.
2665     if (Tok.isNot(tok::r_paren)) {
2666       Diag(Tok, diag::err_expected) << tok::r_paren;
2667       SkipUntil(tok::r_paren, StopAtSemi);
2668       return ExprError();
2669     }
2670 
2671     Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2672                                   ConsumeParen());
2673     break;
2674   }
2675   case tok::kw___builtin_convertvector: {
2676     // The first argument is an expression to be converted, followed by a comma.
2677     ExprResult Expr(ParseAssignmentExpression());
2678     if (Expr.isInvalid()) {
2679       SkipUntil(tok::r_paren, StopAtSemi);
2680       return ExprError();
2681     }
2682 
2683     if (ExpectAndConsume(tok::comma)) {
2684       SkipUntil(tok::r_paren, StopAtSemi);
2685       return ExprError();
2686     }
2687 
2688     // Second argument is the type to bitcast to.
2689     TypeResult DestTy = ParseTypeName();
2690     if (DestTy.isInvalid())
2691       return ExprError();
2692 
2693     // Attempt to consume the r-paren.
2694     if (Tok.isNot(tok::r_paren)) {
2695       Diag(Tok, diag::err_expected) << tok::r_paren;
2696       SkipUntil(tok::r_paren, StopAtSemi);
2697       return ExprError();
2698     }
2699 
2700     Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2701                                          ConsumeParen());
2702     break;
2703   }
2704   case tok::kw___builtin_COLUMN:
2705   case tok::kw___builtin_FILE:
2706   case tok::kw___builtin_FUNCTION:
2707   case tok::kw___builtin_LINE: {
2708     // Attempt to consume the r-paren.
2709     if (Tok.isNot(tok::r_paren)) {
2710       Diag(Tok, diag::err_expected) << tok::r_paren;
2711       SkipUntil(tok::r_paren, StopAtSemi);
2712       return ExprError();
2713     }
2714     SourceLocExpr::IdentKind Kind = [&] {
2715       switch (T) {
2716       case tok::kw___builtin_FILE:
2717         return SourceLocExpr::File;
2718       case tok::kw___builtin_FUNCTION:
2719         return SourceLocExpr::Function;
2720       case tok::kw___builtin_LINE:
2721         return SourceLocExpr::Line;
2722       case tok::kw___builtin_COLUMN:
2723         return SourceLocExpr::Column;
2724       default:
2725         llvm_unreachable("invalid keyword");
2726       }
2727     }();
2728     Res = Actions.ActOnSourceLocExpr(Kind, StartLoc, ConsumeParen());
2729     break;
2730   }
2731   }
2732 
2733   if (Res.isInvalid())
2734     return ExprError();
2735 
2736   // These can be followed by postfix-expr pieces because they are
2737   // primary-expressions.
2738   return ParsePostfixExpressionSuffix(Res.get());
2739 }
2740 
2741 bool Parser::tryParseOpenMPArrayShapingCastPart() {
2742   assert(Tok.is(tok::l_square) && "Expected open bracket");
2743   bool ErrorFound = true;
2744   TentativeParsingAction TPA(*this);
2745   do {
2746     if (Tok.isNot(tok::l_square))
2747       break;
2748     // Consume '['
2749     ConsumeBracket();
2750     // Skip inner expression.
2751     while (!SkipUntil(tok::r_square, tok::annot_pragma_openmp_end,
2752                       StopAtSemi | StopBeforeMatch))
2753       ;
2754     if (Tok.isNot(tok::r_square))
2755       break;
2756     // Consume ']'
2757     ConsumeBracket();
2758     // Found ')' - done.
2759     if (Tok.is(tok::r_paren)) {
2760       ErrorFound = false;
2761       break;
2762     }
2763   } while (Tok.isNot(tok::annot_pragma_openmp_end));
2764   TPA.Revert();
2765   return !ErrorFound;
2766 }
2767 
2768 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2769 /// based on what is allowed by ExprType.  The actual thing parsed is returned
2770 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2771 /// not the parsed cast-expression.
2772 ///
2773 /// \verbatim
2774 ///       primary-expression: [C99 6.5.1]
2775 ///         '(' expression ')'
2776 /// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
2777 ///       postfix-expression: [C99 6.5.2]
2778 ///         '(' type-name ')' '{' initializer-list '}'
2779 ///         '(' type-name ')' '{' initializer-list ',' '}'
2780 ///       cast-expression: [C99 6.5.4]
2781 ///         '(' type-name ')' cast-expression
2782 /// [ARC]   bridged-cast-expression
2783 /// [ARC] bridged-cast-expression:
2784 ///         (__bridge type-name) cast-expression
2785 ///         (__bridge_transfer type-name) cast-expression
2786 ///         (__bridge_retained type-name) cast-expression
2787 ///       fold-expression: [C++1z]
2788 ///         '(' cast-expression fold-operator '...' ')'
2789 ///         '(' '...' fold-operator cast-expression ')'
2790 ///         '(' cast-expression fold-operator '...'
2791 ///                 fold-operator cast-expression ')'
2792 /// [OPENMP] Array shaping operation
2793 ///       '(' '[' expression ']' { '[' expression ']' } cast-expression
2794 /// \endverbatim
2795 ExprResult
2796 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2797                              bool isTypeCast, ParsedType &CastTy,
2798                              SourceLocation &RParenLoc) {
2799   assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2800   ColonProtectionRAIIObject ColonProtection(*this, false);
2801   BalancedDelimiterTracker T(*this, tok::l_paren);
2802   if (T.consumeOpen())
2803     return ExprError();
2804   SourceLocation OpenLoc = T.getOpenLocation();
2805 
2806   PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
2807 
2808   ExprResult Result(true);
2809   bool isAmbiguousTypeId;
2810   CastTy = nullptr;
2811 
2812   if (Tok.is(tok::code_completion)) {
2813     cutOffParsing();
2814     Actions.CodeCompleteExpression(
2815         getCurScope(), PreferredType.get(Tok.getLocation()),
2816         /*IsParenthesized=*/ExprType >= CompoundLiteral);
2817     return ExprError();
2818   }
2819 
2820   // Diagnose use of bridge casts in non-arc mode.
2821   bool BridgeCast = (getLangOpts().ObjC &&
2822                      Tok.isOneOf(tok::kw___bridge,
2823                                  tok::kw___bridge_transfer,
2824                                  tok::kw___bridge_retained,
2825                                  tok::kw___bridge_retain));
2826   if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2827     if (!TryConsumeToken(tok::kw___bridge)) {
2828       StringRef BridgeCastName = Tok.getName();
2829       SourceLocation BridgeKeywordLoc = ConsumeToken();
2830       if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2831         Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2832           << BridgeCastName
2833           << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2834     }
2835     BridgeCast = false;
2836   }
2837 
2838   // None of these cases should fall through with an invalid Result
2839   // unless they've already reported an error.
2840   if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2841     Diag(Tok, diag::ext_gnu_statement_expr);
2842 
2843     checkCompoundToken(OpenLoc, tok::l_paren, CompoundToken::StmtExprBegin);
2844 
2845     if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2846       Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2847     } else {
2848       // Find the nearest non-record decl context. Variables declared in a
2849       // statement expression behave as if they were declared in the enclosing
2850       // function, block, or other code construct.
2851       DeclContext *CodeDC = Actions.CurContext;
2852       while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2853         CodeDC = CodeDC->getParent();
2854         assert(CodeDC && !CodeDC->isFileContext() &&
2855                "statement expr not in code context");
2856       }
2857       Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2858 
2859       Actions.ActOnStartStmtExpr();
2860 
2861       StmtResult Stmt(ParseCompoundStatement(true));
2862       ExprType = CompoundStmt;
2863 
2864       // If the substmt parsed correctly, build the AST node.
2865       if (!Stmt.isInvalid()) {
2866         Result = Actions.ActOnStmtExpr(getCurScope(), OpenLoc, Stmt.get(),
2867                                        Tok.getLocation());
2868       } else {
2869         Actions.ActOnStmtExprError();
2870       }
2871     }
2872   } else if (ExprType >= CompoundLiteral && BridgeCast) {
2873     tok::TokenKind tokenKind = Tok.getKind();
2874     SourceLocation BridgeKeywordLoc = ConsumeToken();
2875 
2876     // Parse an Objective-C ARC ownership cast expression.
2877     ObjCBridgeCastKind Kind;
2878     if (tokenKind == tok::kw___bridge)
2879       Kind = OBC_Bridge;
2880     else if (tokenKind == tok::kw___bridge_transfer)
2881       Kind = OBC_BridgeTransfer;
2882     else if (tokenKind == tok::kw___bridge_retained)
2883       Kind = OBC_BridgeRetained;
2884     else {
2885       // As a hopefully temporary workaround, allow __bridge_retain as
2886       // a synonym for __bridge_retained, but only in system headers.
2887       assert(tokenKind == tok::kw___bridge_retain);
2888       Kind = OBC_BridgeRetained;
2889       if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2890         Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2891           << FixItHint::CreateReplacement(BridgeKeywordLoc,
2892                                           "__bridge_retained");
2893     }
2894 
2895     TypeResult Ty = ParseTypeName();
2896     T.consumeClose();
2897     ColonProtection.restore();
2898     RParenLoc = T.getCloseLocation();
2899 
2900     PreferredType.enterTypeCast(Tok.getLocation(), Ty.get().get());
2901     ExprResult SubExpr = ParseCastExpression(AnyCastExpr);
2902 
2903     if (Ty.isInvalid() || SubExpr.isInvalid())
2904       return ExprError();
2905 
2906     return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2907                                         BridgeKeywordLoc, Ty.get(),
2908                                         RParenLoc, SubExpr.get());
2909   } else if (ExprType >= CompoundLiteral &&
2910              isTypeIdInParens(isAmbiguousTypeId)) {
2911 
2912     // Otherwise, this is a compound literal expression or cast expression.
2913 
2914     // In C++, if the type-id is ambiguous we disambiguate based on context.
2915     // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2916     // in which case we should treat it as type-id.
2917     // if stopIfCastExpr is false, we need to determine the context past the
2918     // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2919     if (isAmbiguousTypeId && !stopIfCastExpr) {
2920       ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2921                                                         ColonProtection);
2922       RParenLoc = T.getCloseLocation();
2923       return res;
2924     }
2925 
2926     // Parse the type declarator.
2927     DeclSpec DS(AttrFactory);
2928     ParseSpecifierQualifierList(DS);
2929     Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
2930     ParseDeclarator(DeclaratorInfo);
2931 
2932     // If our type is followed by an identifier and either ':' or ']', then
2933     // this is probably an Objective-C message send where the leading '[' is
2934     // missing. Recover as if that were the case.
2935     if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2936         !InMessageExpression && getLangOpts().ObjC &&
2937         (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2938       TypeResult Ty;
2939       {
2940         InMessageExpressionRAIIObject InMessage(*this, false);
2941         Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2942       }
2943       Result = ParseObjCMessageExpressionBody(SourceLocation(),
2944                                               SourceLocation(),
2945                                               Ty.get(), nullptr);
2946     } else {
2947       // Match the ')'.
2948       T.consumeClose();
2949       ColonProtection.restore();
2950       RParenLoc = T.getCloseLocation();
2951       if (Tok.is(tok::l_brace)) {
2952         ExprType = CompoundLiteral;
2953         TypeResult Ty;
2954         {
2955           InMessageExpressionRAIIObject InMessage(*this, false);
2956           Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2957         }
2958         return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2959       }
2960 
2961       if (Tok.is(tok::l_paren)) {
2962         // This could be OpenCL vector Literals
2963         if (getLangOpts().OpenCL)
2964         {
2965           TypeResult Ty;
2966           {
2967             InMessageExpressionRAIIObject InMessage(*this, false);
2968             Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2969           }
2970           if(Ty.isInvalid())
2971           {
2972              return ExprError();
2973           }
2974           QualType QT = Ty.get().get().getCanonicalType();
2975           if (QT->isVectorType())
2976           {
2977             // We parsed '(' vector-type-name ')' followed by '('
2978 
2979             // Parse the cast-expression that follows it next.
2980             // isVectorLiteral = true will make sure we don't parse any
2981             // Postfix expression yet
2982             Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
2983                                          /*isAddressOfOperand=*/false,
2984                                          /*isTypeCast=*/IsTypeCast,
2985                                          /*isVectorLiteral=*/true);
2986 
2987             if (!Result.isInvalid()) {
2988               Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2989                                              DeclaratorInfo, CastTy,
2990                                              RParenLoc, Result.get());
2991             }
2992 
2993             // After we performed the cast we can check for postfix-expr pieces.
2994             if (!Result.isInvalid()) {
2995               Result = ParsePostfixExpressionSuffix(Result);
2996             }
2997 
2998             return Result;
2999           }
3000         }
3001       }
3002 
3003       if (ExprType == CastExpr) {
3004         // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
3005 
3006         if (DeclaratorInfo.isInvalidType())
3007           return ExprError();
3008 
3009         // Note that this doesn't parse the subsequent cast-expression, it just
3010         // returns the parsed type to the callee.
3011         if (stopIfCastExpr) {
3012           TypeResult Ty;
3013           {
3014             InMessageExpressionRAIIObject InMessage(*this, false);
3015             Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3016           }
3017           CastTy = Ty.get();
3018           return ExprResult();
3019         }
3020 
3021         // Reject the cast of super idiom in ObjC.
3022         if (Tok.is(tok::identifier) && getLangOpts().ObjC &&
3023             Tok.getIdentifierInfo() == Ident_super &&
3024             getCurScope()->isInObjcMethodScope() &&
3025             GetLookAheadToken(1).isNot(tok::period)) {
3026           Diag(Tok.getLocation(), diag::err_illegal_super_cast)
3027             << SourceRange(OpenLoc, RParenLoc);
3028           return ExprError();
3029         }
3030 
3031         PreferredType.enterTypeCast(Tok.getLocation(), CastTy.get());
3032         // Parse the cast-expression that follows it next.
3033         // TODO: For cast expression with CastTy.
3034         Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3035                                      /*isAddressOfOperand=*/false,
3036                                      /*isTypeCast=*/IsTypeCast);
3037         if (!Result.isInvalid()) {
3038           Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3039                                          DeclaratorInfo, CastTy,
3040                                          RParenLoc, Result.get());
3041         }
3042         return Result;
3043       }
3044 
3045       Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
3046       return ExprError();
3047     }
3048   } else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) &&
3049              isFoldOperator(NextToken().getKind())) {
3050     ExprType = FoldExpr;
3051     return ParseFoldExpression(ExprResult(), T);
3052   } else if (isTypeCast) {
3053     // Parse the expression-list.
3054     InMessageExpressionRAIIObject InMessage(*this, false);
3055 
3056     ExprVector ArgExprs;
3057     CommaLocsTy CommaLocs;
3058 
3059     if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
3060       // FIXME: If we ever support comma expressions as operands to
3061       // fold-expressions, we'll need to allow multiple ArgExprs here.
3062       if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
3063           isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
3064         ExprType = FoldExpr;
3065         return ParseFoldExpression(ArgExprs[0], T);
3066       }
3067 
3068       ExprType = SimpleExpr;
3069       Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
3070                                           ArgExprs);
3071     }
3072   } else if (getLangOpts().OpenMP >= 50 && OpenMPDirectiveParsing &&
3073              ExprType == CastExpr && Tok.is(tok::l_square) &&
3074              tryParseOpenMPArrayShapingCastPart()) {
3075     bool ErrorFound = false;
3076     SmallVector<Expr *, 4> OMPDimensions;
3077     SmallVector<SourceRange, 4> OMPBracketsRanges;
3078     do {
3079       BalancedDelimiterTracker TS(*this, tok::l_square);
3080       TS.consumeOpen();
3081       ExprResult NumElements =
3082           Actions.CorrectDelayedTyposInExpr(ParseExpression());
3083       if (!NumElements.isUsable()) {
3084         ErrorFound = true;
3085         while (!SkipUntil(tok::r_square, tok::r_paren,
3086                           StopAtSemi | StopBeforeMatch))
3087           ;
3088       }
3089       TS.consumeClose();
3090       OMPDimensions.push_back(NumElements.get());
3091       OMPBracketsRanges.push_back(TS.getRange());
3092     } while (Tok.isNot(tok::r_paren));
3093     // Match the ')'.
3094     T.consumeClose();
3095     RParenLoc = T.getCloseLocation();
3096     Result = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3097     if (ErrorFound) {
3098       Result = ExprError();
3099     } else if (!Result.isInvalid()) {
3100       Result = Actions.ActOnOMPArrayShapingExpr(
3101           Result.get(), OpenLoc, RParenLoc, OMPDimensions, OMPBracketsRanges);
3102     }
3103     return Result;
3104   } else {
3105     InMessageExpressionRAIIObject InMessage(*this, false);
3106 
3107     Result = ParseExpression(MaybeTypeCast);
3108     if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
3109       // Correct typos in non-C++ code earlier so that implicit-cast-like
3110       // expressions are parsed correctly.
3111       Result = Actions.CorrectDelayedTyposInExpr(Result);
3112     }
3113 
3114     if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
3115         NextToken().is(tok::ellipsis)) {
3116       ExprType = FoldExpr;
3117       return ParseFoldExpression(Result, T);
3118     }
3119     ExprType = SimpleExpr;
3120 
3121     // Don't build a paren expression unless we actually match a ')'.
3122     if (!Result.isInvalid() && Tok.is(tok::r_paren))
3123       Result =
3124           Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
3125   }
3126 
3127   // Match the ')'.
3128   if (Result.isInvalid()) {
3129     SkipUntil(tok::r_paren, StopAtSemi);
3130     return ExprError();
3131   }
3132 
3133   T.consumeClose();
3134   RParenLoc = T.getCloseLocation();
3135   return Result;
3136 }
3137 
3138 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
3139 /// and we are at the left brace.
3140 ///
3141 /// \verbatim
3142 ///       postfix-expression: [C99 6.5.2]
3143 ///         '(' type-name ')' '{' initializer-list '}'
3144 ///         '(' type-name ')' '{' initializer-list ',' '}'
3145 /// \endverbatim
3146 ExprResult
3147 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
3148                                        SourceLocation LParenLoc,
3149                                        SourceLocation RParenLoc) {
3150   assert(Tok.is(tok::l_brace) && "Not a compound literal!");
3151   if (!getLangOpts().C99)   // Compound literals don't exist in C90.
3152     Diag(LParenLoc, diag::ext_c99_compound_literal);
3153   PreferredType.enterTypeCast(Tok.getLocation(), Ty.get());
3154   ExprResult Result = ParseInitializer();
3155   if (!Result.isInvalid() && Ty)
3156     return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
3157   return Result;
3158 }
3159 
3160 /// ParseStringLiteralExpression - This handles the various token types that
3161 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
3162 /// translation phase #6].
3163 ///
3164 /// \verbatim
3165 ///       primary-expression: [C99 6.5.1]
3166 ///         string-literal
3167 /// \verbatim
3168 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
3169   assert(isTokenStringLiteral() && "Not a string literal!");
3170 
3171   // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
3172   // considered to be strings for concatenation purposes.
3173   SmallVector<Token, 4> StringToks;
3174 
3175   do {
3176     StringToks.push_back(Tok);
3177     ConsumeStringToken();
3178   } while (isTokenStringLiteral());
3179 
3180   // Pass the set of string tokens, ready for concatenation, to the actions.
3181   return Actions.ActOnStringLiteral(StringToks,
3182                                     AllowUserDefinedLiteral ? getCurScope()
3183                                                             : nullptr);
3184 }
3185 
3186 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
3187 /// [C11 6.5.1.1].
3188 ///
3189 /// \verbatim
3190 ///    generic-selection:
3191 ///           _Generic ( assignment-expression , generic-assoc-list )
3192 ///    generic-assoc-list:
3193 ///           generic-association
3194 ///           generic-assoc-list , generic-association
3195 ///    generic-association:
3196 ///           type-name : assignment-expression
3197 ///           default : assignment-expression
3198 /// \endverbatim
3199 ExprResult Parser::ParseGenericSelectionExpression() {
3200   assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
3201   if (!getLangOpts().C11)
3202     Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3203 
3204   SourceLocation KeyLoc = ConsumeToken();
3205   BalancedDelimiterTracker T(*this, tok::l_paren);
3206   if (T.expectAndConsume())
3207     return ExprError();
3208 
3209   ExprResult ControllingExpr;
3210   {
3211     // C11 6.5.1.1p3 "The controlling expression of a generic selection is
3212     // not evaluated."
3213     EnterExpressionEvaluationContext Unevaluated(
3214         Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3215     ControllingExpr =
3216         Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3217     if (ControllingExpr.isInvalid()) {
3218       SkipUntil(tok::r_paren, StopAtSemi);
3219       return ExprError();
3220     }
3221   }
3222 
3223   if (ExpectAndConsume(tok::comma)) {
3224     SkipUntil(tok::r_paren, StopAtSemi);
3225     return ExprError();
3226   }
3227 
3228   SourceLocation DefaultLoc;
3229   TypeVector Types;
3230   ExprVector Exprs;
3231   do {
3232     ParsedType Ty;
3233     if (Tok.is(tok::kw_default)) {
3234       // C11 6.5.1.1p2 "A generic selection shall have no more than one default
3235       // generic association."
3236       if (!DefaultLoc.isInvalid()) {
3237         Diag(Tok, diag::err_duplicate_default_assoc);
3238         Diag(DefaultLoc, diag::note_previous_default_assoc);
3239         SkipUntil(tok::r_paren, StopAtSemi);
3240         return ExprError();
3241       }
3242       DefaultLoc = ConsumeToken();
3243       Ty = nullptr;
3244     } else {
3245       ColonProtectionRAIIObject X(*this);
3246       TypeResult TR = ParseTypeName();
3247       if (TR.isInvalid()) {
3248         SkipUntil(tok::r_paren, StopAtSemi);
3249         return ExprError();
3250       }
3251       Ty = TR.get();
3252     }
3253     Types.push_back(Ty);
3254 
3255     if (ExpectAndConsume(tok::colon)) {
3256       SkipUntil(tok::r_paren, StopAtSemi);
3257       return ExprError();
3258     }
3259 
3260     // FIXME: These expressions should be parsed in a potentially potentially
3261     // evaluated context.
3262     ExprResult ER(
3263         Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
3264     if (ER.isInvalid()) {
3265       SkipUntil(tok::r_paren, StopAtSemi);
3266       return ExprError();
3267     }
3268     Exprs.push_back(ER.get());
3269   } while (TryConsumeToken(tok::comma));
3270 
3271   T.consumeClose();
3272   if (T.getCloseLocation().isInvalid())
3273     return ExprError();
3274 
3275   return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
3276                                            T.getCloseLocation(),
3277                                            ControllingExpr.get(),
3278                                            Types, Exprs);
3279 }
3280 
3281 /// Parse A C++1z fold-expression after the opening paren and optional
3282 /// left-hand-side expression.
3283 ///
3284 /// \verbatim
3285 ///   fold-expression:
3286 ///       ( cast-expression fold-operator ... )
3287 ///       ( ... fold-operator cast-expression )
3288 ///       ( cast-expression fold-operator ... fold-operator cast-expression )
3289 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
3290                                        BalancedDelimiterTracker &T) {
3291   if (LHS.isInvalid()) {
3292     T.skipToEnd();
3293     return true;
3294   }
3295 
3296   tok::TokenKind Kind = tok::unknown;
3297   SourceLocation FirstOpLoc;
3298   if (LHS.isUsable()) {
3299     Kind = Tok.getKind();
3300     assert(isFoldOperator(Kind) && "missing fold-operator");
3301     FirstOpLoc = ConsumeToken();
3302   }
3303 
3304   assert(Tok.is(tok::ellipsis) && "not a fold-expression");
3305   SourceLocation EllipsisLoc = ConsumeToken();
3306 
3307   ExprResult RHS;
3308   if (Tok.isNot(tok::r_paren)) {
3309     if (!isFoldOperator(Tok.getKind()))
3310       return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
3311 
3312     if (Kind != tok::unknown && Tok.getKind() != Kind)
3313       Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
3314         << SourceRange(FirstOpLoc);
3315     Kind = Tok.getKind();
3316     ConsumeToken();
3317 
3318     RHS = ParseExpression();
3319     if (RHS.isInvalid()) {
3320       T.skipToEnd();
3321       return true;
3322     }
3323   }
3324 
3325   Diag(EllipsisLoc, getLangOpts().CPlusPlus17
3326                         ? diag::warn_cxx14_compat_fold_expression
3327                         : diag::ext_fold_expression);
3328 
3329   T.consumeClose();
3330   return Actions.ActOnCXXFoldExpr(getCurScope(), T.getOpenLocation(), LHS.get(),
3331                                   Kind, EllipsisLoc, RHS.get(),
3332                                   T.getCloseLocation());
3333 }
3334 
3335 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
3336 ///
3337 /// \verbatim
3338 ///       argument-expression-list:
3339 ///         assignment-expression
3340 ///         argument-expression-list , assignment-expression
3341 ///
3342 /// [C++] expression-list:
3343 /// [C++]   assignment-expression
3344 /// [C++]   expression-list , assignment-expression
3345 ///
3346 /// [C++0x] expression-list:
3347 /// [C++0x]   initializer-list
3348 ///
3349 /// [C++0x] initializer-list
3350 /// [C++0x]   initializer-clause ...[opt]
3351 /// [C++0x]   initializer-list , initializer-clause ...[opt]
3352 ///
3353 /// [C++0x] initializer-clause:
3354 /// [C++0x]   assignment-expression
3355 /// [C++0x]   braced-init-list
3356 /// \endverbatim
3357 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
3358                                  SmallVectorImpl<SourceLocation> &CommaLocs,
3359                                  llvm::function_ref<void()> ExpressionStarts) {
3360   bool SawError = false;
3361   while (true) {
3362     if (ExpressionStarts)
3363       ExpressionStarts();
3364 
3365     ExprResult Expr;
3366     if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3367       Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3368       Expr = ParseBraceInitializer();
3369     } else
3370       Expr = ParseAssignmentExpression();
3371 
3372     if (Tok.is(tok::ellipsis))
3373       Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
3374     else if (Tok.is(tok::code_completion)) {
3375       // There's nothing to suggest in here as we parsed a full expression.
3376       // Instead fail and propogate the error since caller might have something
3377       // the suggest, e.g. signature help in function call. Note that this is
3378       // performed before pushing the \p Expr, so that signature help can report
3379       // current argument correctly.
3380       SawError = true;
3381       cutOffParsing();
3382       break;
3383     }
3384     if (Expr.isInvalid()) {
3385       SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
3386       SawError = true;
3387     } else {
3388       Exprs.push_back(Expr.get());
3389     }
3390 
3391     if (Tok.isNot(tok::comma))
3392       break;
3393     // Move to the next argument, remember where the comma was.
3394     Token Comma = Tok;
3395     CommaLocs.push_back(ConsumeToken());
3396 
3397     checkPotentialAngleBracketDelimiter(Comma);
3398   }
3399   if (SawError) {
3400     // Ensure typos get diagnosed when errors were encountered while parsing the
3401     // expression list.
3402     for (auto &E : Exprs) {
3403       ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
3404       if (Expr.isUsable()) E = Expr.get();
3405     }
3406   }
3407   return SawError;
3408 }
3409 
3410 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
3411 /// used for misc language extensions.
3412 ///
3413 /// \verbatim
3414 ///       simple-expression-list:
3415 ///         assignment-expression
3416 ///         simple-expression-list , assignment-expression
3417 /// \endverbatim
3418 bool
3419 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
3420                                   SmallVectorImpl<SourceLocation> &CommaLocs) {
3421   while (true) {
3422     ExprResult Expr = ParseAssignmentExpression();
3423     if (Expr.isInvalid())
3424       return true;
3425 
3426     Exprs.push_back(Expr.get());
3427 
3428     if (Tok.isNot(tok::comma))
3429       return false;
3430 
3431     // Move to the next argument, remember where the comma was.
3432     Token Comma = Tok;
3433     CommaLocs.push_back(ConsumeToken());
3434 
3435     checkPotentialAngleBracketDelimiter(Comma);
3436   }
3437 }
3438 
3439 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
3440 ///
3441 /// \verbatim
3442 /// [clang] block-id:
3443 /// [clang]   specifier-qualifier-list block-declarator
3444 /// \endverbatim
3445 void Parser::ParseBlockId(SourceLocation CaretLoc) {
3446   if (Tok.is(tok::code_completion)) {
3447     cutOffParsing();
3448     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
3449     return;
3450   }
3451 
3452   // Parse the specifier-qualifier-list piece.
3453   DeclSpec DS(AttrFactory);
3454   ParseSpecifierQualifierList(DS);
3455 
3456   // Parse the block-declarator.
3457   Declarator DeclaratorInfo(DS, DeclaratorContext::BlockLiteral);
3458   DeclaratorInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3459   ParseDeclarator(DeclaratorInfo);
3460 
3461   MaybeParseGNUAttributes(DeclaratorInfo);
3462 
3463   // Inform sema that we are starting a block.
3464   Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
3465 }
3466 
3467 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
3468 /// like ^(int x){ return x+1; }
3469 ///
3470 /// \verbatim
3471 ///         block-literal:
3472 /// [clang]   '^' block-args[opt] compound-statement
3473 /// [clang]   '^' block-id compound-statement
3474 /// [clang] block-args:
3475 /// [clang]   '(' parameter-list ')'
3476 /// \endverbatim
3477 ExprResult Parser::ParseBlockLiteralExpression() {
3478   assert(Tok.is(tok::caret) && "block literal starts with ^");
3479   SourceLocation CaretLoc = ConsumeToken();
3480 
3481   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
3482                                 "block literal parsing");
3483 
3484   // Enter a scope to hold everything within the block.  This includes the
3485   // argument decls, decls within the compound expression, etc.  This also
3486   // allows determining whether a variable reference inside the block is
3487   // within or outside of the block.
3488   ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
3489                                   Scope::CompoundStmtScope | Scope::DeclScope);
3490 
3491   // Inform sema that we are starting a block.
3492   Actions.ActOnBlockStart(CaretLoc, getCurScope());
3493 
3494   // Parse the return type if present.
3495   DeclSpec DS(AttrFactory);
3496   Declarator ParamInfo(DS, DeclaratorContext::BlockLiteral);
3497   ParamInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3498   // FIXME: Since the return type isn't actually parsed, it can't be used to
3499   // fill ParamInfo with an initial valid range, so do it manually.
3500   ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
3501 
3502   // If this block has arguments, parse them.  There is no ambiguity here with
3503   // the expression case, because the expression case requires a parameter list.
3504   if (Tok.is(tok::l_paren)) {
3505     ParseParenDeclarator(ParamInfo);
3506     // Parse the pieces after the identifier as if we had "int(...)".
3507     // SetIdentifier sets the source range end, but in this case we're past
3508     // that location.
3509     SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
3510     ParamInfo.SetIdentifier(nullptr, CaretLoc);
3511     ParamInfo.SetRangeEnd(Tmp);
3512     if (ParamInfo.isInvalidType()) {
3513       // If there was an error parsing the arguments, they may have
3514       // tried to use ^(x+y) which requires an argument list.  Just
3515       // skip the whole block literal.
3516       Actions.ActOnBlockError(CaretLoc, getCurScope());
3517       return ExprError();
3518     }
3519 
3520     MaybeParseGNUAttributes(ParamInfo);
3521 
3522     // Inform sema that we are starting a block.
3523     Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3524   } else if (!Tok.is(tok::l_brace)) {
3525     ParseBlockId(CaretLoc);
3526   } else {
3527     // Otherwise, pretend we saw (void).
3528     SourceLocation NoLoc;
3529     ParamInfo.AddTypeInfo(
3530         DeclaratorChunk::getFunction(/*HasProto=*/true,
3531                                      /*IsAmbiguous=*/false,
3532                                      /*RParenLoc=*/NoLoc,
3533                                      /*ArgInfo=*/nullptr,
3534                                      /*NumParams=*/0,
3535                                      /*EllipsisLoc=*/NoLoc,
3536                                      /*RParenLoc=*/NoLoc,
3537                                      /*RefQualifierIsLvalueRef=*/true,
3538                                      /*RefQualifierLoc=*/NoLoc,
3539                                      /*MutableLoc=*/NoLoc, EST_None,
3540                                      /*ESpecRange=*/SourceRange(),
3541                                      /*Exceptions=*/nullptr,
3542                                      /*ExceptionRanges=*/nullptr,
3543                                      /*NumExceptions=*/0,
3544                                      /*NoexceptExpr=*/nullptr,
3545                                      /*ExceptionSpecTokens=*/nullptr,
3546                                      /*DeclsInPrototype=*/None, CaretLoc,
3547                                      CaretLoc, ParamInfo),
3548         CaretLoc);
3549 
3550     MaybeParseGNUAttributes(ParamInfo);
3551 
3552     // Inform sema that we are starting a block.
3553     Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3554   }
3555 
3556 
3557   ExprResult Result(true);
3558   if (!Tok.is(tok::l_brace)) {
3559     // Saw something like: ^expr
3560     Diag(Tok, diag::err_expected_expression);
3561     Actions.ActOnBlockError(CaretLoc, getCurScope());
3562     return ExprError();
3563   }
3564 
3565   StmtResult Stmt(ParseCompoundStatementBody());
3566   BlockScope.Exit();
3567   if (!Stmt.isInvalid())
3568     Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3569   else
3570     Actions.ActOnBlockError(CaretLoc, getCurScope());
3571   return Result;
3572 }
3573 
3574 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3575 ///
3576 ///         '__objc_yes'
3577 ///         '__objc_no'
3578 ExprResult Parser::ParseObjCBoolLiteral() {
3579   tok::TokenKind Kind = Tok.getKind();
3580   return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3581 }
3582 
3583 /// Validate availability spec list, emitting diagnostics if necessary. Returns
3584 /// true if invalid.
3585 static bool CheckAvailabilitySpecList(Parser &P,
3586                                       ArrayRef<AvailabilitySpec> AvailSpecs) {
3587   llvm::SmallSet<StringRef, 4> Platforms;
3588   bool HasOtherPlatformSpec = false;
3589   bool Valid = true;
3590   for (const auto &Spec : AvailSpecs) {
3591     if (Spec.isOtherPlatformSpec()) {
3592       if (HasOtherPlatformSpec) {
3593         P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3594         Valid = false;
3595       }
3596 
3597       HasOtherPlatformSpec = true;
3598       continue;
3599     }
3600 
3601     bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3602     if (!Inserted) {
3603       // Rule out multiple version specs referring to the same platform.
3604       // For example, we emit an error for:
3605       // @available(macos 10.10, macos 10.11, *)
3606       StringRef Platform = Spec.getPlatform();
3607       P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3608           << Spec.getEndLoc() << Platform;
3609       Valid = false;
3610     }
3611   }
3612 
3613   if (!HasOtherPlatformSpec) {
3614     SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3615     P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3616         << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3617     return true;
3618   }
3619 
3620   return !Valid;
3621 }
3622 
3623 /// Parse availability query specification.
3624 ///
3625 ///  availability-spec:
3626 ///     '*'
3627 ///     identifier version-tuple
3628 Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3629   if (Tok.is(tok::star)) {
3630     return AvailabilitySpec(ConsumeToken());
3631   } else {
3632     // Parse the platform name.
3633     if (Tok.is(tok::code_completion)) {
3634       cutOffParsing();
3635       Actions.CodeCompleteAvailabilityPlatformName();
3636       return None;
3637     }
3638     if (Tok.isNot(tok::identifier)) {
3639       Diag(Tok, diag::err_avail_query_expected_platform_name);
3640       return None;
3641     }
3642 
3643     IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3644     SourceRange VersionRange;
3645     VersionTuple Version = ParseVersionTuple(VersionRange);
3646 
3647     if (Version.empty())
3648       return None;
3649 
3650     StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3651     StringRef Platform =
3652         AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3653 
3654     if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3655       Diag(PlatformIdentifier->Loc,
3656            diag::err_avail_query_unrecognized_platform_name)
3657           << GivenPlatform;
3658       return None;
3659     }
3660 
3661     return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3662                             VersionRange.getEnd());
3663   }
3664 }
3665 
3666 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3667   assert(Tok.is(tok::kw___builtin_available) ||
3668          Tok.isObjCAtKeyword(tok::objc_available));
3669 
3670   // Eat the available or __builtin_available.
3671   ConsumeToken();
3672 
3673   BalancedDelimiterTracker Parens(*this, tok::l_paren);
3674   if (Parens.expectAndConsume())
3675     return ExprError();
3676 
3677   SmallVector<AvailabilitySpec, 4> AvailSpecs;
3678   bool HasError = false;
3679   while (true) {
3680     Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3681     if (!Spec)
3682       HasError = true;
3683     else
3684       AvailSpecs.push_back(*Spec);
3685 
3686     if (!TryConsumeToken(tok::comma))
3687       break;
3688   }
3689 
3690   if (HasError) {
3691     SkipUntil(tok::r_paren, StopAtSemi);
3692     return ExprError();
3693   }
3694 
3695   CheckAvailabilitySpecList(*this, AvailSpecs);
3696 
3697   if (Parens.consumeClose())
3698     return ExprError();
3699 
3700   return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3701                                                 Parens.getCloseLocation());
3702 }
3703