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