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