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