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