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