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