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