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