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