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