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