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