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