ParseExpr.cpp revision 1df5109f475bcbc528eb1fb9fdb179dcadbb33a6
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 "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/// [C++] the third operand is an assignment-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  OwningExprResult LHS(ParseAssignmentExpression());
204  if (LHS.isInvalid()) return move(LHS);
205
206  return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
207}
208
209/// This routine is called when the '@' is seen and consumed.
210/// Current token is an Identifier and is not a 'try'. This
211/// routine is necessary to disambiguate @try-statement from,
212/// for example, @encode-expression.
213///
214Parser::OwningExprResult
215Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
216  OwningExprResult LHS(ParseObjCAtExpression(AtLoc));
217  if (LHS.isInvalid()) return move(LHS);
218
219  return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
220}
221
222/// This routine is called when a leading '__extension__' is seen and
223/// consumed.  This is necessary because the token gets consumed in the
224/// process of disambiguating between an expression and a declaration.
225Parser::OwningExprResult
226Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
227  OwningExprResult LHS(Actions, true);
228  {
229    // Silence extension warnings in the sub-expression
230    ExtensionRAIIObject O(Diags);
231
232    LHS = ParseCastExpression(false);
233    if (LHS.isInvalid()) return move(LHS);
234  }
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  // C++ [basic.def.odr]p2:
280  //   An expression is potentially evaluated unless it appears where an
281  //   integral constant expression is required (see 5.19) [...].
282  EnterExpressionEvaluationContext Unevaluated(Actions,
283                                               Action::Unevaluated);
284
285  OwningExprResult LHS(ParseCastExpression(false));
286  if (LHS.isInvalid()) return move(LHS);
287
288  return ParseRHSOfBinaryExpression(move(LHS), prec::Conditional);
289}
290
291/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
292/// LHS and has a precedence of at least MinPrec.
293Parser::OwningExprResult
294Parser::ParseRHSOfBinaryExpression(OwningExprResult LHS, unsigned MinPrec) {
295  unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind(),
296                                            GreaterThanIsOperator,
297                                            getLang().CPlusPlus0x);
298  SourceLocation ColonLoc;
299
300  while (1) {
301    // If this token has a lower precedence than we are allowed to parse (e.g.
302    // because we are called recursively, or because the token is not a binop),
303    // then we are done!
304    if (NextTokPrec < MinPrec)
305      return move(LHS);
306
307    // Consume the operator, saving the operator token for error reporting.
308    Token OpToken = Tok;
309    ConsumeToken();
310
311    // Special case handling for the ternary operator.
312    OwningExprResult TernaryMiddle(Actions, true);
313    if (NextTokPrec == prec::Conditional) {
314      if (Tok.isNot(tok::colon)) {
315        // Handle this production specially:
316        //   logical-OR-expression '?' expression ':' conditional-expression
317        // In particular, the RHS of the '?' is 'expression', not
318        // 'logical-OR-expression' as we might expect.
319        TernaryMiddle = ParseExpression();
320        if (TernaryMiddle.isInvalid())
321          return move(TernaryMiddle);
322      } else {
323        // Special case handling of "X ? Y : Z" where Y is empty:
324        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
325        TernaryMiddle = 0;
326        Diag(Tok, diag::ext_gnu_conditional_expr);
327      }
328
329      if (Tok.isNot(tok::colon)) {
330        Diag(Tok, diag::err_expected_colon);
331        Diag(OpToken, diag::note_matching) << "?";
332        return ExprError();
333      }
334
335      // Eat the colon.
336      ColonLoc = ConsumeToken();
337    }
338
339    // Parse another leaf here for the RHS of the operator.
340    // ParseCastExpression works here because all RHS expressions in C have it
341    // as a prefix, at least. However, in C++, an assignment-expression could
342    // be a throw-expression, which is not a valid cast-expression.
343    // Therefore we need some special-casing here.
344    // Also note that the third operand of the conditional operator is
345    // an assignment-expression in C++.
346    OwningExprResult RHS(Actions);
347    if (getLang().CPlusPlus && NextTokPrec <= prec::Conditional)
348      RHS = ParseAssignmentExpression();
349    else
350      RHS = ParseCastExpression(false);
351    if (RHS.isInvalid())
352      return move(RHS);
353
354    // Remember the precedence of this operator and get the precedence of the
355    // operator immediately to the right of the RHS.
356    unsigned ThisPrec = NextTokPrec;
357    NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
358                                     getLang().CPlusPlus0x);
359
360    // Assignment and conditional expressions are right-associative.
361    bool isRightAssoc = ThisPrec == prec::Conditional ||
362                        ThisPrec == prec::Assignment;
363
364    // Get the precedence of the operator to the right of the RHS.  If it binds
365    // more tightly with RHS than we do, evaluate it completely first.
366    if (ThisPrec < NextTokPrec ||
367        (ThisPrec == NextTokPrec && isRightAssoc)) {
368      // If this is left-associative, only parse things on the RHS that bind
369      // more tightly than the current operator.  If it is left-associative, it
370      // is okay, to bind exactly as tightly.  For example, compile A=B=C=D as
371      // A=(B=(C=D)), where each paren is a level of recursion here.
372      // The function takes ownership of the RHS.
373      RHS = ParseRHSOfBinaryExpression(move(RHS), ThisPrec + !isRightAssoc);
374      if (RHS.isInvalid())
375        return move(RHS);
376
377      NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
378                                       getLang().CPlusPlus0x);
379    }
380    assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
381
382    if (!LHS.isInvalid()) {
383      // Combine the LHS and RHS into the LHS (e.g. build AST).
384      if (TernaryMiddle.isInvalid()) {
385        // If we're using '>>' as an operator within a template
386        // argument list (in C++98), suggest the addition of
387        // parentheses so that the code remains well-formed in C++0x.
388        if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
389          SuggestParentheses(OpToken.getLocation(),
390                             diag::warn_cxx0x_right_shift_in_template_arg,
391                         SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
392                                     Actions.getExprRange(RHS.get()).getEnd()));
393
394        LHS = Actions.ActOnBinOp(CurScope, OpToken.getLocation(),
395                                 OpToken.getKind(), move(LHS), move(RHS));
396      } else
397        LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
398                                         move(LHS), move(TernaryMiddle),
399                                         move(RHS));
400    }
401  }
402}
403
404/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
405/// true, parse a unary-expression. isAddressOfOperand exists because an
406/// id-expression that is the operand of address-of gets special treatment
407/// due to member pointers.
408///
409Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression,
410                                                     bool isAddressOfOperand) {
411  bool NotCastExpr;
412  OwningExprResult Res = ParseCastExpression(isUnaryExpression,
413                                             isAddressOfOperand,
414                                             NotCastExpr);
415  if (NotCastExpr)
416    Diag(Tok, diag::err_expected_expression);
417  return move(Res);
418}
419
420/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
421/// true, parse a unary-expression. isAddressOfOperand exists because an
422/// id-expression that is the operand of address-of gets special treatment
423/// due to member pointers. NotCastExpr is set to true if the token is not the
424/// start of a cast-expression, and no diagnostic is emitted in this case.
425///
426///       cast-expression: [C99 6.5.4]
427///         unary-expression
428///         '(' type-name ')' cast-expression
429///
430///       unary-expression:  [C99 6.5.3]
431///         postfix-expression
432///         '++' unary-expression
433///         '--' unary-expression
434///         unary-operator cast-expression
435///         'sizeof' unary-expression
436///         'sizeof' '(' type-name ')'
437/// [GNU]   '__alignof' unary-expression
438/// [GNU]   '__alignof' '(' type-name ')'
439/// [C++0x] 'alignof' '(' type-id ')'
440/// [GNU]   '&&' identifier
441/// [C++]   new-expression
442/// [C++]   delete-expression
443///
444///       unary-operator: one of
445///         '&'  '*'  '+'  '-'  '~'  '!'
446/// [GNU]   '__extension__'  '__real'  '__imag'
447///
448///       primary-expression: [C99 6.5.1]
449/// [C99]   identifier
450/// [C++]   id-expression
451///         constant
452///         string-literal
453/// [C++]   boolean-literal  [C++ 2.13.5]
454/// [C++0x] 'nullptr'        [C++0x 2.14.7]
455///         '(' expression ')'
456///         '__func__'        [C99 6.4.2.2]
457/// [GNU]   '__FUNCTION__'
458/// [GNU]   '__PRETTY_FUNCTION__'
459/// [GNU]   '(' compound-statement ')'
460/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
461/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
462/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
463///                                     assign-expr ')'
464/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
465/// [GNU]   '__null'
466/// [OBJC]  '[' objc-message-expr ']'
467/// [OBJC]  '@selector' '(' objc-selector-arg ')'
468/// [OBJC]  '@protocol' '(' identifier ')'
469/// [OBJC]  '@encode' '(' type-name ')'
470/// [OBJC]  objc-string-literal
471/// [C++]   simple-type-specifier '(' expression-list[opt] ')'      [C++ 5.2.3]
472/// [C++]   typename-specifier '(' expression-list[opt] ')'         [TODO]
473/// [C++]   'const_cast' '<' type-name '>' '(' expression ')'       [C++ 5.2p1]
474/// [C++]   'dynamic_cast' '<' type-name '>' '(' expression ')'     [C++ 5.2p1]
475/// [C++]   'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
476/// [C++]   'static_cast' '<' type-name '>' '(' expression ')'      [C++ 5.2p1]
477/// [C++]   'typeid' '(' expression ')'                             [C++ 5.2p1]
478/// [C++]   'typeid' '(' type-id ')'                                [C++ 5.2p1]
479/// [C++]   'this'          [C++ 9.3.2]
480/// [G++]   unary-type-trait '(' type-id ')'
481/// [G++]   binary-type-trait '(' type-id ',' type-id ')'           [TODO]
482/// [clang] '^' block-literal
483///
484///       constant: [C99 6.4.4]
485///         integer-constant
486///         floating-constant
487///         enumeration-constant -> identifier
488///         character-constant
489///
490///       id-expression: [C++ 5.1]
491///                   unqualified-id
492///                   qualified-id           [TODO]
493///
494///       unqualified-id: [C++ 5.1]
495///                   identifier
496///                   operator-function-id
497///                   conversion-function-id [TODO]
498///                   '~' class-name         [TODO]
499///                   template-id            [TODO]
500///
501///       new-expression: [C++ 5.3.4]
502///                   '::'[opt] 'new' new-placement[opt] new-type-id
503///                                     new-initializer[opt]
504///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
505///                                     new-initializer[opt]
506///
507///       delete-expression: [C++ 5.3.5]
508///                   '::'[opt] 'delete' cast-expression
509///                   '::'[opt] 'delete' '[' ']' cast-expression
510///
511/// [GNU] unary-type-trait:
512///                   '__has_nothrow_assign'                  [TODO]
513///                   '__has_nothrow_copy'                    [TODO]
514///                   '__has_nothrow_constructor'             [TODO]
515///                   '__has_trivial_assign'                  [TODO]
516///                   '__has_trivial_copy'                    [TODO]
517///                   '__has_trivial_constructor'
518///                   '__has_trivial_destructor'
519///                   '__has_virtual_destructor'              [TODO]
520///                   '__is_abstract'                         [TODO]
521///                   '__is_class'
522///                   '__is_empty'                            [TODO]
523///                   '__is_enum'
524///                   '__is_pod'
525///                   '__is_polymorphic'
526///                   '__is_union'
527///
528/// [GNU] binary-type-trait:
529///                   '__is_base_of'                          [TODO]
530///
531Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression,
532                                                     bool isAddressOfOperand,
533                                                     bool &NotCastExpr) {
534  OwningExprResult Res(Actions);
535  tok::TokenKind SavedKind = Tok.getKind();
536  NotCastExpr = false;
537
538  // This handles all of cast-expression, unary-expression, postfix-expression,
539  // and primary-expression.  We handle them together like this for efficiency
540  // and to simplify handling of an expression starting with a '(' token: which
541  // may be one of a parenthesized expression, cast-expression, compound literal
542  // expression, or statement expression.
543  //
544  // If the parsed tokens consist of a primary-expression, the cases below
545  // call ParsePostfixExpressionSuffix to handle the postfix expression
546  // suffixes.  Cases that cannot be followed by postfix exprs should
547  // return without invoking ParsePostfixExpressionSuffix.
548  switch (SavedKind) {
549  case tok::l_paren: {
550    // If this expression is limited to being a unary-expression, the parent can
551    // not start a cast expression.
552    ParenParseOption ParenExprType =
553      isUnaryExpression ? CompoundLiteral : CastExpr;
554    TypeTy *CastTy;
555    SourceLocation LParenLoc = Tok.getLocation();
556    SourceLocation RParenLoc;
557    Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
558                               CastTy, RParenLoc);
559    if (Res.isInvalid()) return move(Res);
560
561    switch (ParenExprType) {
562    case SimpleExpr:   break;    // Nothing else to do.
563    case CompoundStmt: break;  // Nothing else to do.
564    case CompoundLiteral:
565      // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
566      // postfix-expression exist, parse them now.
567      break;
568    case CastExpr:
569      // We have parsed the cast-expression and no postfix-expr pieces are
570      // following.
571      return move(Res);
572    }
573
574    // These can be followed by postfix-expr pieces.
575    return ParsePostfixExpressionSuffix(move(Res));
576  }
577
578    // primary-expression
579  case tok::numeric_constant:
580    // constant: integer-constant
581    // constant: floating-constant
582
583    Res = Actions.ActOnNumericConstant(Tok);
584    ConsumeToken();
585
586    // These can be followed by postfix-expr pieces.
587    return ParsePostfixExpressionSuffix(move(Res));
588
589  case tok::kw_true:
590  case tok::kw_false:
591    return ParseCXXBoolLiteral();
592
593  case tok::kw_nullptr:
594    return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
595
596  case tok::identifier: {      // primary-expression: identifier
597                               // unqualified-id: identifier
598                               // constant: enumeration-constant
599    // Turn a potentially qualified name into a annot_typename or
600    // annot_cxxscope if it would be valid.  This handles things like x::y, etc.
601    if (getLang().CPlusPlus) {
602      // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
603      if (TryAnnotateTypeOrScopeToken())
604        return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
605    }
606
607    // Support 'Class.property' notation.
608    // We don't use isTokObjCMessageIdentifierReceiver(), since it allows
609    // 'super' (which is inappropriate here).
610    if (getLang().ObjC1 &&
611        Actions.getTypeName(*Tok.getIdentifierInfo(),
612                            Tok.getLocation(), CurScope) &&
613        NextToken().is(tok::period)) {
614      IdentifierInfo &ReceiverName = *Tok.getIdentifierInfo();
615      SourceLocation IdentLoc = ConsumeToken();
616      SourceLocation DotLoc = ConsumeToken();
617
618      if (Tok.isNot(tok::identifier)) {
619        Diag(Tok, diag::err_expected_ident);
620        return ExprError();
621      }
622      IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
623      SourceLocation PropertyLoc = ConsumeToken();
624
625      Res = Actions.ActOnClassPropertyRefExpr(ReceiverName, PropertyName,
626                                              IdentLoc, PropertyLoc);
627      // These can be followed by postfix-expr pieces.
628      return ParsePostfixExpressionSuffix(move(Res));
629    }
630    // Consume the identifier so that we can see if it is followed by a '('.
631    // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
632    // need to know whether or not this identifier is a function designator or
633    // not.
634    IdentifierInfo &II = *Tok.getIdentifierInfo();
635    SourceLocation L = ConsumeToken();
636    Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
637    // These can be followed by postfix-expr pieces.
638    return ParsePostfixExpressionSuffix(move(Res));
639  }
640  case tok::char_constant:     // constant: character-constant
641    Res = Actions.ActOnCharacterConstant(Tok);
642    ConsumeToken();
643    // These can be followed by postfix-expr pieces.
644    return ParsePostfixExpressionSuffix(move(Res));
645  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
646  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
647  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
648    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
649    ConsumeToken();
650    // These can be followed by postfix-expr pieces.
651    return ParsePostfixExpressionSuffix(move(Res));
652  case tok::string_literal:    // primary-expression: string-literal
653  case tok::wide_string_literal:
654    Res = ParseStringLiteralExpression();
655    if (Res.isInvalid()) return move(Res);
656    // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
657    return ParsePostfixExpressionSuffix(move(Res));
658  case tok::kw___builtin_va_arg:
659  case tok::kw___builtin_offsetof:
660  case tok::kw___builtin_choose_expr:
661  case tok::kw___builtin_types_compatible_p:
662    return ParseBuiltinPrimaryExpression();
663  case tok::kw___null:
664    return Actions.ActOnGNUNullExpr(ConsumeToken());
665    break;
666  case tok::plusplus:      // unary-expression: '++' unary-expression
667  case tok::minusminus: {  // unary-expression: '--' unary-expression
668    SourceLocation SavedLoc = ConsumeToken();
669    Res = ParseCastExpression(true);
670    if (!Res.isInvalid())
671      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res));
672    return move(Res);
673  }
674  case tok::amp: {         // unary-expression: '&' cast-expression
675    // Special treatment because of member pointers
676    SourceLocation SavedLoc = ConsumeToken();
677    Res = ParseCastExpression(false, true);
678    if (!Res.isInvalid())
679      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res));
680    return move(Res);
681  }
682
683  case tok::star:          // unary-expression: '*' cast-expression
684  case tok::plus:          // unary-expression: '+' cast-expression
685  case tok::minus:         // unary-expression: '-' cast-expression
686  case tok::tilde:         // unary-expression: '~' cast-expression
687  case tok::exclaim:       // unary-expression: '!' cast-expression
688  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
689  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
690    SourceLocation SavedLoc = ConsumeToken();
691    Res = ParseCastExpression(false);
692    if (!Res.isInvalid())
693      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res));
694    return move(Res);
695  }
696
697  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
698    // __extension__ silences extension warnings in the subexpression.
699    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
700    SourceLocation SavedLoc = ConsumeToken();
701    Res = ParseCastExpression(false);
702    if (!Res.isInvalid())
703      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res));
704    return move(Res);
705  }
706  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
707                           // unary-expression: 'sizeof' '(' type-name ')'
708  case tok::kw_alignof:
709  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
710                           // unary-expression: '__alignof' '(' type-name ')'
711                           // unary-expression: 'alignof' '(' type-id ')'
712    return ParseSizeofAlignofExpression();
713  case tok::ampamp: {      // unary-expression: '&&' identifier
714    SourceLocation AmpAmpLoc = ConsumeToken();
715    if (Tok.isNot(tok::identifier))
716      return ExprError(Diag(Tok, diag::err_expected_ident));
717
718    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
719    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
720                                 Tok.getIdentifierInfo());
721    ConsumeToken();
722    return move(Res);
723  }
724  case tok::kw_const_cast:
725  case tok::kw_dynamic_cast:
726  case tok::kw_reinterpret_cast:
727  case tok::kw_static_cast:
728    Res = ParseCXXCasts();
729    // These can be followed by postfix-expr pieces.
730    return ParsePostfixExpressionSuffix(move(Res));
731  case tok::kw_typeid:
732    Res = ParseCXXTypeid();
733    // This can be followed by postfix-expr pieces.
734    return ParsePostfixExpressionSuffix(move(Res));
735  case tok::kw_this:
736    Res = ParseCXXThis();
737    // This can be followed by postfix-expr pieces.
738    return ParsePostfixExpressionSuffix(move(Res));
739
740  case tok::kw_char:
741  case tok::kw_wchar_t:
742  case tok::kw_char16_t:
743  case tok::kw_char32_t:
744  case tok::kw_bool:
745  case tok::kw_short:
746  case tok::kw_int:
747  case tok::kw_long:
748  case tok::kw_signed:
749  case tok::kw_unsigned:
750  case tok::kw_float:
751  case tok::kw_double:
752  case tok::kw_void:
753  case tok::kw_typename:
754  case tok::kw_typeof:
755  case tok::annot_typename: {
756    if (!getLang().CPlusPlus) {
757      Diag(Tok, diag::err_expected_expression);
758      return ExprError();
759    }
760
761    if (SavedKind == tok::kw_typename) {
762      // postfix-expression: typename-specifier '(' expression-list[opt] ')'
763      if (!TryAnnotateTypeOrScopeToken())
764        return ExprError();
765    }
766
767    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
768    //
769    DeclSpec DS;
770    ParseCXXSimpleTypeSpecifier(DS);
771    if (Tok.isNot(tok::l_paren))
772      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
773                         << DS.getSourceRange());
774
775    Res = ParseCXXTypeConstructExpression(DS);
776    // This can be followed by postfix-expr pieces.
777    return ParsePostfixExpressionSuffix(move(Res));
778  }
779
780  case tok::annot_cxxscope: // [C++] id-expression: qualified-id
781  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
782  case tok::annot_template_id: // [C++]          template-id
783    Res = ParseCXXIdExpression(isAddressOfOperand);
784    return ParsePostfixExpressionSuffix(move(Res));
785
786  case tok::coloncolon: {
787    // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
788    // annotates the token, tail recurse.
789    if (TryAnnotateTypeOrScopeToken())
790      return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
791
792    // ::new -> [C++] new-expression
793    // ::delete -> [C++] delete-expression
794    SourceLocation CCLoc = ConsumeToken();
795    if (Tok.is(tok::kw_new))
796      return ParseCXXNewExpression(true, CCLoc);
797    if (Tok.is(tok::kw_delete))
798      return ParseCXXDeleteExpression(true, CCLoc);
799
800    // This is not a type name or scope specifier, it is an invalid expression.
801    Diag(CCLoc, diag::err_expected_expression);
802    return ExprError();
803  }
804
805  case tok::kw_new: // [C++] new-expression
806    return ParseCXXNewExpression(false, Tok.getLocation());
807
808  case tok::kw_delete: // [C++] delete-expression
809    return ParseCXXDeleteExpression(false, Tok.getLocation());
810
811  case tok::kw___is_pod: // [GNU] unary-type-trait
812  case tok::kw___is_class:
813  case tok::kw___is_enum:
814  case tok::kw___is_union:
815  case tok::kw___is_polymorphic:
816  case tok::kw___is_abstract:
817  case tok::kw___has_trivial_constructor:
818  case tok::kw___has_trivial_copy:
819  case tok::kw___has_trivial_assign:
820  case tok::kw___has_trivial_destructor:
821    return ParseUnaryTypeTrait();
822
823  case tok::at: {
824    SourceLocation AtLoc = ConsumeToken();
825    return ParseObjCAtExpression(AtLoc);
826  }
827  case tok::caret:
828    return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
829  case tok::l_square:
830    // These can be followed by postfix-expr pieces.
831    if (getLang().ObjC1)
832      return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
833    // FALL THROUGH.
834  default:
835    NotCastExpr = true;
836    return ExprError();
837  }
838
839  // unreachable.
840  abort();
841}
842
843/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
844/// is parsed, this method parses any suffixes that apply.
845///
846///       postfix-expression: [C99 6.5.2]
847///         primary-expression
848///         postfix-expression '[' expression ']'
849///         postfix-expression '(' argument-expression-list[opt] ')'
850///         postfix-expression '.' identifier
851///         postfix-expression '->' identifier
852///         postfix-expression '++'
853///         postfix-expression '--'
854///         '(' type-name ')' '{' initializer-list '}'
855///         '(' type-name ')' '{' initializer-list ',' '}'
856///
857///       argument-expression-list: [C99 6.5.2]
858///         argument-expression
859///         argument-expression-list ',' assignment-expression
860///
861Parser::OwningExprResult
862Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) {
863  // Now that the primary-expression piece of the postfix-expression has been
864  // parsed, see if there are any postfix-expression pieces here.
865  SourceLocation Loc;
866  while (1) {
867    switch (Tok.getKind()) {
868    default:  // Not a postfix-expression suffix.
869      return move(LHS);
870    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
871      Loc = ConsumeBracket();
872      OwningExprResult Idx(ParseExpression());
873
874      SourceLocation RLoc = Tok.getLocation();
875
876      if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
877        LHS = Actions.ActOnArraySubscriptExpr(CurScope, move(LHS), Loc,
878                                              move(Idx), RLoc);
879      } else
880        LHS = ExprError();
881
882      // Match the ']'.
883      MatchRHSPunctuation(tok::r_square, Loc);
884      break;
885    }
886
887    case tok::l_paren: {   // p-e: p-e '(' argument-expression-list[opt] ')'
888      ExprVector ArgExprs(Actions);
889      CommaLocsTy CommaLocs;
890
891      Loc = ConsumeParen();
892
893      if (Tok.isNot(tok::r_paren)) {
894        if (ParseExpressionList(ArgExprs, CommaLocs)) {
895          SkipUntil(tok::r_paren);
896          return ExprError();
897        }
898      }
899
900      // Match the ')'.
901      if (Tok.isNot(tok::r_paren)) {
902        MatchRHSPunctuation(tok::r_paren, Loc);
903        return ExprError();
904      }
905
906      if (!LHS.isInvalid()) {
907        assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
908               "Unexpected number of commas!");
909        LHS = Actions.ActOnCallExpr(CurScope, move(LHS), Loc,
910                                    move_arg(ArgExprs), CommaLocs.data(),
911                                    Tok.getLocation());
912      }
913
914      ConsumeParen();
915      break;
916    }
917    case tok::arrow:       // postfix-expression: p-e '->' identifier
918    case tok::period: {    // postfix-expression: p-e '.' identifier
919      tok::TokenKind OpKind = Tok.getKind();
920      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
921
922      CXXScopeSpec MemberSS;
923      CXXScopeSpec SS;
924      if (getLang().CPlusPlus && !LHS.isInvalid()) {
925        LHS = Actions.ActOnCXXEnterMemberScope(CurScope, MemberSS, move(LHS),
926                                               OpKind);
927        if (LHS.isInvalid())
928          break;
929        ParseOptionalCXXScopeSpecifier(SS);
930      }
931
932      if (Tok.isNot(tok::identifier)) {
933        Diag(Tok, diag::err_expected_ident);
934        return ExprError();
935      }
936
937      if (!LHS.isInvalid()) {
938        LHS = Actions.ActOnMemberReferenceExpr(CurScope, move(LHS), OpLoc,
939                                               OpKind, Tok.getLocation(),
940                                               *Tok.getIdentifierInfo(),
941                                               ObjCImpDecl, &SS);
942      }
943
944      if (getLang().CPlusPlus)
945        Actions.ActOnCXXExitMemberScope(CurScope, MemberSS);
946
947      ConsumeToken();
948      break;
949    }
950    case tok::plusplus:    // postfix-expression: postfix-expression '++'
951    case tok::minusminus:  // postfix-expression: postfix-expression '--'
952      if (!LHS.isInvalid()) {
953        LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(),
954                                          Tok.getKind(), move(LHS));
955      }
956      ConsumeToken();
957      break;
958    }
959  }
960}
961
962/// ParseExprAfterTypeofSizeofAlignof - We parsed a typeof/sizeof/alignof and
963/// we are at the start of an expression or a parenthesized type-id.
964/// OpTok is the operand token (typeof/sizeof/alignof). Returns the expression
965/// (isCastExpr == false) or the type (isCastExpr == true).
966///
967///       unary-expression:  [C99 6.5.3]
968///         'sizeof' unary-expression
969///         'sizeof' '(' type-name ')'
970/// [GNU]   '__alignof' unary-expression
971/// [GNU]   '__alignof' '(' type-name ')'
972/// [C++0x] 'alignof' '(' type-id ')'
973///
974/// [GNU]   typeof-specifier:
975///           typeof ( expressions )
976///           typeof ( type-name )
977/// [GNU/C++] typeof unary-expression
978///
979Parser::OwningExprResult
980Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok,
981                                          bool &isCastExpr,
982                                          TypeTy *&CastTy,
983                                          SourceRange &CastRange) {
984
985  assert((OpTok.is(tok::kw_typeof)    || OpTok.is(tok::kw_sizeof) ||
986          OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof)) &&
987          "Not a typeof/sizeof/alignof expression!");
988
989  OwningExprResult Operand(Actions);
990
991  // If the operand doesn't start with an '(', it must be an expression.
992  if (Tok.isNot(tok::l_paren)) {
993    isCastExpr = false;
994    if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) {
995      Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo();
996      return ExprError();
997    }
998
999    // C++0x [expr.sizeof]p1:
1000    //   [...] The operand is either an expression, which is an unevaluated
1001    //   operand (Clause 5) [...]
1002    //
1003    // The GNU typeof and alignof extensions also behave as unevaluated
1004    // operands.
1005    EnterExpressionEvaluationContext Unevaluated(Actions,
1006                                                 Action::Unevaluated);
1007    Operand = ParseCastExpression(true/*isUnaryExpression*/);
1008  } else {
1009    // If it starts with a '(', we know that it is either a parenthesized
1010    // type-name, or it is a unary-expression that starts with a compound
1011    // literal, or starts with a primary-expression that is a parenthesized
1012    // expression.
1013    ParenParseOption ExprType = CastExpr;
1014    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1015
1016    // C++0x [expr.sizeof]p1:
1017    //   [...] The operand is either an expression, which is an unevaluated
1018    //   operand (Clause 5) [...]
1019    //
1020    // The GNU typeof and alignof extensions also behave as unevaluated
1021    // operands.
1022    EnterExpressionEvaluationContext Unevaluated(Actions,
1023                                                 Action::Unevaluated);
1024    Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1025                                   CastTy, RParenLoc);
1026    CastRange = SourceRange(LParenLoc, RParenLoc);
1027
1028    // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1029    // a type.
1030    if (ExprType == CastExpr) {
1031      isCastExpr = true;
1032      return ExprEmpty();
1033    }
1034
1035    // If this is a parenthesized expression, it is the start of a
1036    // unary-expression, but doesn't include any postfix pieces.  Parse these
1037    // now if present.
1038    Operand = ParsePostfixExpressionSuffix(move(Operand));
1039  }
1040
1041  // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1042  isCastExpr = false;
1043  return move(Operand);
1044}
1045
1046
1047/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
1048///       unary-expression:  [C99 6.5.3]
1049///         'sizeof' unary-expression
1050///         'sizeof' '(' type-name ')'
1051/// [GNU]   '__alignof' unary-expression
1052/// [GNU]   '__alignof' '(' type-name ')'
1053/// [C++0x] 'alignof' '(' type-id ')'
1054Parser::OwningExprResult Parser::ParseSizeofAlignofExpression() {
1055  assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
1056          || Tok.is(tok::kw_alignof)) &&
1057         "Not a sizeof/alignof expression!");
1058  Token OpTok = Tok;
1059  ConsumeToken();
1060
1061  bool isCastExpr;
1062  TypeTy *CastTy;
1063  SourceRange CastRange;
1064  OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok,
1065                                                               isCastExpr,
1066                                                               CastTy,
1067                                                               CastRange);
1068
1069  if (isCastExpr)
1070    return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
1071                                          OpTok.is(tok::kw_sizeof),
1072                                          /*isType=*/true, CastTy,
1073                                          CastRange);
1074
1075  // If we get here, the operand to the sizeof/alignof was an expresion.
1076  if (!Operand.isInvalid())
1077    Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
1078                                             OpTok.is(tok::kw_sizeof),
1079                                             /*isType=*/false,
1080                                             Operand.release(), CastRange);
1081  return move(Operand);
1082}
1083
1084/// ParseBuiltinPrimaryExpression
1085///
1086///       primary-expression: [C99 6.5.1]
1087/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1088/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1089/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1090///                                     assign-expr ')'
1091/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1092///
1093/// [GNU] offsetof-member-designator:
1094/// [GNU]   identifier
1095/// [GNU]   offsetof-member-designator '.' identifier
1096/// [GNU]   offsetof-member-designator '[' expression ']'
1097///
1098Parser::OwningExprResult Parser::ParseBuiltinPrimaryExpression() {
1099  OwningExprResult Res(Actions);
1100  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1101
1102  tok::TokenKind T = Tok.getKind();
1103  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
1104
1105  // All of these start with an open paren.
1106  if (Tok.isNot(tok::l_paren))
1107    return ExprError(Diag(Tok, diag::err_expected_lparen_after_id)
1108                       << BuiltinII);
1109
1110  SourceLocation LParenLoc = ConsumeParen();
1111  // TODO: Build AST.
1112
1113  switch (T) {
1114  default: assert(0 && "Not a builtin primary expression!");
1115  case tok::kw___builtin_va_arg: {
1116    OwningExprResult Expr(ParseAssignmentExpression());
1117    if (Expr.isInvalid()) {
1118      SkipUntil(tok::r_paren);
1119      return ExprError();
1120    }
1121
1122    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1123      return ExprError();
1124
1125    TypeResult Ty = ParseTypeName();
1126
1127    if (Tok.isNot(tok::r_paren)) {
1128      Diag(Tok, diag::err_expected_rparen);
1129      return ExprError();
1130    }
1131    if (Ty.isInvalid())
1132      Res = ExprError();
1133    else
1134      Res = Actions.ActOnVAArg(StartLoc, move(Expr), Ty.get(), ConsumeParen());
1135    break;
1136  }
1137  case tok::kw___builtin_offsetof: {
1138    SourceLocation TypeLoc = Tok.getLocation();
1139    TypeResult Ty = ParseTypeName();
1140    if (Ty.isInvalid()) {
1141      SkipUntil(tok::r_paren);
1142      return ExprError();
1143    }
1144
1145    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1146      return ExprError();
1147
1148    // We must have at least one identifier here.
1149    if (Tok.isNot(tok::identifier)) {
1150      Diag(Tok, diag::err_expected_ident);
1151      SkipUntil(tok::r_paren);
1152      return ExprError();
1153    }
1154
1155    // Keep track of the various subcomponents we see.
1156    llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
1157
1158    Comps.push_back(Action::OffsetOfComponent());
1159    Comps.back().isBrackets = false;
1160    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1161    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1162
1163    // FIXME: This loop leaks the index expressions on error.
1164    while (1) {
1165      if (Tok.is(tok::period)) {
1166        // offsetof-member-designator: offsetof-member-designator '.' identifier
1167        Comps.push_back(Action::OffsetOfComponent());
1168        Comps.back().isBrackets = false;
1169        Comps.back().LocStart = ConsumeToken();
1170
1171        if (Tok.isNot(tok::identifier)) {
1172          Diag(Tok, diag::err_expected_ident);
1173          SkipUntil(tok::r_paren);
1174          return ExprError();
1175        }
1176        Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1177        Comps.back().LocEnd = ConsumeToken();
1178
1179      } else if (Tok.is(tok::l_square)) {
1180        // offsetof-member-designator: offsetof-member-design '[' expression ']'
1181        Comps.push_back(Action::OffsetOfComponent());
1182        Comps.back().isBrackets = true;
1183        Comps.back().LocStart = ConsumeBracket();
1184        Res = ParseExpression();
1185        if (Res.isInvalid()) {
1186          SkipUntil(tok::r_paren);
1187          return move(Res);
1188        }
1189        Comps.back().U.E = Res.release();
1190
1191        Comps.back().LocEnd =
1192          MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
1193      } else {
1194        if (Tok.isNot(tok::r_paren)) {
1195          MatchRHSPunctuation(tok::r_paren, LParenLoc);
1196          Res = ExprError();
1197        } else if (Ty.isInvalid()) {
1198          Res = ExprError();
1199        } else {
1200          Res = Actions.ActOnBuiltinOffsetOf(CurScope, StartLoc, TypeLoc,
1201                                             Ty.get(), &Comps[0],
1202                                             Comps.size(), ConsumeParen());
1203        }
1204        break;
1205      }
1206    }
1207    break;
1208  }
1209  case tok::kw___builtin_choose_expr: {
1210    OwningExprResult Cond(ParseAssignmentExpression());
1211    if (Cond.isInvalid()) {
1212      SkipUntil(tok::r_paren);
1213      return move(Cond);
1214    }
1215    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1216      return ExprError();
1217
1218    OwningExprResult Expr1(ParseAssignmentExpression());
1219    if (Expr1.isInvalid()) {
1220      SkipUntil(tok::r_paren);
1221      return move(Expr1);
1222    }
1223    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1224      return ExprError();
1225
1226    OwningExprResult Expr2(ParseAssignmentExpression());
1227    if (Expr2.isInvalid()) {
1228      SkipUntil(tok::r_paren);
1229      return move(Expr2);
1230    }
1231    if (Tok.isNot(tok::r_paren)) {
1232      Diag(Tok, diag::err_expected_rparen);
1233      return ExprError();
1234    }
1235    Res = Actions.ActOnChooseExpr(StartLoc, move(Cond), move(Expr1),
1236                                  move(Expr2), ConsumeParen());
1237    break;
1238  }
1239  case tok::kw___builtin_types_compatible_p:
1240    TypeResult Ty1 = ParseTypeName();
1241
1242    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1243      return ExprError();
1244
1245    TypeResult Ty2 = ParseTypeName();
1246
1247    if (Tok.isNot(tok::r_paren)) {
1248      Diag(Tok, diag::err_expected_rparen);
1249      return ExprError();
1250    }
1251
1252    if (Ty1.isInvalid() || Ty2.isInvalid())
1253      Res = ExprError();
1254    else
1255      Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1.get(), Ty2.get(),
1256                                             ConsumeParen());
1257    break;
1258  }
1259
1260  // These can be followed by postfix-expr pieces because they are
1261  // primary-expressions.
1262  return ParsePostfixExpressionSuffix(move(Res));
1263}
1264
1265/// ParseParenExpression - This parses the unit that starts with a '(' token,
1266/// based on what is allowed by ExprType.  The actual thing parsed is returned
1267/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
1268/// not the parsed cast-expression.
1269///
1270///       primary-expression: [C99 6.5.1]
1271///         '(' expression ')'
1272/// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
1273///       postfix-expression: [C99 6.5.2]
1274///         '(' type-name ')' '{' initializer-list '}'
1275///         '(' type-name ')' '{' initializer-list ',' '}'
1276///       cast-expression: [C99 6.5.4]
1277///         '(' type-name ')' cast-expression
1278///
1279Parser::OwningExprResult
1280Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
1281                             TypeTy *&CastTy, SourceLocation &RParenLoc) {
1282  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
1283  GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
1284  SourceLocation OpenLoc = ConsumeParen();
1285  OwningExprResult Result(Actions, true);
1286  bool isAmbiguousTypeId;
1287  CastTy = 0;
1288
1289  if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
1290    Diag(Tok, diag::ext_gnu_statement_expr);
1291    OwningStmtResult Stmt(ParseCompoundStatement(true));
1292    ExprType = CompoundStmt;
1293
1294    // If the substmt parsed correctly, build the AST node.
1295    if (!Stmt.isInvalid() && Tok.is(tok::r_paren))
1296      Result = Actions.ActOnStmtExpr(OpenLoc, move(Stmt), Tok.getLocation());
1297
1298  } else if (ExprType >= CompoundLiteral &&
1299             isTypeIdInParens(isAmbiguousTypeId)) {
1300
1301    // Otherwise, this is a compound literal expression or cast expression.
1302
1303    // In C++, if the type-id is ambiguous we disambiguate based on context.
1304    // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
1305    // in which case we should treat it as type-id.
1306    // if stopIfCastExpr is false, we need to determine the context past the
1307    // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
1308    if (isAmbiguousTypeId && !stopIfCastExpr)
1309      return ParseCXXAmbiguousParenExpression(ExprType, CastTy,
1310                                              OpenLoc, RParenLoc);
1311
1312    TypeResult Ty = ParseTypeName();
1313
1314    // Match the ')'.
1315    if (Tok.is(tok::r_paren))
1316      RParenLoc = ConsumeParen();
1317    else
1318      MatchRHSPunctuation(tok::r_paren, OpenLoc);
1319
1320    if (Tok.is(tok::l_brace)) {
1321      ExprType = CompoundLiteral;
1322      return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
1323    }
1324
1325    if (ExprType == CastExpr) {
1326      // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
1327
1328      if (Ty.isInvalid())
1329        return ExprError();
1330
1331      CastTy = Ty.get();
1332
1333      if (stopIfCastExpr) {
1334        // Note that this doesn't parse the subsequent cast-expression, it just
1335        // returns the parsed type to the callee.
1336        return OwningExprResult(Actions);
1337      }
1338
1339      // Parse the cast-expression that follows it next.
1340      // TODO: For cast expression with CastTy.
1341      Result = ParseCastExpression(false);
1342      if (!Result.isInvalid())
1343        Result = Actions.ActOnCastExpr(OpenLoc, CastTy, RParenLoc,move(Result));
1344      return move(Result);
1345    }
1346
1347    Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1348    return ExprError();
1349  } else {
1350    Result = ParseExpression();
1351    ExprType = SimpleExpr;
1352    if (!Result.isInvalid() && Tok.is(tok::r_paren))
1353      Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), move(Result));
1354  }
1355
1356  // Match the ')'.
1357  if (Result.isInvalid()) {
1358    SkipUntil(tok::r_paren);
1359    return ExprError();
1360  }
1361
1362  if (Tok.is(tok::r_paren))
1363    RParenLoc = ConsumeParen();
1364  else
1365    MatchRHSPunctuation(tok::r_paren, OpenLoc);
1366
1367  return move(Result);
1368}
1369
1370/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
1371/// and we are at the left brace.
1372///
1373///       postfix-expression: [C99 6.5.2]
1374///         '(' type-name ')' '{' initializer-list '}'
1375///         '(' type-name ')' '{' initializer-list ',' '}'
1376///
1377Parser::OwningExprResult
1378Parser::ParseCompoundLiteralExpression(TypeTy *Ty,
1379                                       SourceLocation LParenLoc,
1380                                       SourceLocation RParenLoc) {
1381  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
1382  if (!getLang().C99)   // Compound literals don't exist in C90.
1383    Diag(LParenLoc, diag::ext_c99_compound_literal);
1384  OwningExprResult Result = ParseInitializer();
1385  if (!Result.isInvalid() && Ty)
1386    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, move(Result));
1387  return move(Result);
1388}
1389
1390/// ParseStringLiteralExpression - This handles the various token types that
1391/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1392/// translation phase #6].
1393///
1394///       primary-expression: [C99 6.5.1]
1395///         string-literal
1396Parser::OwningExprResult Parser::ParseStringLiteralExpression() {
1397  assert(isTokenStringLiteral() && "Not a string literal!");
1398
1399  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
1400  // considered to be strings for concatenation purposes.
1401  llvm::SmallVector<Token, 4> StringToks;
1402
1403  do {
1404    StringToks.push_back(Tok);
1405    ConsumeStringToken();
1406  } while (isTokenStringLiteral());
1407
1408  // Pass the set of string tokens, ready for concatenation, to the actions.
1409  return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
1410}
1411
1412/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1413///
1414///       argument-expression-list:
1415///         assignment-expression
1416///         argument-expression-list , assignment-expression
1417///
1418/// [C++] expression-list:
1419/// [C++]   assignment-expression
1420/// [C++]   expression-list , assignment-expression
1421///
1422bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1423  while (1) {
1424    OwningExprResult Expr(ParseAssignmentExpression());
1425    if (Expr.isInvalid())
1426      return true;
1427
1428    Exprs.push_back(Expr.release());
1429
1430    if (Tok.isNot(tok::comma))
1431      return false;
1432    // Move to the next argument, remember where the comma was.
1433    CommaLocs.push_back(ConsumeToken());
1434  }
1435}
1436
1437/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
1438///
1439/// [clang] block-id:
1440/// [clang]   specifier-qualifier-list block-declarator
1441///
1442void Parser::ParseBlockId() {
1443  // Parse the specifier-qualifier-list piece.
1444  DeclSpec DS;
1445  ParseSpecifierQualifierList(DS);
1446
1447  // Parse the block-declarator.
1448  Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
1449  ParseDeclarator(DeclaratorInfo);
1450
1451  // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes.
1452  DeclaratorInfo.AddAttributes(DS.TakeAttributes(),
1453                               SourceLocation());
1454
1455  if (Tok.is(tok::kw___attribute)) {
1456    SourceLocation Loc;
1457    AttributeList *AttrList = ParseAttributes(&Loc);
1458    DeclaratorInfo.AddAttributes(AttrList, Loc);
1459  }
1460
1461  // Inform sema that we are starting a block.
1462  Actions.ActOnBlockArguments(DeclaratorInfo, CurScope);
1463}
1464
1465/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
1466/// like ^(int x){ return x+1; }
1467///
1468///         block-literal:
1469/// [clang]   '^' block-args[opt] compound-statement
1470/// [clang]   '^' block-id compound-statement
1471/// [clang] block-args:
1472/// [clang]   '(' parameter-list ')'
1473///
1474Parser::OwningExprResult Parser::ParseBlockLiteralExpression() {
1475  assert(Tok.is(tok::caret) && "block literal starts with ^");
1476  SourceLocation CaretLoc = ConsumeToken();
1477
1478  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
1479                                "block literal parsing");
1480
1481  // Enter a scope to hold everything within the block.  This includes the
1482  // argument decls, decls within the compound expression, etc.  This also
1483  // allows determining whether a variable reference inside the block is
1484  // within or outside of the block.
1485  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
1486                              Scope::BreakScope | Scope::ContinueScope |
1487                              Scope::DeclScope);
1488
1489  // Inform sema that we are starting a block.
1490  Actions.ActOnBlockStart(CaretLoc, CurScope);
1491
1492  // Parse the return type if present.
1493  DeclSpec DS;
1494  Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
1495  // FIXME: Since the return type isn't actually parsed, it can't be used to
1496  // fill ParamInfo with an initial valid range, so do it manually.
1497  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
1498
1499  // If this block has arguments, parse them.  There is no ambiguity here with
1500  // the expression case, because the expression case requires a parameter list.
1501  if (Tok.is(tok::l_paren)) {
1502    ParseParenDeclarator(ParamInfo);
1503    // Parse the pieces after the identifier as if we had "int(...)".
1504    // SetIdentifier sets the source range end, but in this case we're past
1505    // that location.
1506    SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
1507    ParamInfo.SetIdentifier(0, CaretLoc);
1508    ParamInfo.SetRangeEnd(Tmp);
1509    if (ParamInfo.isInvalidType()) {
1510      // If there was an error parsing the arguments, they may have
1511      // tried to use ^(x+y) which requires an argument list.  Just
1512      // skip the whole block literal.
1513      Actions.ActOnBlockError(CaretLoc, CurScope);
1514      return ExprError();
1515    }
1516
1517    if (Tok.is(tok::kw___attribute)) {
1518      SourceLocation Loc;
1519      AttributeList *AttrList = ParseAttributes(&Loc);
1520      ParamInfo.AddAttributes(AttrList, Loc);
1521    }
1522
1523    // Inform sema that we are starting a block.
1524    Actions.ActOnBlockArguments(ParamInfo, CurScope);
1525  } else if (!Tok.is(tok::l_brace)) {
1526    ParseBlockId();
1527  } else {
1528    // Otherwise, pretend we saw (void).
1529    ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
1530                                                       SourceLocation(),
1531                                                       0, 0, 0,
1532                                                       false, SourceLocation(),
1533                                                       false, 0, 0, 0,
1534                                                       CaretLoc, ParamInfo),
1535                          CaretLoc);
1536
1537    if (Tok.is(tok::kw___attribute)) {
1538      SourceLocation Loc;
1539      AttributeList *AttrList = ParseAttributes(&Loc);
1540      ParamInfo.AddAttributes(AttrList, Loc);
1541    }
1542
1543    // Inform sema that we are starting a block.
1544    Actions.ActOnBlockArguments(ParamInfo, CurScope);
1545  }
1546
1547
1548  OwningExprResult Result(Actions, true);
1549  if (!Tok.is(tok::l_brace)) {
1550    // Saw something like: ^expr
1551    Diag(Tok, diag::err_expected_expression);
1552    Actions.ActOnBlockError(CaretLoc, CurScope);
1553    return ExprError();
1554  }
1555
1556  OwningStmtResult Stmt(ParseCompoundStatementBody());
1557  if (!Stmt.isInvalid())
1558    Result = Actions.ActOnBlockStmtExpr(CaretLoc, move(Stmt), CurScope);
1559  else
1560    Actions.ActOnBlockError(CaretLoc, CurScope);
1561  return move(Result);
1562}
1563