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