ParseExpr.cpp revision 20df9b7ab9388b2a488c5b1293cd196b1e073b4e
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/Parse/DeclSpec.h"
24#include "clang/Parse/Scope.h"
25#include "ExtensionRAIIObject.h"
26#include "AstGuard.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/SmallString.h"
29using namespace clang;
30
31/// PrecedenceLevels - These are precedences for the binary/ternary operators in
32/// the C99 grammar.  These have been named to relate with the C99 grammar
33/// productions.  Low precedences numbers bind more weakly than high numbers.
34namespace prec {
35  enum Level {
36    Unknown        = 0,    // Not binary operator.
37    Comma          = 1,    // ,
38    Assignment     = 2,    // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
39    Conditional    = 3,    // ?
40    LogicalOr      = 4,    // ||
41    LogicalAnd     = 5,    // &&
42    InclusiveOr    = 6,    // |
43    ExclusiveOr    = 7,    // ^
44    And            = 8,    // &
45    Equality       = 9,    // ==, !=
46    Relational     = 10,   //  >=, <=, >, <
47    Shift          = 11,   // <<, >>
48    Additive       = 12,   // -, +
49    Multiplicative = 13    // *, /, %
50  };
51}
52
53
54/// getBinOpPrecedence - Return the precedence of the specified binary operator
55/// token.  This returns:
56///
57static prec::Level getBinOpPrecedence(tok::TokenKind Kind) {
58  switch (Kind) {
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:
83  case tok::greater:              return prec::Relational;
84  case tok::lessless:
85  case tok::greatergreater:       return prec::Shift;
86  case tok::plus:
87  case tok::minus:                return prec::Additive;
88  case tok::percent:
89  case tok::slash:
90  case tok::star:                 return prec::Multiplicative;
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///       multiplicative-expression: [C99 6.5.5]
108///         cast-expression
109///         multiplicative-expression '*' cast-expression
110///         multiplicative-expression '/' cast-expression
111///         multiplicative-expression '%' cast-expression
112///
113///       additive-expression: [C99 6.5.6]
114///         multiplicative-expression
115///         additive-expression '+' multiplicative-expression
116///         additive-expression '-' multiplicative-expression
117///
118///       shift-expression: [C99 6.5.7]
119///         additive-expression
120///         shift-expression '<<' additive-expression
121///         shift-expression '>>' additive-expression
122///
123///       relational-expression: [C99 6.5.8]
124///         shift-expression
125///         relational-expression '<' shift-expression
126///         relational-expression '>' shift-expression
127///         relational-expression '<=' shift-expression
128///         relational-expression '>=' shift-expression
129///
130///       equality-expression: [C99 6.5.9]
131///         relational-expression
132///         equality-expression '==' relational-expression
133///         equality-expression '!=' relational-expression
134///
135///       AND-expression: [C99 6.5.10]
136///         equality-expression
137///         AND-expression '&' equality-expression
138///
139///       exclusive-OR-expression: [C99 6.5.11]
140///         AND-expression
141///         exclusive-OR-expression '^' AND-expression
142///
143///       inclusive-OR-expression: [C99 6.5.12]
144///         exclusive-OR-expression
145///         inclusive-OR-expression '|' exclusive-OR-expression
146///
147///       logical-AND-expression: [C99 6.5.13]
148///         inclusive-OR-expression
149///         logical-AND-expression '&&' inclusive-OR-expression
150///
151///       logical-OR-expression: [C99 6.5.14]
152///         logical-AND-expression
153///         logical-OR-expression '||' logical-AND-expression
154///
155///       conditional-expression: [C99 6.5.15]
156///         logical-OR-expression
157///         logical-OR-expression '?' expression ':' conditional-expression
158/// [GNU]   logical-OR-expression '?' ':' conditional-expression
159///
160///       assignment-expression: [C99 6.5.16]
161///         conditional-expression
162///         unary-expression assignment-operator assignment-expression
163/// [C++]   throw-expression [C++ 15]
164///
165///       assignment-operator: one of
166///         = *= /= %= += -= <<= >>= &= ^= |=
167///
168///       expression: [C99 6.5.17]
169///         assignment-expression
170///         expression ',' assignment-expression
171///
172Parser::OwningExprResult Parser::ParseExpression() {
173  if (Tok.is(tok::kw_throw))
174    return ParseThrowExpression();
175
176  OwningExprResult LHS(ParseCastExpression(false));
177  if (LHS.isInvalid()) return move(LHS);
178
179  return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
180}
181
182/// This routine is called when the '@' is seen and consumed.
183/// Current token is an Identifier and is not a 'try'. This
184/// routine is necessary to disambiguate @try-statement from,
185/// for example, @encode-expression.
186///
187Parser::OwningExprResult
188Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
189  OwningExprResult LHS(Actions, ParseObjCAtExpression(AtLoc));
190  if (LHS.isInvalid()) return move(LHS);
191
192  return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
193}
194
195/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
196///
197Parser::OwningExprResult Parser::ParseAssignmentExpression() {
198  if (Tok.is(tok::kw_throw))
199    return ParseThrowExpression();
200
201  OwningExprResult LHS(ParseCastExpression(false));
202  if (LHS.isInvalid()) return move(LHS);
203
204  return ParseRHSOfBinaryExpression(move(LHS), prec::Assignment);
205}
206
207/// ParseAssignmentExprWithObjCMessageExprStart - Parse an assignment expression
208/// where part of an objc message send has already been parsed.  In this case
209/// LBracLoc indicates the location of the '[' of the message send, and either
210/// ReceiverName or ReceiverExpr is non-null indicating the receiver of the
211/// message.
212///
213/// Since this handles full assignment-expression's, it handles postfix
214/// expressions and other binary operators for these expressions as well.
215Parser::ExprResult
216Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
217                                                    SourceLocation NameLoc,
218                                                   IdentifierInfo *ReceiverName,
219                                                    ExprTy *ReceiverExpr) {
220  OwningExprResult R(Actions, ParseObjCMessageExpressionBody(LBracLoc, NameLoc,
221                                                             ReceiverName,
222                                                             ReceiverExpr));
223  if (R.isInvalid()) return R.result();
224  R = ParsePostfixExpressionSuffix(move(R));
225  if (R.isInvalid()) return R.result();
226  return ParseRHSOfBinaryExpression(move(R), prec::Assignment).result();
227}
228
229
230Parser::OwningExprResult Parser::ParseConstantExpression() {
231  OwningExprResult LHS(ParseCastExpression(false));
232  if (LHS.isInvalid()) return move(LHS);
233
234  return ParseRHSOfBinaryExpression(move(LHS), prec::Conditional);
235}
236
237/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
238/// LHS and has a precedence of at least MinPrec.
239Parser::OwningExprResult
240Parser::ParseRHSOfBinaryExpression(OwningExprResult LHS, unsigned MinPrec) {
241  unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind());
242  SourceLocation ColonLoc;
243
244  while (1) {
245    // If this token has a lower precedence than we are allowed to parse (e.g.
246    // because we are called recursively, or because the token is not a binop),
247    // then we are done!
248    if (NextTokPrec < MinPrec)
249      return move(LHS);
250
251    // Consume the operator, saving the operator token for error reporting.
252    Token OpToken = Tok;
253    ConsumeToken();
254
255    // Special case handling for the ternary operator.
256    OwningExprResult TernaryMiddle(Actions, true);
257    if (NextTokPrec == prec::Conditional) {
258      if (Tok.isNot(tok::colon)) {
259        // Handle this production specially:
260        //   logical-OR-expression '?' expression ':' conditional-expression
261        // In particular, the RHS of the '?' is 'expression', not
262        // 'logical-OR-expression' as we might expect.
263        TernaryMiddle = ParseExpression();
264        if (TernaryMiddle.isInvalid())
265          return move(TernaryMiddle);
266      } else {
267        // Special case handling of "X ? Y : Z" where Y is empty:
268        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
269        TernaryMiddle = 0;
270        Diag(Tok, diag::ext_gnu_conditional_expr);
271      }
272
273      if (Tok.isNot(tok::colon)) {
274        Diag(Tok, diag::err_expected_colon);
275        Diag(OpToken, diag::note_matching) << "?";
276        return ExprError();
277      }
278
279      // Eat the colon.
280      ColonLoc = ConsumeToken();
281    }
282
283    // Parse another leaf here for the RHS of the operator.
284    OwningExprResult RHS(ParseCastExpression(false));
285    if (RHS.isInvalid())
286      return move(RHS);
287
288    // Remember the precedence of this operator and get the precedence of the
289    // operator immediately to the right of the RHS.
290    unsigned ThisPrec = NextTokPrec;
291    NextTokPrec = getBinOpPrecedence(Tok.getKind());
292
293    // Assignment and conditional expressions are right-associative.
294    bool isRightAssoc = ThisPrec == prec::Conditional ||
295                        ThisPrec == prec::Assignment;
296
297    // Get the precedence of the operator to the right of the RHS.  If it binds
298    // more tightly with RHS than we do, evaluate it completely first.
299    if (ThisPrec < NextTokPrec ||
300        (ThisPrec == NextTokPrec && isRightAssoc)) {
301      // If this is left-associative, only parse things on the RHS that bind
302      // more tightly than the current operator.  If it is left-associative, it
303      // is okay, to bind exactly as tightly.  For example, compile A=B=C=D as
304      // A=(B=(C=D)), where each paren is a level of recursion here.
305      // The function takes ownership of the RHS.
306      RHS = ParseRHSOfBinaryExpression(move(RHS), ThisPrec + !isRightAssoc);
307      if (RHS.isInvalid())
308        return move(RHS);
309
310      NextTokPrec = getBinOpPrecedence(Tok.getKind());
311    }
312    assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
313
314    if (!LHS.isInvalid()) {
315      // Combine the LHS and RHS into the LHS (e.g. build AST).
316      if (TernaryMiddle.isInvalid())
317        LHS = Actions.ActOnBinOp(CurScope, OpToken.getLocation(),
318                                 OpToken.getKind(), LHS.release(),
319                                 RHS.release());
320      else
321        LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
322                                         LHS.release(), TernaryMiddle.release(),
323                                         RHS.release());
324    }
325  }
326}
327
328/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
329/// true, parse a unary-expression.
330///
331///       cast-expression: [C99 6.5.4]
332///         unary-expression
333///         '(' type-name ')' cast-expression
334///
335///       unary-expression:  [C99 6.5.3]
336///         postfix-expression
337///         '++' unary-expression
338///         '--' unary-expression
339///         unary-operator cast-expression
340///         'sizeof' unary-expression
341///         'sizeof' '(' type-name ')'
342/// [GNU]   '__alignof' unary-expression
343/// [GNU]   '__alignof' '(' type-name ')'
344/// [C++0x] 'alignof' '(' type-id ')'
345/// [GNU]   '&&' identifier
346/// [C++]   new-expression
347/// [C++]   delete-expression
348///
349///       unary-operator: one of
350///         '&'  '*'  '+'  '-'  '~'  '!'
351/// [GNU]   '__extension__'  '__real'  '__imag'
352///
353///       primary-expression: [C99 6.5.1]
354/// [C99]   identifier
355/// [C++]   id-expression
356///         constant
357///         string-literal
358/// [C++]   boolean-literal  [C++ 2.13.5]
359///         '(' expression ')'
360///         '__func__'        [C99 6.4.2.2]
361/// [GNU]   '__FUNCTION__'
362/// [GNU]   '__PRETTY_FUNCTION__'
363/// [GNU]   '(' compound-statement ')'
364/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
365/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
366/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
367///                                     assign-expr ')'
368/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
369/// [GNU]   '__null'
370/// [OBJC]  '[' objc-message-expr ']'
371/// [OBJC]  '@selector' '(' objc-selector-arg ')'
372/// [OBJC]  '@protocol' '(' identifier ')'
373/// [OBJC]  '@encode' '(' type-name ')'
374/// [OBJC]  objc-string-literal
375/// [C++]   simple-type-specifier '(' expression-list[opt] ')'      [C++ 5.2.3]
376/// [C++]   typename-specifier '(' expression-list[opt] ')'         [TODO]
377/// [C++]   'const_cast' '<' type-name '>' '(' expression ')'       [C++ 5.2p1]
378/// [C++]   'dynamic_cast' '<' type-name '>' '(' expression ')'     [C++ 5.2p1]
379/// [C++]   'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
380/// [C++]   'static_cast' '<' type-name '>' '(' expression ')'      [C++ 5.2p1]
381/// [C++]   'typeid' '(' expression ')'                             [C++ 5.2p1]
382/// [C++]   'typeid' '(' type-id ')'                                [C++ 5.2p1]
383/// [C++]   'this'          [C++ 9.3.2]
384/// [clang] '^' block-literal
385///
386///       constant: [C99 6.4.4]
387///         integer-constant
388///         floating-constant
389///         enumeration-constant -> identifier
390///         character-constant
391///
392///       id-expression: [C++ 5.1]
393///                   unqualified-id
394///                   qualified-id           [TODO]
395///
396///       unqualified-id: [C++ 5.1]
397///                   identifier
398///                   operator-function-id
399///                   conversion-function-id [TODO]
400///                   '~' class-name         [TODO]
401///                   template-id            [TODO]
402///
403///       new-expression: [C++ 5.3.4]
404///                   '::'[opt] 'new' new-placement[opt] new-type-id
405///                                     new-initializer[opt]
406///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
407///                                     new-initializer[opt]
408///
409///       delete-expression: [C++ 5.3.5]
410///                   '::'[opt] 'delete' cast-expression
411///                   '::'[opt] 'delete' '[' ']' cast-expression
412///
413Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
414  if (getLang().CPlusPlus) {
415    // Annotate typenames and C++ scope specifiers.
416    // Used only in C++, where the typename can be considered as a functional
417    // style cast ("int(1)").
418    // In C we don't expect identifiers to be treated as typenames; if it's a
419    // typedef name, let it be handled as an identifier and
420    // Actions.ActOnIdentifierExpr will emit the proper diagnostic.
421    TryAnnotateTypeOrScopeToken();
422  }
423
424  OwningExprResult Res(Actions);
425  tok::TokenKind SavedKind = Tok.getKind();
426
427  // This handles all of cast-expression, unary-expression, postfix-expression,
428  // and primary-expression.  We handle them together like this for efficiency
429  // and to simplify handling of an expression starting with a '(' token: which
430  // may be one of a parenthesized expression, cast-expression, compound literal
431  // expression, or statement expression.
432  //
433  // If the parsed tokens consist of a primary-expression, the cases below
434  // call ParsePostfixExpressionSuffix to handle the postfix expression
435  // suffixes.  Cases that cannot be followed by postfix exprs should
436  // return without invoking ParsePostfixExpressionSuffix.
437  switch (SavedKind) {
438  case tok::l_paren: {
439    // If this expression is limited to being a unary-expression, the parent can
440    // not start a cast expression.
441    ParenParseOption ParenExprType =
442      isUnaryExpression ? CompoundLiteral : CastExpr;
443    TypeTy *CastTy;
444    SourceLocation LParenLoc = Tok.getLocation();
445    SourceLocation RParenLoc;
446    Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
447    if (Res.isInvalid()) return move(Res);
448
449    switch (ParenExprType) {
450    case SimpleExpr:   break;    // Nothing else to do.
451    case CompoundStmt: break;  // Nothing else to do.
452    case CompoundLiteral:
453      // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
454      // postfix-expression exist, parse them now.
455      break;
456    case CastExpr:
457      // We parsed '(' type-name ')' and the thing after it wasn't a '{'.  Parse
458      // the cast-expression that follows it next.
459      // TODO: For cast expression with CastTy.
460      Res = ParseCastExpression(false);
461      if (!Res.isInvalid())
462        Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc,
463                                    Res.release());
464      return move(Res);
465    }
466
467    // These can be followed by postfix-expr pieces.
468    return ParsePostfixExpressionSuffix(move(Res));
469  }
470
471    // primary-expression
472  case tok::numeric_constant:
473    // constant: integer-constant
474    // constant: floating-constant
475
476    Res = Actions.ActOnNumericConstant(Tok);
477    ConsumeToken();
478
479    // These can be followed by postfix-expr pieces.
480    return ParsePostfixExpressionSuffix(move(Res));
481
482  case tok::kw_true:
483  case tok::kw_false:
484    return ParseCXXBoolLiteral();
485
486  case tok::identifier: {      // primary-expression: identifier
487                               // unqualified-id: identifier
488                               // constant: enumeration-constant
489
490    // Consume the identifier so that we can see if it is followed by a '('.
491    // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
492    // need to know whether or not this identifier is a function designator or
493    // not.
494    IdentifierInfo &II = *Tok.getIdentifierInfo();
495    SourceLocation L = ConsumeToken();
496    Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
497    // These can be followed by postfix-expr pieces.
498    return ParsePostfixExpressionSuffix(move(Res));
499  }
500  case tok::char_constant:     // constant: character-constant
501    Res = Actions.ActOnCharacterConstant(Tok);
502    ConsumeToken();
503    // These can be followed by postfix-expr pieces.
504    return ParsePostfixExpressionSuffix(move(Res));
505  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
506  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
507  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
508    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
509    ConsumeToken();
510    // These can be followed by postfix-expr pieces.
511    return ParsePostfixExpressionSuffix(move(Res));
512  case tok::string_literal:    // primary-expression: string-literal
513  case tok::wide_string_literal:
514    Res = ParseStringLiteralExpression();
515    if (Res.isInvalid()) return move(Res);
516    // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
517    return ParsePostfixExpressionSuffix(move(Res));
518  case tok::kw___builtin_va_arg:
519  case tok::kw___builtin_offsetof:
520  case tok::kw___builtin_choose_expr:
521  case tok::kw___builtin_overload:
522  case tok::kw___builtin_types_compatible_p:
523    return ParseBuiltinPrimaryExpression();
524  case tok::kw___null:
525    return Owned(Actions.ActOnGNUNullExpr(ConsumeToken()));
526    break;
527  case tok::plusplus:      // unary-expression: '++' unary-expression
528  case tok::minusminus: {  // unary-expression: '--' unary-expression
529    SourceLocation SavedLoc = ConsumeToken();
530    Res = ParseCastExpression(true);
531    if (!Res.isInvalid())
532      Res = Owned(Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind,
533                                       Res.release()));
534    return move(Res);
535  }
536  case tok::amp:           // unary-expression: '&' cast-expression
537  case tok::star:          // unary-expression: '*' cast-expression
538  case tok::plus:          // unary-expression: '+' cast-expression
539  case tok::minus:         // unary-expression: '-' cast-expression
540  case tok::tilde:         // unary-expression: '~' cast-expression
541  case tok::exclaim:       // unary-expression: '!' cast-expression
542  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
543  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
544    SourceLocation SavedLoc = ConsumeToken();
545    Res = ParseCastExpression(false);
546    if (!Res.isInvalid())
547      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.release());
548    return move(Res);
549  }
550
551  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
552    // __extension__ silences extension warnings in the subexpression.
553    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
554    SourceLocation SavedLoc = ConsumeToken();
555    Res = ParseCastExpression(false);
556    if (!Res.isInvalid())
557      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.release());
558    return move(Res);
559  }
560  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
561                           // unary-expression: 'sizeof' '(' type-name ')'
562  case tok::kw_alignof:
563  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
564                           // unary-expression: '__alignof' '(' type-name ')'
565                           // unary-expression: 'alignof' '(' type-id ')'
566    return ParseSizeofAlignofExpression();
567  case tok::ampamp: {      // unary-expression: '&&' identifier
568    SourceLocation AmpAmpLoc = ConsumeToken();
569    if (Tok.isNot(tok::identifier))
570      return ExprError(Diag(Tok, diag::err_expected_ident));
571
572    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
573    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
574                                 Tok.getIdentifierInfo());
575    ConsumeToken();
576    return move(Res);
577  }
578  case tok::kw_const_cast:
579  case tok::kw_dynamic_cast:
580  case tok::kw_reinterpret_cast:
581  case tok::kw_static_cast:
582    Res = ParseCXXCasts();
583    // These can be followed by postfix-expr pieces.
584    return ParsePostfixExpressionSuffix(move(Res));
585  case tok::kw_typeid:
586    Res = ParseCXXTypeid();
587    // This can be followed by postfix-expr pieces.
588    return ParsePostfixExpressionSuffix(move(Res));
589  case tok::kw_this:
590    Res = ParseCXXThis();
591    // This can be followed by postfix-expr pieces.
592    return ParsePostfixExpressionSuffix(move(Res));
593
594  case tok::kw_char:
595  case tok::kw_wchar_t:
596  case tok::kw_bool:
597  case tok::kw_short:
598  case tok::kw_int:
599  case tok::kw_long:
600  case tok::kw_signed:
601  case tok::kw_unsigned:
602  case tok::kw_float:
603  case tok::kw_double:
604  case tok::kw_void:
605  case tok::kw_typeof: {
606    if (!getLang().CPlusPlus)
607      goto UnhandledToken;
608  case tok::annot_qualtypename:
609    assert(getLang().CPlusPlus && "Expected C++");
610    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
611    //
612    DeclSpec DS;
613    ParseCXXSimpleTypeSpecifier(DS);
614    if (Tok.isNot(tok::l_paren))
615      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
616                         << DS.getSourceRange());
617
618    Res = ParseCXXTypeConstructExpression(DS);
619    // This can be followed by postfix-expr pieces.
620    return ParsePostfixExpressionSuffix(move(Res));
621  }
622
623  case tok::annot_cxxscope: // [C++] id-expression: qualified-id
624  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
625                         //                      template-id
626    Res = ParseCXXIdExpression();
627    return ParsePostfixExpressionSuffix(move(Res));
628
629  case tok::coloncolon: // [C++] new-expression or [C++] delete-expression
630    // If the next token is neither 'new' nor 'delete', the :: would have been
631    // parsed as a scope specifier already.
632    if (NextToken().is(tok::kw_new))
633      return ParseCXXNewExpression();
634    else
635      return ParseCXXDeleteExpression();
636
637  case tok::kw_new: // [C++] new-expression
638    return ParseCXXNewExpression();
639
640  case tok::kw_delete: // [C++] delete-expression
641    return ParseCXXDeleteExpression();
642
643  case tok::at: {
644    SourceLocation AtLoc = ConsumeToken();
645    return Owned(ParseObjCAtExpression(AtLoc));
646  }
647  case tok::l_square:
648    // These can be followed by postfix-expr pieces.
649    if (getLang().ObjC1)
650      return ParsePostfixExpressionSuffix(Owned(ParseObjCMessageExpression()));
651    // FALL THROUGH.
652  case tok::caret:
653    if (getLang().Blocks)
654      return ParsePostfixExpressionSuffix(Owned(ParseBlockLiteralExpression()));
655    Diag(Tok, diag::err_expected_expression);
656    return ExprError();
657  default:
658  UnhandledToken:
659    Diag(Tok, diag::err_expected_expression);
660    return ExprError();
661  }
662
663  // unreachable.
664  abort();
665}
666
667/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
668/// is parsed, this method parses any suffixes that apply.
669///
670///       postfix-expression: [C99 6.5.2]
671///         primary-expression
672///         postfix-expression '[' expression ']'
673///         postfix-expression '(' argument-expression-list[opt] ')'
674///         postfix-expression '.' identifier
675///         postfix-expression '->' identifier
676///         postfix-expression '++'
677///         postfix-expression '--'
678///         '(' type-name ')' '{' initializer-list '}'
679///         '(' type-name ')' '{' initializer-list ',' '}'
680///
681///       argument-expression-list: [C99 6.5.2]
682///         argument-expression
683///         argument-expression-list ',' assignment-expression
684///
685Parser::OwningExprResult
686Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) {
687  // Now that the primary-expression piece of the postfix-expression has been
688  // parsed, see if there are any postfix-expression pieces here.
689  SourceLocation Loc;
690  while (1) {
691    switch (Tok.getKind()) {
692    default:  // Not a postfix-expression suffix.
693      return move(LHS);
694    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
695      Loc = ConsumeBracket();
696      OwningExprResult Idx(ParseExpression());
697
698      SourceLocation RLoc = Tok.getLocation();
699
700      if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
701        LHS = Actions.ActOnArraySubscriptExpr(CurScope, LHS.release(), Loc,
702                                              Idx.release(), RLoc);
703      } else
704        LHS = ExprError();
705
706      // Match the ']'.
707      MatchRHSPunctuation(tok::r_square, Loc);
708      break;
709    }
710
711    case tok::l_paren: {   // p-e: p-e '(' argument-expression-list[opt] ')'
712      ExprVector ArgExprs(Actions);
713      CommaLocsTy CommaLocs;
714
715      Loc = ConsumeParen();
716
717      if (Tok.isNot(tok::r_paren)) {
718        if (ParseExpressionList(ArgExprs, CommaLocs)) {
719          SkipUntil(tok::r_paren);
720          return ExprError();
721        }
722      }
723
724      // Match the ')'.
725      if (!LHS.isInvalid() && Tok.is(tok::r_paren)) {
726        assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
727               "Unexpected number of commas!");
728        LHS = Actions.ActOnCallExpr(CurScope, LHS.release(), Loc,
729                                    ArgExprs.take(),
730                                    ArgExprs.size(), &CommaLocs[0],
731                                    Tok.getLocation());
732      }
733
734      MatchRHSPunctuation(tok::r_paren, Loc);
735      break;
736    }
737    case tok::arrow:       // postfix-expression: p-e '->' identifier
738    case tok::period: {    // postfix-expression: p-e '.' identifier
739      tok::TokenKind OpKind = Tok.getKind();
740      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
741
742      if (Tok.isNot(tok::identifier)) {
743        Diag(Tok, diag::err_expected_ident);
744        return ExprError();
745      }
746
747      if (!LHS.isInvalid()) {
748        LHS = Actions.ActOnMemberReferenceExpr(LHS.release(), OpLoc, OpKind,
749                                               Tok.getLocation(),
750                                               *Tok.getIdentifierInfo());
751      }
752      ConsumeToken();
753      break;
754    }
755    case tok::plusplus:    // postfix-expression: postfix-expression '++'
756    case tok::minusminus:  // postfix-expression: postfix-expression '--'
757      if (!LHS.isInvalid()) {
758        LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(),
759                                          Tok.getKind(), LHS.release());
760      }
761      ConsumeToken();
762      break;
763    }
764  }
765}
766
767
768/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
769///       unary-expression:  [C99 6.5.3]
770///         'sizeof' unary-expression
771///         'sizeof' '(' type-name ')'
772/// [GNU]   '__alignof' unary-expression
773/// [GNU]   '__alignof' '(' type-name ')'
774/// [C++0x] 'alignof' '(' type-id ')'
775Parser::OwningExprResult Parser::ParseSizeofAlignofExpression() {
776  assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
777          || Tok.is(tok::kw_alignof)) &&
778         "Not a sizeof/alignof expression!");
779  Token OpTok = Tok;
780  ConsumeToken();
781
782  // If the operand doesn't start with an '(', it must be an expression.
783  OwningExprResult Operand(Actions);
784  if (Tok.isNot(tok::l_paren)) {
785    Operand = ParseCastExpression(true);
786  } else {
787    // If it starts with a '(', we know that it is either a parenthesized
788    // type-name, or it is a unary-expression that starts with a compound
789    // literal, or starts with a primary-expression that is a parenthesized
790    // expression.
791    ParenParseOption ExprType = CastExpr;
792    TypeTy *CastTy;
793    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
794    Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
795
796    // If ParseParenExpression parsed a '(typename)' sequence only, the this is
797    // sizeof/alignof a type.  Otherwise, it is sizeof/alignof an expression.
798    if (ExprType == CastExpr)
799      return Owned(Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
800                                            OpTok.is(tok::kw_sizeof),
801                                            /*isType=*/true, CastTy,
802                                            SourceRange(LParenLoc, RParenLoc)));
803
804    // If this is a parenthesized expression, it is the start of a
805    // unary-expression, but doesn't include any postfix pieces.  Parse these
806    // now if present.
807    Operand = ParsePostfixExpressionSuffix(move(Operand));
808  }
809
810  // If we get here, the operand to the sizeof/alignof was an expresion.
811  if (!Operand.isInvalid())
812    Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
813                                             OpTok.is(tok::kw_sizeof),
814                                             /*isType=*/false,
815                                             Operand.release(), SourceRange());
816  return move(Operand);
817}
818
819/// ParseBuiltinPrimaryExpression
820///
821///       primary-expression: [C99 6.5.1]
822/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
823/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
824/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
825///                                     assign-expr ')'
826/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
827/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
828///
829/// [GNU] offsetof-member-designator:
830/// [GNU]   identifier
831/// [GNU]   offsetof-member-designator '.' identifier
832/// [GNU]   offsetof-member-designator '[' expression ']'
833///
834Parser::OwningExprResult Parser::ParseBuiltinPrimaryExpression() {
835  OwningExprResult Res(Actions);
836  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
837
838  tok::TokenKind T = Tok.getKind();
839  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
840
841  // All of these start with an open paren.
842  if (Tok.isNot(tok::l_paren))
843    return ExprError(Diag(Tok, diag::err_expected_lparen_after_id)
844                       << BuiltinII);
845
846  SourceLocation LParenLoc = ConsumeParen();
847  // TODO: Build AST.
848
849  switch (T) {
850  default: assert(0 && "Not a builtin primary expression!");
851  case tok::kw___builtin_va_arg: {
852    OwningExprResult Expr(ParseAssignmentExpression());
853    if (Expr.isInvalid()) {
854      SkipUntil(tok::r_paren);
855      return ExprError();
856    }
857
858    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
859      return ExprError();
860
861    TypeTy *Ty = ParseTypeName();
862
863    if (Tok.isNot(tok::r_paren)) {
864      Diag(Tok, diag::err_expected_rparen);
865      return ExprError();
866    }
867    Res = Actions.ActOnVAArg(StartLoc, Expr.release(), Ty, ConsumeParen());
868    break;
869  }
870  case tok::kw___builtin_offsetof: {
871    SourceLocation TypeLoc = Tok.getLocation();
872    TypeTy *Ty = ParseTypeName();
873
874    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
875      return ExprError();
876
877    // We must have at least one identifier here.
878    if (Tok.isNot(tok::identifier)) {
879      Diag(Tok, diag::err_expected_ident);
880      SkipUntil(tok::r_paren);
881      return ExprError();
882    }
883
884    // Keep track of the various subcomponents we see.
885    llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
886
887    Comps.push_back(Action::OffsetOfComponent());
888    Comps.back().isBrackets = false;
889    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
890    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
891
892    // FIXME: This loop leaks the index expressions on error.
893    while (1) {
894      if (Tok.is(tok::period)) {
895        // offsetof-member-designator: offsetof-member-designator '.' identifier
896        Comps.push_back(Action::OffsetOfComponent());
897        Comps.back().isBrackets = false;
898        Comps.back().LocStart = ConsumeToken();
899
900        if (Tok.isNot(tok::identifier)) {
901          Diag(Tok, diag::err_expected_ident);
902          SkipUntil(tok::r_paren);
903          return ExprError();
904        }
905        Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
906        Comps.back().LocEnd = ConsumeToken();
907
908      } else if (Tok.is(tok::l_square)) {
909        // offsetof-member-designator: offsetof-member-design '[' expression ']'
910        Comps.push_back(Action::OffsetOfComponent());
911        Comps.back().isBrackets = true;
912        Comps.back().LocStart = ConsumeBracket();
913        Res = ParseExpression();
914        if (Res.isInvalid()) {
915          SkipUntil(tok::r_paren);
916          return move(Res);
917        }
918        Comps.back().U.E = Res.release();
919
920        Comps.back().LocEnd =
921          MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
922      } else if (Tok.is(tok::r_paren)) {
923        Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
924                                           Comps.size(), ConsumeParen());
925        break;
926      } else {
927        // Error occurred.
928        return ExprError();
929      }
930    }
931    break;
932  }
933  case tok::kw___builtin_choose_expr: {
934    OwningExprResult Cond(ParseAssignmentExpression());
935    if (Cond.isInvalid()) {
936      SkipUntil(tok::r_paren);
937      return move(Cond);
938    }
939    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
940      return ExprError();
941
942    OwningExprResult Expr1(ParseAssignmentExpression());
943    if (Expr1.isInvalid()) {
944      SkipUntil(tok::r_paren);
945      return move(Expr1);
946    }
947    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
948      return ExprError();
949
950    OwningExprResult Expr2(ParseAssignmentExpression());
951    if (Expr2.isInvalid()) {
952      SkipUntil(tok::r_paren);
953      return move(Expr2);
954    }
955    if (Tok.isNot(tok::r_paren)) {
956      Diag(Tok, diag::err_expected_rparen);
957      return ExprError();
958    }
959    Res = Actions.ActOnChooseExpr(StartLoc, Cond.release(), Expr1.release(),
960                                  Expr2.release(), ConsumeParen());
961    break;
962  }
963  case tok::kw___builtin_overload: {
964    ExprVector ArgExprs(Actions);
965    llvm::SmallVector<SourceLocation, 8> CommaLocs;
966
967    // For each iteration through the loop look for assign-expr followed by a
968    // comma.  If there is no comma, break and attempt to match r-paren.
969    if (Tok.isNot(tok::r_paren)) {
970      while (1) {
971        OwningExprResult ArgExpr(ParseAssignmentExpression());
972        if (ArgExpr.isInvalid()) {
973          SkipUntil(tok::r_paren);
974          return ExprError();
975        } else
976          ArgExprs.push_back(ArgExpr.release());
977
978        if (Tok.isNot(tok::comma))
979          break;
980        // Move to the next argument, remember where the comma was.
981        CommaLocs.push_back(ConsumeToken());
982      }
983    }
984
985    // Attempt to consume the r-paren
986    if (Tok.isNot(tok::r_paren)) {
987      Diag(Tok, diag::err_expected_rparen);
988      SkipUntil(tok::r_paren);
989      return ExprError();
990    }
991    Res = Actions.ActOnOverloadExpr(ArgExprs.take(), ArgExprs.size(),
992                                    &CommaLocs[0], StartLoc, ConsumeParen());
993    break;
994  }
995  case tok::kw___builtin_types_compatible_p:
996    TypeTy *Ty1 = ParseTypeName();
997
998    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
999      return ExprError();
1000
1001    TypeTy *Ty2 = ParseTypeName();
1002
1003    if (Tok.isNot(tok::r_paren)) {
1004      Diag(Tok, diag::err_expected_rparen);
1005      return ExprError();
1006    }
1007    Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
1008    break;
1009  }
1010
1011  // These can be followed by postfix-expr pieces because they are
1012  // primary-expressions.
1013  return ParsePostfixExpressionSuffix(move(Res));
1014}
1015
1016/// ParseParenExpression - This parses the unit that starts with a '(' token,
1017/// based on what is allowed by ExprType.  The actual thing parsed is returned
1018/// in ExprType.
1019///
1020///       primary-expression: [C99 6.5.1]
1021///         '(' expression ')'
1022/// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
1023///       postfix-expression: [C99 6.5.2]
1024///         '(' type-name ')' '{' initializer-list '}'
1025///         '(' type-name ')' '{' initializer-list ',' '}'
1026///       cast-expression: [C99 6.5.4]
1027///         '(' type-name ')' cast-expression
1028///
1029Parser::OwningExprResult
1030Parser::ParseParenExpression(ParenParseOption &ExprType,
1031                             TypeTy *&CastTy, SourceLocation &RParenLoc) {
1032  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
1033  SourceLocation OpenLoc = ConsumeParen();
1034  OwningExprResult Result(Actions, true);
1035  CastTy = 0;
1036
1037  if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
1038    Diag(Tok, diag::ext_gnu_statement_expr);
1039    OwningStmtResult Stmt(ParseCompoundStatement(true));
1040    ExprType = CompoundStmt;
1041
1042    // If the substmt parsed correctly, build the AST node.
1043    if (!Stmt.isInvalid() && Tok.is(tok::r_paren))
1044      Result = Actions.ActOnStmtExpr(
1045        OpenLoc, Stmt.release(), Tok.getLocation());
1046
1047  } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) {
1048    // Otherwise, this is a compound literal expression or cast expression.
1049    TypeTy *Ty = ParseTypeName();
1050
1051    // Match the ')'.
1052    if (Tok.is(tok::r_paren))
1053      RParenLoc = ConsumeParen();
1054    else
1055      MatchRHSPunctuation(tok::r_paren, OpenLoc);
1056
1057    if (Tok.is(tok::l_brace)) {
1058      if (!getLang().C99)   // Compound literals don't exist in C90.
1059        Diag(OpenLoc, diag::ext_c99_compound_literal);
1060      Result = ParseInitializer();
1061      ExprType = CompoundLiteral;
1062      if (!Result.isInvalid())
1063        return Owned(Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc,
1064                                                  Result.release()));
1065    } else if (ExprType == CastExpr) {
1066      // Note that this doesn't parse the subsequence cast-expression, it just
1067      // returns the parsed type to the callee.
1068      ExprType = CastExpr;
1069      CastTy = Ty;
1070      return OwningExprResult(Actions);
1071    } else {
1072      Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1073      return ExprError();
1074    }
1075    return move(Result);
1076  } else {
1077    Result = ParseExpression();
1078    ExprType = SimpleExpr;
1079    if (!Result.isInvalid() && Tok.is(tok::r_paren))
1080      Result = Actions.ActOnParenExpr(
1081        OpenLoc, Tok.getLocation(), Result.release());
1082  }
1083
1084  // Match the ')'.
1085  if (Result.isInvalid())
1086    SkipUntil(tok::r_paren);
1087  else {
1088    if (Tok.is(tok::r_paren))
1089      RParenLoc = ConsumeParen();
1090    else
1091      MatchRHSPunctuation(tok::r_paren, OpenLoc);
1092  }
1093
1094  return move(Result);
1095}
1096
1097/// ParseStringLiteralExpression - This handles the various token types that
1098/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1099/// translation phase #6].
1100///
1101///       primary-expression: [C99 6.5.1]
1102///         string-literal
1103Parser::OwningExprResult Parser::ParseStringLiteralExpression() {
1104  assert(isTokenStringLiteral() && "Not a string literal!");
1105
1106  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
1107  // considered to be strings for concatenation purposes.
1108  llvm::SmallVector<Token, 4> StringToks;
1109
1110  do {
1111    StringToks.push_back(Tok);
1112    ConsumeStringToken();
1113  } while (isTokenStringLiteral());
1114
1115  // Pass the set of string tokens, ready for concatenation, to the actions.
1116  return Owned(Actions.ActOnStringLiteral(&StringToks[0], StringToks.size()));
1117}
1118
1119/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1120///
1121///       argument-expression-list:
1122///         assignment-expression
1123///         argument-expression-list , assignment-expression
1124///
1125/// [C++] expression-list:
1126/// [C++]   assignment-expression
1127/// [C++]   expression-list , assignment-expression
1128///
1129bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1130  while (1) {
1131    OwningExprResult Expr(ParseAssignmentExpression());
1132    if (Expr.isInvalid())
1133      return true;
1134
1135    Exprs.push_back(Expr.release());
1136
1137    if (Tok.isNot(tok::comma))
1138      return false;
1139    // Move to the next argument, remember where the comma was.
1140    CommaLocs.push_back(ConsumeToken());
1141  }
1142}
1143
1144/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
1145/// like ^(int x){ return x+1; }
1146///
1147///         block-literal:
1148/// [clang]   '^' block-args[opt] compound-statement
1149/// [clang] block-args:
1150/// [clang]   '(' parameter-list ')'
1151///
1152Parser::ExprResult Parser::ParseBlockLiteralExpression() {
1153  assert(Tok.is(tok::caret) && "block literal starts with ^");
1154  SourceLocation CaretLoc = ConsumeToken();
1155
1156  // Enter a scope to hold everything within the block.  This includes the
1157  // argument decls, decls within the compound expression, etc.  This also
1158  // allows determining whether a variable reference inside the block is
1159  // within or outside of the block.
1160  ParseScope BlockScope(this, Scope::BlockScope|Scope::FnScope|Scope::BreakScope|
1161                              Scope::ContinueScope|Scope::DeclScope);
1162
1163  // Inform sema that we are starting a block.
1164  Actions.ActOnBlockStart(CaretLoc, CurScope);
1165
1166  // Parse the return type if present.
1167  DeclSpec DS;
1168  Declarator ParamInfo(DS, Declarator::PrototypeContext);
1169
1170  // If this block has arguments, parse them.  There is no ambiguity here with
1171  // the expression case, because the expression case requires a parameter list.
1172  if (Tok.is(tok::l_paren)) {
1173    ParseParenDeclarator(ParamInfo);
1174    // Parse the pieces after the identifier as if we had "int(...)".
1175    ParamInfo.SetIdentifier(0, CaretLoc);
1176    if (ParamInfo.getInvalidType()) {
1177      // If there was an error parsing the arguments, they may have tried to use
1178      // ^(x+y) which requires an argument list.  Just skip the whole block
1179      // literal.
1180      return true;
1181    }
1182  } else {
1183    // Otherwise, pretend we saw (void).
1184    ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
1185                                                       0, 0, 0, CaretLoc));
1186  }
1187
1188  // Inform sema that we are starting a block.
1189  Actions.ActOnBlockArguments(ParamInfo);
1190
1191  OwningExprResult Result(Actions, true);
1192  if (Tok.is(tok::l_brace)) {
1193    OwningStmtResult Stmt(ParseCompoundStatementBody());
1194    if (!Stmt.isInvalid()) {
1195      Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.release(), CurScope);
1196    } else {
1197      Actions.ActOnBlockError(CaretLoc, CurScope);
1198    }
1199  }
1200  return Result.result();
1201}
1202
1203