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