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