ParseExpr.cpp revision 208600
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/Parse/Template.h"
26#include "clang/Basic/PrettyStackTrace.h"
27#include "RAIIObjectsForParser.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/SmallString.h"
30using namespace clang;
31
32/// getBinOpPrecedence - Return the precedence of the specified binary operator
33/// token.  This returns:
34///
35static prec::Level getBinOpPrecedence(tok::TokenKind Kind,
36                                      bool GreaterThanIsOperator,
37                                      bool CPlusPlus0x) {
38  switch (Kind) {
39  case tok::greater:
40    // C++ [temp.names]p3:
41    //   [...] When parsing a template-argument-list, the first
42    //   non-nested > is taken as the ending delimiter rather than a
43    //   greater-than operator. [...]
44    if (GreaterThanIsOperator)
45      return prec::Relational;
46    return prec::Unknown;
47
48  case tok::greatergreater:
49    // C++0x [temp.names]p3:
50    //
51    //   [...] Similarly, the first non-nested >> is treated as two
52    //   consecutive but distinct > tokens, the first of which is
53    //   taken as the end of the template-argument-list and completes
54    //   the template-id. [...]
55    if (GreaterThanIsOperator || !CPlusPlus0x)
56      return prec::Shift;
57    return prec::Unknown;
58
59  default:                        return prec::Unknown;
60  case tok::comma:                return prec::Comma;
61  case tok::equal:
62  case tok::starequal:
63  case tok::slashequal:
64  case tok::percentequal:
65  case tok::plusequal:
66  case tok::minusequal:
67  case tok::lesslessequal:
68  case tok::greatergreaterequal:
69  case tok::ampequal:
70  case tok::caretequal:
71  case tok::pipeequal:            return prec::Assignment;
72  case tok::question:             return prec::Conditional;
73  case tok::pipepipe:             return prec::LogicalOr;
74  case tok::ampamp:               return prec::LogicalAnd;
75  case tok::pipe:                 return prec::InclusiveOr;
76  case tok::caret:                return prec::ExclusiveOr;
77  case tok::amp:                  return prec::And;
78  case tok::exclaimequal:
79  case tok::equalequal:           return prec::Equality;
80  case tok::lessequal:
81  case tok::less:
82  case tok::greaterequal:         return prec::Relational;
83  case tok::lessless:             return prec::Shift;
84  case tok::plus:
85  case tok::minus:                return prec::Additive;
86  case tok::percent:
87  case tok::slash:
88  case tok::star:                 return prec::Multiplicative;
89  case tok::periodstar:
90  case tok::arrowstar:            return prec::PointerToMember;
91  }
92}
93
94
95/// ParseExpression - Simple precedence-based parser for binary/ternary
96/// operators.
97///
98/// Note: we diverge from the C99 grammar when parsing the assignment-expression
99/// production.  C99 specifies that the LHS of an assignment operator should be
100/// parsed as a unary-expression, but consistency dictates that it be a
101/// conditional-expession.  In practice, the important thing here is that the
102/// LHS of an assignment has to be an l-value, which productions between
103/// unary-expression and conditional-expression don't produce.  Because we want
104/// consistency, we parse the LHS as a conditional-expression, then check for
105/// l-value-ness in semantic analysis stages.
106///
107///       pm-expression: [C++ 5.5]
108///         cast-expression
109///         pm-expression '.*' cast-expression
110///         pm-expression '->*' cast-expression
111///
112///       multiplicative-expression: [C99 6.5.5]
113///     Note: in C++, apply pm-expression instead of cast-expression
114///         cast-expression
115///         multiplicative-expression '*' cast-expression
116///         multiplicative-expression '/' cast-expression
117///         multiplicative-expression '%' cast-expression
118///
119///       additive-expression: [C99 6.5.6]
120///         multiplicative-expression
121///         additive-expression '+' multiplicative-expression
122///         additive-expression '-' multiplicative-expression
123///
124///       shift-expression: [C99 6.5.7]
125///         additive-expression
126///         shift-expression '<<' additive-expression
127///         shift-expression '>>' additive-expression
128///
129///       relational-expression: [C99 6.5.8]
130///         shift-expression
131///         relational-expression '<' shift-expression
132///         relational-expression '>' shift-expression
133///         relational-expression '<=' shift-expression
134///         relational-expression '>=' shift-expression
135///
136///       equality-expression: [C99 6.5.9]
137///         relational-expression
138///         equality-expression '==' relational-expression
139///         equality-expression '!=' relational-expression
140///
141///       AND-expression: [C99 6.5.10]
142///         equality-expression
143///         AND-expression '&' equality-expression
144///
145///       exclusive-OR-expression: [C99 6.5.11]
146///         AND-expression
147///         exclusive-OR-expression '^' AND-expression
148///
149///       inclusive-OR-expression: [C99 6.5.12]
150///         exclusive-OR-expression
151///         inclusive-OR-expression '|' exclusive-OR-expression
152///
153///       logical-AND-expression: [C99 6.5.13]
154///         inclusive-OR-expression
155///         logical-AND-expression '&&' inclusive-OR-expression
156///
157///       logical-OR-expression: [C99 6.5.14]
158///         logical-AND-expression
159///         logical-OR-expression '||' logical-AND-expression
160///
161///       conditional-expression: [C99 6.5.15]
162///         logical-OR-expression
163///         logical-OR-expression '?' expression ':' conditional-expression
164/// [GNU]   logical-OR-expression '?' ':' conditional-expression
165/// [C++] the third operand is an assignment-expression
166///
167///       assignment-expression: [C99 6.5.16]
168///         conditional-expression
169///         unary-expression assignment-operator assignment-expression
170/// [C++]   throw-expression [C++ 15]
171///
172///       assignment-operator: one of
173///         = *= /= %= += -= <<= >>= &= ^= |=
174///
175///       expression: [C99 6.5.17]
176///         assignment-expression
177///         expression ',' assignment-expression
178///
179Parser::OwningExprResult Parser::ParseExpression() {
180  OwningExprResult LHS(ParseAssignmentExpression());
181  if (LHS.isInvalid()) return move(LHS);
182
183  return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
184}
185
186/// This routine is called when the '@' is seen and consumed.
187/// Current token is an Identifier and is not a 'try'. This
188/// routine is necessary to disambiguate @try-statement from,
189/// for example, @encode-expression.
190///
191Parser::OwningExprResult
192Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
193  OwningExprResult LHS(ParseObjCAtExpression(AtLoc));
194  if (LHS.isInvalid()) return move(LHS);
195
196  return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
197}
198
199/// This routine is called when a leading '__extension__' is seen and
200/// consumed.  This is necessary because the token gets consumed in the
201/// process of disambiguating between an expression and a declaration.
202Parser::OwningExprResult
203Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
204  OwningExprResult LHS(Actions, true);
205  {
206    // Silence extension warnings in the sub-expression
207    ExtensionRAIIObject O(Diags);
208
209    LHS = ParseCastExpression(false);
210    if (LHS.isInvalid()) return move(LHS);
211  }
212
213  LHS = Actions.ActOnUnaryOp(CurScope, ExtLoc, tok::kw___extension__,
214                             move(LHS));
215  if (LHS.isInvalid()) return move(LHS);
216
217  return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
218}
219
220/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
221///
222Parser::OwningExprResult Parser::ParseAssignmentExpression() {
223  if (Tok.is(tok::code_completion)) {
224    Actions.CodeCompleteOrdinaryName(CurScope, Action::CCC_Expression);
225    ConsumeCodeCompletionToken();
226  }
227
228  if (Tok.is(tok::kw_throw))
229    return ParseThrowExpression();
230
231  OwningExprResult LHS(ParseCastExpression(false));
232  if (LHS.isInvalid()) return move(LHS);
233
234  return ParseRHSOfBinaryExpression(move(LHS), prec::Assignment);
235}
236
237/// ParseAssignmentExprWithObjCMessageExprStart - Parse an assignment expression
238/// where part of an objc message send has already been parsed.  In this case
239/// LBracLoc indicates the location of the '[' of the message send, and either
240/// ReceiverName or ReceiverExpr is non-null indicating the receiver of the
241/// message.
242///
243/// Since this handles full assignment-expression's, it handles postfix
244/// expressions and other binary operators for these expressions as well.
245Parser::OwningExprResult
246Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
247                                                    SourceLocation SuperLoc,
248                                                    TypeTy *ReceiverType,
249                                                    ExprArg ReceiverExpr) {
250  OwningExprResult R(ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
251                                                    ReceiverType,
252                                                    move(ReceiverExpr)));
253  if (R.isInvalid()) return move(R);
254  R = ParsePostfixExpressionSuffix(move(R));
255  if (R.isInvalid()) return move(R);
256  return ParseRHSOfBinaryExpression(move(R), prec::Assignment);
257}
258
259
260Parser::OwningExprResult Parser::ParseConstantExpression() {
261  // C++ [basic.def.odr]p2:
262  //   An expression is potentially evaluated unless it appears where an
263  //   integral constant expression is required (see 5.19) [...].
264  EnterExpressionEvaluationContext Unevaluated(Actions,
265                                               Action::Unevaluated);
266
267  OwningExprResult LHS(ParseCastExpression(false));
268  if (LHS.isInvalid()) return move(LHS);
269
270  return ParseRHSOfBinaryExpression(move(LHS), prec::Conditional);
271}
272
273/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
274/// LHS and has a precedence of at least MinPrec.
275Parser::OwningExprResult
276Parser::ParseRHSOfBinaryExpression(OwningExprResult LHS, prec::Level MinPrec) {
277  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
278                                               GreaterThanIsOperator,
279                                               getLang().CPlusPlus0x);
280  SourceLocation ColonLoc;
281
282  while (1) {
283    // If this token has a lower precedence than we are allowed to parse (e.g.
284    // because we are called recursively, or because the token is not a binop),
285    // then we are done!
286    if (NextTokPrec < MinPrec)
287      return move(LHS);
288
289    // Consume the operator, saving the operator token for error reporting.
290    Token OpToken = Tok;
291    ConsumeToken();
292
293    // Special case handling for the ternary operator.
294    OwningExprResult TernaryMiddle(Actions, true);
295    if (NextTokPrec == prec::Conditional) {
296      if (Tok.isNot(tok::colon)) {
297        // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
298        ColonProtectionRAIIObject X(*this);
299
300        // Handle this production specially:
301        //   logical-OR-expression '?' expression ':' conditional-expression
302        // In particular, the RHS of the '?' is 'expression', not
303        // 'logical-OR-expression' as we might expect.
304        TernaryMiddle = ParseExpression();
305        if (TernaryMiddle.isInvalid())
306          return move(TernaryMiddle);
307      } else {
308        // Special case handling of "X ? Y : Z" where Y is empty:
309        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
310        TernaryMiddle = 0;
311        Diag(Tok, diag::ext_gnu_conditional_expr);
312      }
313
314      if (Tok.is(tok::colon)) {
315        // Eat the colon.
316        ColonLoc = ConsumeToken();
317      } else {
318        // Otherwise, we're missing a ':'.  Assume that this was a typo that the
319        // user forgot.  If we're not in a macro instantion, we can suggest a
320        // fixit hint.  If there were two spaces before the current token,
321        // suggest inserting the colon in between them, otherwise insert ": ".
322        SourceLocation FILoc = Tok.getLocation();
323        const char *FIText = ": ";
324        if (FILoc.isFileID()) {
325          const SourceManager &SM = PP.getSourceManager();
326          bool IsInvalid = false;
327          const char *SourcePtr =
328            SM.getCharacterData(FILoc.getFileLocWithOffset(-1), &IsInvalid);
329          if (!IsInvalid && *SourcePtr == ' ') {
330            SourcePtr =
331              SM.getCharacterData(FILoc.getFileLocWithOffset(-2), &IsInvalid);
332            if (!IsInvalid && *SourcePtr == ' ') {
333              FILoc = FILoc.getFileLocWithOffset(-1);
334              FIText = ":";
335            }
336          }
337        }
338
339        Diag(Tok, diag::err_expected_colon)
340          << FixItHint::CreateInsertion(FILoc, FIText);
341        Diag(OpToken, diag::note_matching) << "?";
342        ColonLoc = Tok.getLocation();
343      }
344    }
345
346    // Parse another leaf here for the RHS of the operator.
347    // ParseCastExpression works here because all RHS expressions in C have it
348    // as a prefix, at least. However, in C++, an assignment-expression could
349    // be a throw-expression, which is not a valid cast-expression.
350    // Therefore we need some special-casing here.
351    // Also note that the third operand of the conditional operator is
352    // an assignment-expression in C++.
353    OwningExprResult RHS(Actions);
354    if (getLang().CPlusPlus && NextTokPrec <= prec::Conditional)
355      RHS = ParseAssignmentExpression();
356    else
357      RHS = ParseCastExpression(false);
358    if (RHS.isInvalid())
359      return move(RHS);
360
361    // Remember the precedence of this operator and get the precedence of the
362    // operator immediately to the right of the RHS.
363    prec::Level ThisPrec = NextTokPrec;
364    NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
365                                     getLang().CPlusPlus0x);
366
367    // Assignment and conditional expressions are right-associative.
368    bool isRightAssoc = ThisPrec == prec::Conditional ||
369                        ThisPrec == prec::Assignment;
370
371    // Get the precedence of the operator to the right of the RHS.  If it binds
372    // more tightly with RHS than we do, evaluate it completely first.
373    if (ThisPrec < NextTokPrec ||
374        (ThisPrec == NextTokPrec && isRightAssoc)) {
375      // If this is left-associative, only parse things on the RHS that bind
376      // more tightly than the current operator.  If it is left-associative, it
377      // is okay, to bind exactly as tightly.  For example, compile A=B=C=D as
378      // A=(B=(C=D)), where each paren is a level of recursion here.
379      // The function takes ownership of the RHS.
380      RHS = ParseRHSOfBinaryExpression(move(RHS),
381                            static_cast<prec::Level>(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] ')'         [C++ 5.2.3]
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
503///
504///       unqualified-id: [C++ 5.1]
505///                   identifier
506///                   operator-function-id
507///                   conversion-function-id
508///                   '~' class-name
509///                   template-id
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 ExprError();
629        if (!Tok.is(tok::identifier))
630          return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
631      }
632    }
633
634    // Consume the identifier so that we can see if it is followed by a '(' or
635    // '.'.
636    IdentifierInfo &II = *Tok.getIdentifierInfo();
637    SourceLocation ILoc = ConsumeToken();
638
639    // Support 'Class.property' and 'super.property' notation.
640    if (getLang().ObjC1 && Tok.is(tok::period) &&
641        (Actions.getTypeName(II, ILoc, CurScope) ||
642         // Allow the base to be 'super' if in an objc-method.
643         (&II == Ident_super && CurScope->isInObjcMethodScope()))) {
644      SourceLocation DotLoc = ConsumeToken();
645
646      if (Tok.isNot(tok::identifier)) {
647        Diag(Tok, diag::err_expected_property_name);
648        return ExprError();
649      }
650      IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
651      SourceLocation PropertyLoc = ConsumeToken();
652
653      Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
654                                              ILoc, PropertyLoc);
655      // These can be followed by postfix-expr pieces.
656      return ParsePostfixExpressionSuffix(move(Res));
657    }
658
659    // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
660    // need to know whether or not this identifier is a function designator or
661    // not.
662    UnqualifiedId Name;
663    CXXScopeSpec ScopeSpec;
664    Name.setIdentifier(&II, ILoc);
665    Res = Actions.ActOnIdExpression(CurScope, ScopeSpec, Name,
666                                    Tok.is(tok::l_paren), false);
667    // These can be followed by postfix-expr pieces.
668    return ParsePostfixExpressionSuffix(move(Res));
669  }
670  case tok::char_constant:     // constant: character-constant
671    Res = Actions.ActOnCharacterConstant(Tok);
672    ConsumeToken();
673    // These can be followed by postfix-expr pieces.
674    return ParsePostfixExpressionSuffix(move(Res));
675  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
676  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
677  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
678    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
679    ConsumeToken();
680    // These can be followed by postfix-expr pieces.
681    return ParsePostfixExpressionSuffix(move(Res));
682  case tok::string_literal:    // primary-expression: string-literal
683  case tok::wide_string_literal:
684    Res = ParseStringLiteralExpression();
685    if (Res.isInvalid()) return move(Res);
686    // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
687    return ParsePostfixExpressionSuffix(move(Res));
688  case tok::kw___builtin_va_arg:
689  case tok::kw___builtin_offsetof:
690  case tok::kw___builtin_choose_expr:
691  case tok::kw___builtin_types_compatible_p:
692    return ParseBuiltinPrimaryExpression();
693  case tok::kw___null:
694    return Actions.ActOnGNUNullExpr(ConsumeToken());
695    break;
696  case tok::plusplus:      // unary-expression: '++' unary-expression
697  case tok::minusminus: {  // unary-expression: '--' unary-expression
698    SourceLocation SavedLoc = ConsumeToken();
699    Res = ParseCastExpression(true);
700    if (!Res.isInvalid())
701      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res));
702    return move(Res);
703  }
704  case tok::amp: {         // unary-expression: '&' cast-expression
705    // Special treatment because of member pointers
706    SourceLocation SavedLoc = ConsumeToken();
707    Res = ParseCastExpression(false, true);
708    if (!Res.isInvalid())
709      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res));
710    return move(Res);
711  }
712
713  case tok::star:          // unary-expression: '*' cast-expression
714  case tok::plus:          // unary-expression: '+' cast-expression
715  case tok::minus:         // unary-expression: '-' cast-expression
716  case tok::tilde:         // unary-expression: '~' cast-expression
717  case tok::exclaim:       // unary-expression: '!' cast-expression
718  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
719  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
720    SourceLocation SavedLoc = ConsumeToken();
721    Res = ParseCastExpression(false);
722    if (!Res.isInvalid())
723      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res));
724    return move(Res);
725  }
726
727  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
728    // __extension__ silences extension warnings in the subexpression.
729    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
730    SourceLocation SavedLoc = ConsumeToken();
731    Res = ParseCastExpression(false);
732    if (!Res.isInvalid())
733      Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res));
734    return move(Res);
735  }
736  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
737                           // unary-expression: 'sizeof' '(' type-name ')'
738  case tok::kw_alignof:
739  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
740                           // unary-expression: '__alignof' '(' type-name ')'
741                           // unary-expression: 'alignof' '(' type-id ')'
742    return ParseSizeofAlignofExpression();
743  case tok::ampamp: {      // unary-expression: '&&' identifier
744    SourceLocation AmpAmpLoc = ConsumeToken();
745    if (Tok.isNot(tok::identifier))
746      return ExprError(Diag(Tok, diag::err_expected_ident));
747
748    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
749    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
750                                 Tok.getIdentifierInfo());
751    ConsumeToken();
752    return move(Res);
753  }
754  case tok::kw_const_cast:
755  case tok::kw_dynamic_cast:
756  case tok::kw_reinterpret_cast:
757  case tok::kw_static_cast:
758    Res = ParseCXXCasts();
759    // These can be followed by postfix-expr pieces.
760    return ParsePostfixExpressionSuffix(move(Res));
761  case tok::kw_typeid:
762    Res = ParseCXXTypeid();
763    // This can be followed by postfix-expr pieces.
764    return ParsePostfixExpressionSuffix(move(Res));
765  case tok::kw_this:
766    Res = ParseCXXThis();
767    // This can be followed by postfix-expr pieces.
768    return ParsePostfixExpressionSuffix(move(Res));
769
770  case tok::kw_char:
771  case tok::kw_wchar_t:
772  case tok::kw_char16_t:
773  case tok::kw_char32_t:
774  case tok::kw_bool:
775  case tok::kw_short:
776  case tok::kw_int:
777  case tok::kw_long:
778  case tok::kw_signed:
779  case tok::kw_unsigned:
780  case tok::kw_float:
781  case tok::kw_double:
782  case tok::kw_void:
783  case tok::kw_typename:
784  case tok::kw_typeof:
785  case tok::kw___vector:
786  case tok::annot_typename: {
787    if (!getLang().CPlusPlus) {
788      Diag(Tok, diag::err_expected_expression);
789      return ExprError();
790    }
791
792    if (SavedKind == tok::kw_typename) {
793      // postfix-expression: typename-specifier '(' expression-list[opt] ')'
794      if (TryAnnotateTypeOrScopeToken())
795        return ExprError();
796    }
797
798    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
799    //
800    DeclSpec DS;
801    ParseCXXSimpleTypeSpecifier(DS);
802    if (Tok.isNot(tok::l_paren))
803      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
804                         << DS.getSourceRange());
805
806    Res = ParseCXXTypeConstructExpression(DS);
807    // This can be followed by postfix-expr pieces.
808    return ParsePostfixExpressionSuffix(move(Res));
809  }
810
811  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
812    // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
813    // (We can end up in this situation after tentative parsing.)
814    if (TryAnnotateTypeOrScopeToken())
815      return ExprError();
816    if (!Tok.is(tok::annot_cxxscope))
817      return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
818                                 NotCastExpr, TypeOfCast);
819
820    Token Next = NextToken();
821    if (Next.is(tok::annot_template_id)) {
822      TemplateIdAnnotation *TemplateId
823        = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue());
824      if (TemplateId->Kind == TNK_Type_template) {
825        // We have a qualified template-id that we know refers to a
826        // type, translate it into a type and continue parsing as a
827        // cast expression.
828        CXXScopeSpec SS;
829        ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
830        AnnotateTemplateIdTokenAsType(&SS);
831        return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
832                                   NotCastExpr, TypeOfCast);
833      }
834    }
835
836    // Parse as an id-expression.
837    Res = ParseCXXIdExpression(isAddressOfOperand);
838    return ParsePostfixExpressionSuffix(move(Res));
839  }
840
841  case tok::annot_template_id: { // [C++]          template-id
842    TemplateIdAnnotation *TemplateId
843      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
844    if (TemplateId->Kind == TNK_Type_template) {
845      // We have a template-id that we know refers to a type,
846      // translate it into a type and continue parsing as a cast
847      // expression.
848      AnnotateTemplateIdTokenAsType();
849      return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
850                                 NotCastExpr, TypeOfCast);
851    }
852
853    // Fall through to treat the template-id as an id-expression.
854  }
855
856  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
857    Res = ParseCXXIdExpression(isAddressOfOperand);
858    return ParsePostfixExpressionSuffix(move(Res));
859
860  case tok::coloncolon: {
861    // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
862    // annotates the token, tail recurse.
863    if (TryAnnotateTypeOrScopeToken())
864      return ExprError();
865    if (!Tok.is(tok::coloncolon))
866      return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
867
868    // ::new -> [C++] new-expression
869    // ::delete -> [C++] delete-expression
870    SourceLocation CCLoc = ConsumeToken();
871    if (Tok.is(tok::kw_new))
872      return ParseCXXNewExpression(true, CCLoc);
873    if (Tok.is(tok::kw_delete))
874      return ParseCXXDeleteExpression(true, CCLoc);
875
876    // This is not a type name or scope specifier, it is an invalid expression.
877    Diag(CCLoc, diag::err_expected_expression);
878    return ExprError();
879  }
880
881  case tok::kw_new: // [C++] new-expression
882    return ParseCXXNewExpression(false, Tok.getLocation());
883
884  case tok::kw_delete: // [C++] delete-expression
885    return ParseCXXDeleteExpression(false, Tok.getLocation());
886
887  case tok::kw___is_pod: // [GNU] unary-type-trait
888  case tok::kw___is_class:
889  case tok::kw___is_enum:
890  case tok::kw___is_union:
891  case tok::kw___is_empty:
892  case tok::kw___is_polymorphic:
893  case tok::kw___is_abstract:
894  case tok::kw___is_literal:
895  case tok::kw___has_trivial_constructor:
896  case tok::kw___has_trivial_copy:
897  case tok::kw___has_trivial_assign:
898  case tok::kw___has_trivial_destructor:
899    return ParseUnaryTypeTrait();
900
901  case tok::at: {
902    SourceLocation AtLoc = ConsumeToken();
903    return ParseObjCAtExpression(AtLoc);
904  }
905  case tok::caret:
906    return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
907  case tok::code_completion:
908    Actions.CodeCompleteOrdinaryName(CurScope, Action::CCC_Expression);
909    ConsumeCodeCompletionToken();
910    return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
911                               NotCastExpr, TypeOfCast);
912  case tok::l_square:
913    // These can be followed by postfix-expr pieces.
914    if (getLang().ObjC1)
915      return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
916    // FALL THROUGH.
917  default:
918    NotCastExpr = true;
919    return ExprError();
920  }
921
922  // unreachable.
923  abort();
924}
925
926/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
927/// is parsed, this method parses any suffixes that apply.
928///
929///       postfix-expression: [C99 6.5.2]
930///         primary-expression
931///         postfix-expression '[' expression ']'
932///         postfix-expression '(' argument-expression-list[opt] ')'
933///         postfix-expression '.' identifier
934///         postfix-expression '->' identifier
935///         postfix-expression '++'
936///         postfix-expression '--'
937///         '(' type-name ')' '{' initializer-list '}'
938///         '(' type-name ')' '{' initializer-list ',' '}'
939///
940///       argument-expression-list: [C99 6.5.2]
941///         argument-expression
942///         argument-expression-list ',' assignment-expression
943///
944Parser::OwningExprResult
945Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) {
946  // Now that the primary-expression piece of the postfix-expression has been
947  // parsed, see if there are any postfix-expression pieces here.
948  SourceLocation Loc;
949  while (1) {
950    switch (Tok.getKind()) {
951    default:  // Not a postfix-expression suffix.
952      return move(LHS);
953    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
954      Loc = ConsumeBracket();
955      OwningExprResult Idx(ParseExpression());
956
957      SourceLocation RLoc = Tok.getLocation();
958
959      if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
960        LHS = Actions.ActOnArraySubscriptExpr(CurScope, move(LHS), Loc,
961                                              move(Idx), RLoc);
962      } else
963        LHS = ExprError();
964
965      // Match the ']'.
966      MatchRHSPunctuation(tok::r_square, Loc);
967      break;
968    }
969
970    case tok::l_paren: {   // p-e: p-e '(' argument-expression-list[opt] ')'
971      ExprVector ArgExprs(Actions);
972      CommaLocsTy CommaLocs;
973
974      Loc = ConsumeParen();
975
976      if (Tok.is(tok::code_completion)) {
977        Actions.CodeCompleteCall(CurScope, LHS.get(), 0, 0);
978        ConsumeCodeCompletionToken();
979      }
980
981      if (Tok.isNot(tok::r_paren)) {
982        if (ParseExpressionList(ArgExprs, CommaLocs, &Action::CodeCompleteCall,
983                                LHS.get())) {
984          SkipUntil(tok::r_paren);
985          return ExprError();
986        }
987      }
988
989      // Match the ')'.
990      if (Tok.isNot(tok::r_paren)) {
991        MatchRHSPunctuation(tok::r_paren, Loc);
992        return ExprError();
993      }
994
995      if (!LHS.isInvalid()) {
996        assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
997               "Unexpected number of commas!");
998        LHS = Actions.ActOnCallExpr(CurScope, move(LHS), Loc,
999                                    move_arg(ArgExprs), CommaLocs.data(),
1000                                    Tok.getLocation());
1001      }
1002
1003      ConsumeParen();
1004      break;
1005    }
1006    case tok::arrow:
1007    case tok::period: {
1008      // postfix-expression: p-e '->' template[opt] id-expression
1009      // postfix-expression: p-e '.' template[opt] id-expression
1010      tok::TokenKind OpKind = Tok.getKind();
1011      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
1012
1013      CXXScopeSpec SS;
1014      Action::TypeTy *ObjectType = 0;
1015      bool MayBePseudoDestructor = false;
1016      if (getLang().CPlusPlus && !LHS.isInvalid()) {
1017        LHS = Actions.ActOnStartCXXMemberReference(CurScope, move(LHS),
1018                                                   OpLoc, OpKind, ObjectType,
1019                                                   MayBePseudoDestructor);
1020        if (LHS.isInvalid())
1021          break;
1022
1023        ParseOptionalCXXScopeSpecifier(SS, ObjectType, false,
1024                                       &MayBePseudoDestructor);
1025      }
1026
1027      if (Tok.is(tok::code_completion)) {
1028        // Code completion for a member access expression.
1029        Actions.CodeCompleteMemberReferenceExpr(CurScope, LHS.get(),
1030                                                OpLoc, OpKind == tok::arrow);
1031
1032        ConsumeCodeCompletionToken();
1033      }
1034
1035      if (MayBePseudoDestructor) {
1036        LHS = ParseCXXPseudoDestructor(move(LHS), OpLoc, OpKind, SS,
1037                                       ObjectType);
1038        break;
1039      }
1040
1041      // Either the action has told is that this cannot be a
1042      // pseudo-destructor expression (based on the type of base
1043      // expression), or we didn't see a '~' in the right place. We
1044      // can still parse a destructor name here, but in that case it
1045      // names a real destructor.
1046      UnqualifiedId Name;
1047      if (ParseUnqualifiedId(SS,
1048                             /*EnteringContext=*/false,
1049                             /*AllowDestructorName=*/true,
1050                             /*AllowConstructorName=*/false,
1051                             ObjectType,
1052                             Name))
1053        return ExprError();
1054
1055      if (!LHS.isInvalid())
1056        LHS = Actions.ActOnMemberAccessExpr(CurScope, move(LHS), OpLoc,
1057                                            OpKind, SS, Name, ObjCImpDecl,
1058                                            Tok.is(tok::l_paren));
1059      break;
1060    }
1061    case tok::plusplus:    // postfix-expression: postfix-expression '++'
1062    case tok::minusminus:  // postfix-expression: postfix-expression '--'
1063      if (!LHS.isInvalid()) {
1064        LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(),
1065                                          Tok.getKind(), move(LHS));
1066      }
1067      ConsumeToken();
1068      break;
1069    }
1070  }
1071}
1072
1073/// ParseExprAfterTypeofSizeofAlignof - We parsed a typeof/sizeof/alignof and
1074/// we are at the start of an expression or a parenthesized type-id.
1075/// OpTok is the operand token (typeof/sizeof/alignof). Returns the expression
1076/// (isCastExpr == false) or the type (isCastExpr == true).
1077///
1078///       unary-expression:  [C99 6.5.3]
1079///         'sizeof' unary-expression
1080///         'sizeof' '(' type-name ')'
1081/// [GNU]   '__alignof' unary-expression
1082/// [GNU]   '__alignof' '(' type-name ')'
1083/// [C++0x] 'alignof' '(' type-id ')'
1084///
1085/// [GNU]   typeof-specifier:
1086///           typeof ( expressions )
1087///           typeof ( type-name )
1088/// [GNU/C++] typeof unary-expression
1089///
1090Parser::OwningExprResult
1091Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok,
1092                                          bool &isCastExpr,
1093                                          TypeTy *&CastTy,
1094                                          SourceRange &CastRange) {
1095
1096  assert((OpTok.is(tok::kw_typeof)    || OpTok.is(tok::kw_sizeof) ||
1097          OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof)) &&
1098          "Not a typeof/sizeof/alignof expression!");
1099
1100  OwningExprResult Operand(Actions);
1101
1102  // If the operand doesn't start with an '(', it must be an expression.
1103  if (Tok.isNot(tok::l_paren)) {
1104    isCastExpr = false;
1105    if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) {
1106      Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo();
1107      return ExprError();
1108    }
1109
1110    // C++0x [expr.sizeof]p1:
1111    //   [...] The operand is either an expression, which is an unevaluated
1112    //   operand (Clause 5) [...]
1113    //
1114    // The GNU typeof and alignof extensions also behave as unevaluated
1115    // operands.
1116    EnterExpressionEvaluationContext Unevaluated(Actions,
1117                                                 Action::Unevaluated);
1118    Operand = ParseCastExpression(true/*isUnaryExpression*/);
1119  } else {
1120    // If it starts with a '(', we know that it is either a parenthesized
1121    // type-name, or it is a unary-expression that starts with a compound
1122    // literal, or starts with a primary-expression that is a parenthesized
1123    // expression.
1124    ParenParseOption ExprType = CastExpr;
1125    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1126
1127    // C++0x [expr.sizeof]p1:
1128    //   [...] The operand is either an expression, which is an unevaluated
1129    //   operand (Clause 5) [...]
1130    //
1131    // The GNU typeof and alignof extensions also behave as unevaluated
1132    // operands.
1133    EnterExpressionEvaluationContext Unevaluated(Actions,
1134                                                 Action::Unevaluated);
1135    Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1136                                   0/*TypeOfCast*/,
1137                                   CastTy, RParenLoc);
1138    CastRange = SourceRange(LParenLoc, RParenLoc);
1139
1140    // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1141    // a type.
1142    if (ExprType == CastExpr) {
1143      isCastExpr = true;
1144      return ExprEmpty();
1145    }
1146
1147    // If this is a parenthesized expression, it is the start of a
1148    // unary-expression, but doesn't include any postfix pieces.  Parse these
1149    // now if present.
1150    Operand = ParsePostfixExpressionSuffix(move(Operand));
1151  }
1152
1153  // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1154  isCastExpr = false;
1155  return move(Operand);
1156}
1157
1158
1159/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
1160///       unary-expression:  [C99 6.5.3]
1161///         'sizeof' unary-expression
1162///         'sizeof' '(' type-name ')'
1163/// [GNU]   '__alignof' unary-expression
1164/// [GNU]   '__alignof' '(' type-name ')'
1165/// [C++0x] 'alignof' '(' type-id ')'
1166Parser::OwningExprResult Parser::ParseSizeofAlignofExpression() {
1167  assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
1168          || Tok.is(tok::kw_alignof)) &&
1169         "Not a sizeof/alignof expression!");
1170  Token OpTok = Tok;
1171  ConsumeToken();
1172
1173  bool isCastExpr;
1174  TypeTy *CastTy;
1175  SourceRange CastRange;
1176  OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok,
1177                                                               isCastExpr,
1178                                                               CastTy,
1179                                                               CastRange);
1180
1181  if (isCastExpr)
1182    return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
1183                                          OpTok.is(tok::kw_sizeof),
1184                                          /*isType=*/true, CastTy,
1185                                          CastRange);
1186
1187  // If we get here, the operand to the sizeof/alignof was an expresion.
1188  if (!Operand.isInvalid())
1189    Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
1190                                             OpTok.is(tok::kw_sizeof),
1191                                             /*isType=*/false,
1192                                             Operand.release(), CastRange);
1193  return move(Operand);
1194}
1195
1196/// ParseBuiltinPrimaryExpression
1197///
1198///       primary-expression: [C99 6.5.1]
1199/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1200/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1201/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1202///                                     assign-expr ')'
1203/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1204///
1205/// [GNU] offsetof-member-designator:
1206/// [GNU]   identifier
1207/// [GNU]   offsetof-member-designator '.' identifier
1208/// [GNU]   offsetof-member-designator '[' expression ']'
1209///
1210Parser::OwningExprResult Parser::ParseBuiltinPrimaryExpression() {
1211  OwningExprResult Res(Actions);
1212  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1213
1214  tok::TokenKind T = Tok.getKind();
1215  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
1216
1217  // All of these start with an open paren.
1218  if (Tok.isNot(tok::l_paren))
1219    return ExprError(Diag(Tok, diag::err_expected_lparen_after_id)
1220                       << BuiltinII);
1221
1222  SourceLocation LParenLoc = ConsumeParen();
1223  // TODO: Build AST.
1224
1225  switch (T) {
1226  default: assert(0 && "Not a builtin primary expression!");
1227  case tok::kw___builtin_va_arg: {
1228    OwningExprResult Expr(ParseAssignmentExpression());
1229    if (Expr.isInvalid()) {
1230      SkipUntil(tok::r_paren);
1231      return ExprError();
1232    }
1233
1234    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1235      return ExprError();
1236
1237    TypeResult Ty = ParseTypeName();
1238
1239    if (Tok.isNot(tok::r_paren)) {
1240      Diag(Tok, diag::err_expected_rparen);
1241      return ExprError();
1242    }
1243    if (Ty.isInvalid())
1244      Res = ExprError();
1245    else
1246      Res = Actions.ActOnVAArg(StartLoc, move(Expr), Ty.get(), ConsumeParen());
1247    break;
1248  }
1249  case tok::kw___builtin_offsetof: {
1250    SourceLocation TypeLoc = Tok.getLocation();
1251    TypeResult Ty = ParseTypeName();
1252    if (Ty.isInvalid()) {
1253      SkipUntil(tok::r_paren);
1254      return ExprError();
1255    }
1256
1257    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1258      return ExprError();
1259
1260    // We must have at least one identifier here.
1261    if (Tok.isNot(tok::identifier)) {
1262      Diag(Tok, diag::err_expected_ident);
1263      SkipUntil(tok::r_paren);
1264      return ExprError();
1265    }
1266
1267    // Keep track of the various subcomponents we see.
1268    llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
1269
1270    Comps.push_back(Action::OffsetOfComponent());
1271    Comps.back().isBrackets = false;
1272    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1273    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1274
1275    // FIXME: This loop leaks the index expressions on error.
1276    while (1) {
1277      if (Tok.is(tok::period)) {
1278        // offsetof-member-designator: offsetof-member-designator '.' identifier
1279        Comps.push_back(Action::OffsetOfComponent());
1280        Comps.back().isBrackets = false;
1281        Comps.back().LocStart = ConsumeToken();
1282
1283        if (Tok.isNot(tok::identifier)) {
1284          Diag(Tok, diag::err_expected_ident);
1285          SkipUntil(tok::r_paren);
1286          return ExprError();
1287        }
1288        Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1289        Comps.back().LocEnd = ConsumeToken();
1290
1291      } else if (Tok.is(tok::l_square)) {
1292        // offsetof-member-designator: offsetof-member-design '[' expression ']'
1293        Comps.push_back(Action::OffsetOfComponent());
1294        Comps.back().isBrackets = true;
1295        Comps.back().LocStart = ConsumeBracket();
1296        Res = ParseExpression();
1297        if (Res.isInvalid()) {
1298          SkipUntil(tok::r_paren);
1299          return move(Res);
1300        }
1301        Comps.back().U.E = Res.release();
1302
1303        Comps.back().LocEnd =
1304          MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
1305      } else {
1306        if (Tok.isNot(tok::r_paren)) {
1307          MatchRHSPunctuation(tok::r_paren, LParenLoc);
1308          Res = ExprError();
1309        } else if (Ty.isInvalid()) {
1310          Res = ExprError();
1311        } else {
1312          Res = Actions.ActOnBuiltinOffsetOf(CurScope, StartLoc, TypeLoc,
1313                                             Ty.get(), &Comps[0],
1314                                             Comps.size(), ConsumeParen());
1315        }
1316        break;
1317      }
1318    }
1319    break;
1320  }
1321  case tok::kw___builtin_choose_expr: {
1322    OwningExprResult Cond(ParseAssignmentExpression());
1323    if (Cond.isInvalid()) {
1324      SkipUntil(tok::r_paren);
1325      return move(Cond);
1326    }
1327    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1328      return ExprError();
1329
1330    OwningExprResult Expr1(ParseAssignmentExpression());
1331    if (Expr1.isInvalid()) {
1332      SkipUntil(tok::r_paren);
1333      return move(Expr1);
1334    }
1335    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1336      return ExprError();
1337
1338    OwningExprResult Expr2(ParseAssignmentExpression());
1339    if (Expr2.isInvalid()) {
1340      SkipUntil(tok::r_paren);
1341      return move(Expr2);
1342    }
1343    if (Tok.isNot(tok::r_paren)) {
1344      Diag(Tok, diag::err_expected_rparen);
1345      return ExprError();
1346    }
1347    Res = Actions.ActOnChooseExpr(StartLoc, move(Cond), move(Expr1),
1348                                  move(Expr2), ConsumeParen());
1349    break;
1350  }
1351  case tok::kw___builtin_types_compatible_p:
1352    TypeResult Ty1 = ParseTypeName();
1353
1354    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1355      return ExprError();
1356
1357    TypeResult Ty2 = ParseTypeName();
1358
1359    if (Tok.isNot(tok::r_paren)) {
1360      Diag(Tok, diag::err_expected_rparen);
1361      return ExprError();
1362    }
1363
1364    if (Ty1.isInvalid() || Ty2.isInvalid())
1365      Res = ExprError();
1366    else
1367      Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1.get(), Ty2.get(),
1368                                             ConsumeParen());
1369    break;
1370  }
1371
1372  // These can be followed by postfix-expr pieces because they are
1373  // primary-expressions.
1374  return ParsePostfixExpressionSuffix(move(Res));
1375}
1376
1377/// ParseParenExpression - This parses the unit that starts with a '(' token,
1378/// based on what is allowed by ExprType.  The actual thing parsed is returned
1379/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
1380/// not the parsed cast-expression.
1381///
1382///       primary-expression: [C99 6.5.1]
1383///         '(' expression ')'
1384/// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
1385///       postfix-expression: [C99 6.5.2]
1386///         '(' type-name ')' '{' initializer-list '}'
1387///         '(' type-name ')' '{' initializer-list ',' '}'
1388///       cast-expression: [C99 6.5.4]
1389///         '(' type-name ')' cast-expression
1390///
1391Parser::OwningExprResult
1392Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
1393                             TypeTy *TypeOfCast, TypeTy *&CastTy,
1394                             SourceLocation &RParenLoc) {
1395  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
1396  GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
1397  SourceLocation OpenLoc = ConsumeParen();
1398  OwningExprResult Result(Actions, true);
1399  bool isAmbiguousTypeId;
1400  CastTy = 0;
1401
1402  if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
1403    Diag(Tok, diag::ext_gnu_statement_expr);
1404    OwningStmtResult Stmt(ParseCompoundStatement(0, true));
1405    ExprType = CompoundStmt;
1406
1407    // If the substmt parsed correctly, build the AST node.
1408    if (!Stmt.isInvalid() && Tok.is(tok::r_paren))
1409      Result = Actions.ActOnStmtExpr(OpenLoc, move(Stmt), Tok.getLocation());
1410
1411  } else if (ExprType >= CompoundLiteral &&
1412             isTypeIdInParens(isAmbiguousTypeId)) {
1413
1414    // Otherwise, this is a compound literal expression or cast expression.
1415
1416    // In C++, if the type-id is ambiguous we disambiguate based on context.
1417    // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
1418    // in which case we should treat it as type-id.
1419    // if stopIfCastExpr is false, we need to determine the context past the
1420    // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
1421    if (isAmbiguousTypeId && !stopIfCastExpr)
1422      return ParseCXXAmbiguousParenExpression(ExprType, CastTy,
1423                                              OpenLoc, RParenLoc);
1424
1425    TypeResult Ty = ParseTypeName();
1426
1427    // Match the ')'.
1428    if (Tok.is(tok::r_paren))
1429      RParenLoc = ConsumeParen();
1430    else
1431      MatchRHSPunctuation(tok::r_paren, OpenLoc);
1432
1433    if (Tok.is(tok::l_brace)) {
1434      ExprType = CompoundLiteral;
1435      return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
1436    }
1437
1438    if (ExprType == CastExpr) {
1439      // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
1440
1441      if (Ty.isInvalid())
1442        return ExprError();
1443
1444      CastTy = Ty.get();
1445
1446      // Note that this doesn't parse the subsequent cast-expression, it just
1447      // returns the parsed type to the callee.
1448      if (stopIfCastExpr)
1449        return OwningExprResult(Actions);
1450
1451      // Reject the cast of super idiom in ObjC.
1452      if (Tok.is(tok::identifier) && getLang().ObjC1 &&
1453          Tok.getIdentifierInfo() == Ident_super &&
1454          CurScope->isInObjcMethodScope() &&
1455          GetLookAheadToken(1).isNot(tok::period)) {
1456        Diag(Tok.getLocation(), diag::err_illegal_super_cast)
1457          << SourceRange(OpenLoc, RParenLoc);
1458        return ExprError();
1459      }
1460
1461      // Parse the cast-expression that follows it next.
1462      // TODO: For cast expression with CastTy.
1463      Result = ParseCastExpression(false, false, CastTy);
1464      if (!Result.isInvalid())
1465        Result = Actions.ActOnCastExpr(CurScope, OpenLoc, CastTy, RParenLoc,
1466                                       move(Result));
1467      return move(Result);
1468    }
1469
1470    Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1471    return ExprError();
1472  } else if (TypeOfCast) {
1473    // Parse the expression-list.
1474    ExprVector ArgExprs(Actions);
1475    CommaLocsTy CommaLocs;
1476
1477    if (!ParseExpressionList(ArgExprs, CommaLocs)) {
1478      ExprType = SimpleExpr;
1479      Result = Actions.ActOnParenOrParenListExpr(OpenLoc, Tok.getLocation(),
1480                                          move_arg(ArgExprs), TypeOfCast);
1481    }
1482  } else {
1483    Result = ParseExpression();
1484    ExprType = SimpleExpr;
1485    if (!Result.isInvalid() && Tok.is(tok::r_paren))
1486      Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), move(Result));
1487  }
1488
1489  // Match the ')'.
1490  if (Result.isInvalid()) {
1491    SkipUntil(tok::r_paren);
1492    return ExprError();
1493  }
1494
1495  if (Tok.is(tok::r_paren))
1496    RParenLoc = ConsumeParen();
1497  else
1498    MatchRHSPunctuation(tok::r_paren, OpenLoc);
1499
1500  return move(Result);
1501}
1502
1503/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
1504/// and we are at the left brace.
1505///
1506///       postfix-expression: [C99 6.5.2]
1507///         '(' type-name ')' '{' initializer-list '}'
1508///         '(' type-name ')' '{' initializer-list ',' '}'
1509///
1510Parser::OwningExprResult
1511Parser::ParseCompoundLiteralExpression(TypeTy *Ty,
1512                                       SourceLocation LParenLoc,
1513                                       SourceLocation RParenLoc) {
1514  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
1515  if (!getLang().C99)   // Compound literals don't exist in C90.
1516    Diag(LParenLoc, diag::ext_c99_compound_literal);
1517  OwningExprResult Result = ParseInitializer();
1518  if (!Result.isInvalid() && Ty)
1519    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, move(Result));
1520  return move(Result);
1521}
1522
1523/// ParseStringLiteralExpression - This handles the various token types that
1524/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1525/// translation phase #6].
1526///
1527///       primary-expression: [C99 6.5.1]
1528///         string-literal
1529Parser::OwningExprResult Parser::ParseStringLiteralExpression() {
1530  assert(isTokenStringLiteral() && "Not a string literal!");
1531
1532  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
1533  // considered to be strings for concatenation purposes.
1534  llvm::SmallVector<Token, 4> StringToks;
1535
1536  do {
1537    StringToks.push_back(Tok);
1538    ConsumeStringToken();
1539  } while (isTokenStringLiteral());
1540
1541  // Pass the set of string tokens, ready for concatenation, to the actions.
1542  return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
1543}
1544
1545/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1546///
1547///       argument-expression-list:
1548///         assignment-expression
1549///         argument-expression-list , assignment-expression
1550///
1551/// [C++] expression-list:
1552/// [C++]   assignment-expression
1553/// [C++]   expression-list , assignment-expression
1554///
1555bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs,
1556                                 void (Action::*Completer)(Scope *S,
1557                                                           void *Data,
1558                                                           ExprTy **Args,
1559                                                           unsigned NumArgs),
1560                                 void *Data) {
1561  while (1) {
1562    if (Tok.is(tok::code_completion)) {
1563      if (Completer)
1564        (Actions.*Completer)(CurScope, Data, Exprs.data(), Exprs.size());
1565      ConsumeCodeCompletionToken();
1566    }
1567
1568    OwningExprResult Expr(ParseAssignmentExpression());
1569    if (Expr.isInvalid())
1570      return true;
1571
1572    Exprs.push_back(Expr.release());
1573
1574    if (Tok.isNot(tok::comma))
1575      return false;
1576    // Move to the next argument, remember where the comma was.
1577    CommaLocs.push_back(ConsumeToken());
1578  }
1579}
1580
1581/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
1582///
1583/// [clang] block-id:
1584/// [clang]   specifier-qualifier-list block-declarator
1585///
1586void Parser::ParseBlockId() {
1587  // Parse the specifier-qualifier-list piece.
1588  DeclSpec DS;
1589  ParseSpecifierQualifierList(DS);
1590
1591  // Parse the block-declarator.
1592  Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
1593  ParseDeclarator(DeclaratorInfo);
1594
1595  // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes.
1596  DeclaratorInfo.AddAttributes(DS.TakeAttributes(),
1597                               SourceLocation());
1598
1599  if (Tok.is(tok::kw___attribute)) {
1600    SourceLocation Loc;
1601    AttributeList *AttrList = ParseGNUAttributes(&Loc);
1602    DeclaratorInfo.AddAttributes(AttrList, Loc);
1603  }
1604
1605  // Inform sema that we are starting a block.
1606  Actions.ActOnBlockArguments(DeclaratorInfo, CurScope);
1607}
1608
1609/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
1610/// like ^(int x){ return x+1; }
1611///
1612///         block-literal:
1613/// [clang]   '^' block-args[opt] compound-statement
1614/// [clang]   '^' block-id compound-statement
1615/// [clang] block-args:
1616/// [clang]   '(' parameter-list ')'
1617///
1618Parser::OwningExprResult Parser::ParseBlockLiteralExpression() {
1619  assert(Tok.is(tok::caret) && "block literal starts with ^");
1620  SourceLocation CaretLoc = ConsumeToken();
1621
1622  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
1623                                "block literal parsing");
1624
1625  // Enter a scope to hold everything within the block.  This includes the
1626  // argument decls, decls within the compound expression, etc.  This also
1627  // allows determining whether a variable reference inside the block is
1628  // within or outside of the block.
1629  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
1630                              Scope::BreakScope | Scope::ContinueScope |
1631                              Scope::DeclScope);
1632
1633  // Inform sema that we are starting a block.
1634  Actions.ActOnBlockStart(CaretLoc, CurScope);
1635
1636  // Parse the return type if present.
1637  DeclSpec DS;
1638  Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
1639  // FIXME: Since the return type isn't actually parsed, it can't be used to
1640  // fill ParamInfo with an initial valid range, so do it manually.
1641  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
1642
1643  // If this block has arguments, parse them.  There is no ambiguity here with
1644  // the expression case, because the expression case requires a parameter list.
1645  if (Tok.is(tok::l_paren)) {
1646    ParseParenDeclarator(ParamInfo);
1647    // Parse the pieces after the identifier as if we had "int(...)".
1648    // SetIdentifier sets the source range end, but in this case we're past
1649    // that location.
1650    SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
1651    ParamInfo.SetIdentifier(0, CaretLoc);
1652    ParamInfo.SetRangeEnd(Tmp);
1653    if (ParamInfo.isInvalidType()) {
1654      // If there was an error parsing the arguments, they may have
1655      // tried to use ^(x+y) which requires an argument list.  Just
1656      // skip the whole block literal.
1657      Actions.ActOnBlockError(CaretLoc, CurScope);
1658      return ExprError();
1659    }
1660
1661    if (Tok.is(tok::kw___attribute)) {
1662      SourceLocation Loc;
1663      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1664      ParamInfo.AddAttributes(AttrList, Loc);
1665    }
1666
1667    // Inform sema that we are starting a block.
1668    Actions.ActOnBlockArguments(ParamInfo, CurScope);
1669  } else if (!Tok.is(tok::l_brace)) {
1670    ParseBlockId();
1671  } else {
1672    // Otherwise, pretend we saw (void).
1673    ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
1674                                                       SourceLocation(),
1675                                                       0, 0, 0,
1676                                                       false, SourceLocation(),
1677                                                       false, 0, 0, 0,
1678                                                       CaretLoc, CaretLoc,
1679                                                       ParamInfo),
1680                          CaretLoc);
1681
1682    if (Tok.is(tok::kw___attribute)) {
1683      SourceLocation Loc;
1684      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1685      ParamInfo.AddAttributes(AttrList, Loc);
1686    }
1687
1688    // Inform sema that we are starting a block.
1689    Actions.ActOnBlockArguments(ParamInfo, CurScope);
1690  }
1691
1692
1693  OwningExprResult Result(Actions, true);
1694  if (!Tok.is(tok::l_brace)) {
1695    // Saw something like: ^expr
1696    Diag(Tok, diag::err_expected_expression);
1697    Actions.ActOnBlockError(CaretLoc, CurScope);
1698    return ExprError();
1699  }
1700
1701  OwningStmtResult Stmt(ParseCompoundStatementBody());
1702  if (!Stmt.isInvalid())
1703    Result = Actions.ActOnBlockStmtExpr(CaretLoc, move(Stmt), CurScope);
1704  else
1705    Actions.ActOnBlockError(CaretLoc, CurScope);
1706  return move(Result);
1707}
1708