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