ParseExpr.cpp revision 312eadb832cab4497a069409954500d8192b8f0d
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 ...[opt]
176///         expression ',' assignment-expression ...[opt]
177///
178/// \param Primary if non-empty, an already-parsed expression that will be used
179/// as the first primary expression.
180ExprResult Parser::ParseExpression(ExprResult Primary) {
181  ExprResult LHS(ParseAssignmentExpression(Primary));
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  return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
194}
195
196/// This routine is called when a leading '__extension__' is seen and
197/// consumed.  This is necessary because the token gets consumed in the
198/// process of disambiguating between an expression and a declaration.
199ExprResult
200Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
201  ExprResult LHS(true);
202  {
203    // Silence extension warnings in the sub-expression
204    ExtensionRAIIObject O(Diags);
205
206    LHS = ParseCastExpression(false);
207  }
208
209  if (!LHS.isInvalid())
210    LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
211                               LHS.take());
212
213  return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
214}
215
216/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
217///
218/// \param Primary if non-empty, an already-parsed expression that will be used
219/// as the first primary expression.
220ExprResult Parser::ParseAssignmentExpression(ExprResult Primary) {
221  if (Tok.is(tok::code_completion)) {
222    if (Primary.isUsable())
223      Actions.CodeCompletePostfixExpression(getCurScope(), Primary);
224    else
225      Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
226    ConsumeCodeCompletionToken();
227  }
228
229  if (!Primary.isUsable() && Tok.is(tok::kw_throw))
230    return ParseThrowExpression();
231
232  ExprResult LHS;
233  if (Primary.get() || Primary.isInvalid())
234    LHS = ParsePostfixExpressionSuffix(Primary);
235  else
236    LHS = ParseCastExpression(false, false, ParsedType());
237
238  return ParseRHSOfBinaryExpression(move(LHS), prec::Assignment);
239}
240
241/// ParseAssignmentExprWithObjCMessageExprStart - Parse an assignment expression
242/// where part of an objc message send has already been parsed.  In this case
243/// LBracLoc indicates the location of the '[' of the message send, and either
244/// ReceiverName or ReceiverExpr is non-null indicating the receiver of the
245/// message.
246///
247/// Since this handles full assignment-expression's, it handles postfix
248/// expressions and other binary operators for these expressions as well.
249ExprResult
250Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
251                                                    SourceLocation SuperLoc,
252                                                    ParsedType ReceiverType,
253                                                    Expr *ReceiverExpr) {
254  ExprResult R
255    = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
256                                     ReceiverType, ReceiverExpr);
257  R = ParsePostfixExpressionSuffix(R);
258  return ParseRHSOfBinaryExpression(R, prec::Assignment);
259}
260
261
262ExprResult Parser::ParseConstantExpression() {
263  // C++ [basic.def.odr]p2:
264  //   An expression is potentially evaluated unless it appears where an
265  //   integral constant expression is required (see 5.19) [...].
266  EnterExpressionEvaluationContext Unevaluated(Actions,
267                                               Sema::Unevaluated);
268
269  ExprResult LHS(ParseCastExpression(false));
270  return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
271}
272
273/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
274/// LHS and has a precedence of at least MinPrec.
275ExprResult
276Parser::ParseRHSOfBinaryExpression(ExprResult 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    ExprResult TernaryMiddle(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          LHS = ExprError();
307          TernaryMiddle = 0;
308        }
309      } else {
310        // Special case handling of "X ? Y : Z" where Y is empty:
311        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
312        TernaryMiddle = 0;
313        Diag(Tok, diag::ext_gnu_conditional_expr);
314      }
315
316      if (Tok.is(tok::colon)) {
317        // Eat the colon.
318        ColonLoc = ConsumeToken();
319      } else {
320        // Otherwise, we're missing a ':'.  Assume that this was a typo that the
321        // user forgot.  If we're not in a macro instantion, we can suggest a
322        // fixit hint.  If there were two spaces before the current token,
323        // suggest inserting the colon in between them, otherwise insert ": ".
324        SourceLocation FILoc = Tok.getLocation();
325        const char *FIText = ": ";
326        if (FILoc.isFileID()) {
327          const SourceManager &SM = PP.getSourceManager();
328          bool IsInvalid = false;
329          const char *SourcePtr =
330            SM.getCharacterData(FILoc.getFileLocWithOffset(-1), &IsInvalid);
331          if (!IsInvalid && *SourcePtr == ' ') {
332            SourcePtr =
333              SM.getCharacterData(FILoc.getFileLocWithOffset(-2), &IsInvalid);
334            if (!IsInvalid && *SourcePtr == ' ') {
335              FILoc = FILoc.getFileLocWithOffset(-1);
336              FIText = ":";
337            }
338          }
339        }
340
341        Diag(Tok, diag::err_expected_colon)
342          << FixItHint::CreateInsertion(FILoc, FIText);
343        Diag(OpToken, diag::note_matching) << "?";
344        ColonLoc = Tok.getLocation();
345      }
346    }
347
348    // Code completion for the right-hand side of an assignment expression
349    // goes through a special hook that takes the left-hand side into account.
350    if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
351      Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
352      ConsumeCodeCompletionToken();
353      return ExprError();
354    }
355
356    // Parse another leaf here for the RHS of the operator.
357    // ParseCastExpression works here because all RHS expressions in C have it
358    // as a prefix, at least. However, in C++, an assignment-expression could
359    // be a throw-expression, which is not a valid cast-expression.
360    // Therefore we need some special-casing here.
361    // Also note that the third operand of the conditional operator is
362    // an assignment-expression in C++.
363    ExprResult RHS;
364    if (getLang().CPlusPlus && NextTokPrec <= prec::Conditional)
365      RHS = ParseAssignmentExpression();
366    else
367      RHS = ParseCastExpression(false);
368
369    if (RHS.isInvalid())
370      LHS = ExprError();
371
372    // Remember the precedence of this operator and get the precedence of the
373    // operator immediately to the right of the RHS.
374    prec::Level ThisPrec = NextTokPrec;
375    NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
376                                     getLang().CPlusPlus0x);
377
378    // Assignment and conditional expressions are right-associative.
379    bool isRightAssoc = ThisPrec == prec::Conditional ||
380                        ThisPrec == prec::Assignment;
381
382    // Get the precedence of the operator to the right of the RHS.  If it binds
383    // more tightly with RHS than we do, evaluate it completely first.
384    if (ThisPrec < NextTokPrec ||
385        (ThisPrec == NextTokPrec && isRightAssoc)) {
386      // If this is left-associative, only parse things on the RHS that bind
387      // more tightly than the current operator.  If it is left-associative, it
388      // is okay, to bind exactly as tightly.  For example, compile A=B=C=D as
389      // A=(B=(C=D)), where each paren is a level of recursion here.
390      // The function takes ownership of the RHS.
391      RHS = ParseRHSOfBinaryExpression(RHS,
392                            static_cast<prec::Level>(ThisPrec + !isRightAssoc));
393
394      if (RHS.isInvalid())
395        LHS = ExprError();
396
397      NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
398                                       getLang().CPlusPlus0x);
399    }
400    assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
401
402    if (!LHS.isInvalid()) {
403      // Combine the LHS and RHS into the LHS (e.g. build AST).
404      if (TernaryMiddle.isInvalid()) {
405        // If we're using '>>' as an operator within a template
406        // argument list (in C++98), suggest the addition of
407        // parentheses so that the code remains well-formed in C++0x.
408        if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
409          SuggestParentheses(OpToken.getLocation(),
410                             diag::warn_cxx0x_right_shift_in_template_arg,
411                         SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
412                                     Actions.getExprRange(RHS.get()).getEnd()));
413
414        LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
415                                 OpToken.getKind(), LHS.take(), RHS.take());
416      } else
417        LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
418                                         LHS.take(), TernaryMiddle.take(),
419                                         RHS.take());
420    }
421  }
422}
423
424/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
425/// true, parse a unary-expression. isAddressOfOperand exists because an
426/// id-expression that is the operand of address-of gets special treatment
427/// due to member pointers.
428///
429ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
430                                       bool isAddressOfOperand,
431                                       ParsedType TypeOfCast) {
432  bool NotCastExpr;
433  ExprResult Res = ParseCastExpression(isUnaryExpression,
434                                       isAddressOfOperand,
435                                       NotCastExpr,
436                                       TypeOfCast);
437  if (NotCastExpr)
438    Diag(Tok, diag::err_expected_expression);
439  return move(Res);
440}
441
442/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
443/// true, parse a unary-expression. isAddressOfOperand exists because an
444/// id-expression that is the operand of address-of gets special treatment
445/// due to member pointers. NotCastExpr is set to true if the token is not the
446/// start of a cast-expression, and no diagnostic is emitted in this case.
447///
448///       cast-expression: [C99 6.5.4]
449///         unary-expression
450///         '(' type-name ')' cast-expression
451///
452///       unary-expression:  [C99 6.5.3]
453///         postfix-expression
454///         '++' unary-expression
455///         '--' unary-expression
456///         unary-operator cast-expression
457///         'sizeof' unary-expression
458///         'sizeof' '(' type-name ')'
459/// [C++0x] 'sizeof' '...' '(' identifier ')'
460/// [GNU]   '__alignof' unary-expression
461/// [GNU]   '__alignof' '(' type-name ')'
462/// [C++0x] 'alignof' '(' type-id ')'
463/// [GNU]   '&&' identifier
464/// [C++]   new-expression
465/// [C++]   delete-expression
466/// [C++0x] 'noexcept' '(' expression ')'
467///
468///       unary-operator: one of
469///         '&'  '*'  '+'  '-'  '~'  '!'
470/// [GNU]   '__extension__'  '__real'  '__imag'
471///
472///       primary-expression: [C99 6.5.1]
473/// [C99]   identifier
474/// [C++]   id-expression
475///         constant
476///         string-literal
477/// [C++]   boolean-literal  [C++ 2.13.5]
478/// [C++0x] 'nullptr'        [C++0x 2.14.7]
479///         '(' expression ')'
480/// [C1X]   generic-selection
481///         '__func__'        [C99 6.4.2.2]
482/// [GNU]   '__FUNCTION__'
483/// [GNU]   '__PRETTY_FUNCTION__'
484/// [GNU]   '(' compound-statement ')'
485/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
486/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
487/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
488///                                     assign-expr ')'
489/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
490/// [GNU]   '__null'
491/// [OBJC]  '[' objc-message-expr ']'
492/// [OBJC]  '@selector' '(' objc-selector-arg ')'
493/// [OBJC]  '@protocol' '(' identifier ')'
494/// [OBJC]  '@encode' '(' type-name ')'
495/// [OBJC]  objc-string-literal
496/// [C++]   simple-type-specifier '(' expression-list[opt] ')'      [C++ 5.2.3]
497/// [C++]   typename-specifier '(' expression-list[opt] ')'         [C++ 5.2.3]
498/// [C++]   'const_cast' '<' type-name '>' '(' expression ')'       [C++ 5.2p1]
499/// [C++]   'dynamic_cast' '<' type-name '>' '(' expression ')'     [C++ 5.2p1]
500/// [C++]   'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
501/// [C++]   'static_cast' '<' type-name '>' '(' expression ')'      [C++ 5.2p1]
502/// [C++]   'typeid' '(' expression ')'                             [C++ 5.2p1]
503/// [C++]   'typeid' '(' type-id ')'                                [C++ 5.2p1]
504/// [C++]   'this'          [C++ 9.3.2]
505/// [G++]   unary-type-trait '(' type-id ')'
506/// [G++]   binary-type-trait '(' type-id ',' type-id ')'           [TODO]
507/// [clang] '^' block-literal
508///
509///       constant: [C99 6.4.4]
510///         integer-constant
511///         floating-constant
512///         enumeration-constant -> identifier
513///         character-constant
514///
515///       id-expression: [C++ 5.1]
516///                   unqualified-id
517///                   qualified-id
518///
519///       unqualified-id: [C++ 5.1]
520///                   identifier
521///                   operator-function-id
522///                   conversion-function-id
523///                   '~' class-name
524///                   template-id
525///
526///       new-expression: [C++ 5.3.4]
527///                   '::'[opt] 'new' new-placement[opt] new-type-id
528///                                     new-initializer[opt]
529///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
530///                                     new-initializer[opt]
531///
532///       delete-expression: [C++ 5.3.5]
533///                   '::'[opt] 'delete' cast-expression
534///                   '::'[opt] 'delete' '[' ']' cast-expression
535///
536/// [GNU] unary-type-trait:
537///                   '__has_nothrow_assign'
538///                   '__has_nothrow_copy'
539///                   '__has_nothrow_constructor'
540///                   '__has_trivial_assign'                  [TODO]
541///                   '__has_trivial_copy'                    [TODO]
542///                   '__has_trivial_constructor'
543///                   '__has_trivial_destructor'
544///                   '__has_virtual_destructor'
545///                   '__is_abstract'                         [TODO]
546///                   '__is_class'
547///                   '__is_empty'                            [TODO]
548///                   '__is_enum'
549///                   '__is_pod'
550///                   '__is_polymorphic'
551///                   '__is_trivial'
552///                   '__is_union'
553///
554///       binary-type-trait:
555/// [GNU]             '__is_base_of'
556/// [MS]              '__is_convertible_to'
557///
558ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
559                                       bool isAddressOfOperand,
560                                       bool &NotCastExpr,
561                                       ParsedType TypeOfCast) {
562  ExprResult Res;
563  tok::TokenKind SavedKind = Tok.getKind();
564  NotCastExpr = false;
565
566  // This handles all of cast-expression, unary-expression, postfix-expression,
567  // and primary-expression.  We handle them together like this for efficiency
568  // and to simplify handling of an expression starting with a '(' token: which
569  // may be one of a parenthesized expression, cast-expression, compound literal
570  // expression, or statement expression.
571  //
572  // If the parsed tokens consist of a primary-expression, the cases below
573  // break out of the switch;  at the end we call ParsePostfixExpressionSuffix
574  // to handle the postfix expression suffixes.  Cases that cannot be followed
575  // by postfix exprs should return without invoking
576  // ParsePostfixExpressionSuffix.
577  switch (SavedKind) {
578  case tok::l_paren: {
579    // If this expression is limited to being a unary-expression, the parent can
580    // not start a cast expression.
581    ParenParseOption ParenExprType =
582      (isUnaryExpression && !getLang().CPlusPlus)? CompoundLiteral : CastExpr;
583    ParsedType CastTy;
584    SourceLocation RParenLoc;
585
586    {
587      // The inside of the parens don't need to be a colon protected scope, and
588      // isn't immediately a message send.
589      ColonProtectionRAIIObject X(*this, false);
590
591      Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
592                                 TypeOfCast, CastTy, RParenLoc);
593    }
594
595    switch (ParenExprType) {
596    case SimpleExpr:   break;    // Nothing else to do.
597    case CompoundStmt: break;  // Nothing else to do.
598    case CompoundLiteral:
599      // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
600      // postfix-expression exist, parse them now.
601      break;
602    case CastExpr:
603      // We have parsed the cast-expression and no postfix-expr pieces are
604      // following.
605      return move(Res);
606    }
607
608    break;
609  }
610
611    // primary-expression
612  case tok::numeric_constant:
613    // constant: integer-constant
614    // constant: floating-constant
615
616    Res = Actions.ActOnNumericConstant(Tok);
617    ConsumeToken();
618    break;
619
620  case tok::kw_true:
621  case tok::kw_false:
622    return ParseCXXBoolLiteral();
623
624  case tok::kw_nullptr:
625    return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
626
627  case tok::identifier: {      // primary-expression: identifier
628                               // unqualified-id: identifier
629                               // constant: enumeration-constant
630    // Turn a potentially qualified name into a annot_typename or
631    // annot_cxxscope if it would be valid.  This handles things like x::y, etc.
632    if (getLang().CPlusPlus) {
633      // Avoid the unnecessary parse-time lookup in the common case
634      // where the syntax forbids a type.
635      const Token &Next = NextToken();
636      if (Next.is(tok::coloncolon) ||
637          (!ColonIsSacred && Next.is(tok::colon)) ||
638          Next.is(tok::less) ||
639          Next.is(tok::l_paren)) {
640        // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
641        if (TryAnnotateTypeOrScopeToken())
642          return ExprError();
643        if (!Tok.is(tok::identifier))
644          return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
645      }
646    }
647
648    // Consume the identifier so that we can see if it is followed by a '(' or
649    // '.'.
650    IdentifierInfo &II = *Tok.getIdentifierInfo();
651    SourceLocation ILoc = ConsumeToken();
652
653    // Support 'Class.property' and 'super.property' notation.
654    if (getLang().ObjC1 && Tok.is(tok::period) &&
655        (Actions.getTypeName(II, ILoc, getCurScope()) ||
656         // Allow the base to be 'super' if in an objc-method.
657         (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
658      ConsumeToken();
659
660      if (Tok.isNot(tok::identifier)) {
661        Diag(Tok, diag::err_expected_property_name);
662        return ExprError();
663      }
664      IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
665      SourceLocation PropertyLoc = ConsumeToken();
666
667      Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
668                                              ILoc, PropertyLoc);
669      break;
670    }
671
672    // In an Objective-C method, if we have "super" followed by an identifier,
673    // the token sequence is ill-formed. However, if there's a ':' or ']' after
674    // that identifier, this is probably a message send with a missing open
675    // bracket. Treat it as such.
676    if (getLang().ObjC1 && &II == Ident_super && !InMessageExpression &&
677        getCurScope()->isInObjcMethodScope() &&
678        ((Tok.is(tok::identifier) &&
679         (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
680         Tok.is(tok::code_completion))) {
681      Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
682                                           0);
683      break;
684    }
685
686    // If we have an Objective-C class name followed by an identifier
687    // and either ':' or ']', this is an Objective-C class message
688    // send that's missing the opening '['. Recovery
689    // appropriately. Also take this path if we're performing code
690    // completion after an Objective-C class name.
691    if (getLang().ObjC1 &&
692        ((Tok.is(tok::identifier) && !InMessageExpression) ||
693         Tok.is(tok::code_completion))) {
694      const Token& Next = NextToken();
695      if (Tok.is(tok::code_completion) ||
696          Next.is(tok::colon) || Next.is(tok::r_square))
697        if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
698          if (Typ.get()->isObjCObjectOrInterfaceType()) {
699            // Fake up a Declarator to use with ActOnTypeName.
700            DeclSpec DS(AttrFactory);
701            DS.SetRangeStart(ILoc);
702            DS.SetRangeEnd(ILoc);
703            const char *PrevSpec = 0;
704            unsigned DiagID;
705            DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ);
706
707            Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
708            TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
709                                                  DeclaratorInfo);
710            if (Ty.isInvalid())
711              break;
712
713            Res = ParseObjCMessageExpressionBody(SourceLocation(),
714                                                 SourceLocation(),
715                                                 Ty.get(), 0);
716            break;
717          }
718    }
719
720    // Make sure to pass down the right value for isAddressOfOperand.
721    if (isAddressOfOperand && isPostfixExpressionSuffixStart())
722      isAddressOfOperand = false;
723
724    // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
725    // need to know whether or not this identifier is a function designator or
726    // not.
727    UnqualifiedId Name;
728    CXXScopeSpec ScopeSpec;
729    Name.setIdentifier(&II, ILoc);
730    Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, Name,
731                                    Tok.is(tok::l_paren), isAddressOfOperand);
732    break;
733  }
734  case tok::char_constant:     // constant: character-constant
735    Res = Actions.ActOnCharacterConstant(Tok);
736    ConsumeToken();
737    break;
738  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
739  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
740  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
741    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
742    ConsumeToken();
743    break;
744  case tok::string_literal:    // primary-expression: string-literal
745  case tok::wide_string_literal:
746    Res = ParseStringLiteralExpression();
747    break;
748  case tok::kw__Generic:   // primary-expression: generic-selection [C1X 6.5.1]
749    Res = ParseGenericSelectionExpression();
750    break;
751  case tok::kw___builtin_va_arg:
752  case tok::kw___builtin_offsetof:
753  case tok::kw___builtin_choose_expr:
754    return ParseBuiltinPrimaryExpression();
755  case tok::kw___null:
756    return Actions.ActOnGNUNullExpr(ConsumeToken());
757    break;
758  case tok::plusplus:      // unary-expression: '++' unary-expression [C99]
759  case tok::minusminus: {  // unary-expression: '--' unary-expression [C99]
760    // C++ [expr.unary] has:
761    //   unary-expression:
762    //     ++ cast-expression
763    //     -- cast-expression
764    SourceLocation SavedLoc = ConsumeToken();
765    Res = ParseCastExpression(!getLang().CPlusPlus);
766    if (!Res.isInvalid())
767      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
768    return move(Res);
769  }
770  case tok::amp: {         // unary-expression: '&' cast-expression
771    // Special treatment because of member pointers
772    SourceLocation SavedLoc = ConsumeToken();
773    Res = ParseCastExpression(false, true);
774    if (!Res.isInvalid())
775      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
776    return move(Res);
777  }
778
779  case tok::star:          // unary-expression: '*' cast-expression
780  case tok::plus:          // unary-expression: '+' cast-expression
781  case tok::minus:         // unary-expression: '-' cast-expression
782  case tok::tilde:         // unary-expression: '~' cast-expression
783  case tok::exclaim:       // unary-expression: '!' cast-expression
784  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
785  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
786    SourceLocation SavedLoc = ConsumeToken();
787    Res = ParseCastExpression(false);
788    if (!Res.isInvalid())
789      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
790    return move(Res);
791  }
792
793  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
794    // __extension__ silences extension warnings in the subexpression.
795    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
796    SourceLocation SavedLoc = ConsumeToken();
797    Res = ParseCastExpression(false);
798    if (!Res.isInvalid())
799      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
800    return move(Res);
801  }
802  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
803                           // unary-expression: 'sizeof' '(' type-name ')'
804  case tok::kw_alignof:
805  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
806                           // unary-expression: '__alignof' '(' type-name ')'
807                           // unary-expression: 'alignof' '(' type-id ')'
808  case tok::kw_vec_step:   // unary-expression: OpenCL 'vec_step' expression
809    return ParseUnaryExprOrTypeTraitExpression();
810  case tok::ampamp: {      // unary-expression: '&&' identifier
811    SourceLocation AmpAmpLoc = ConsumeToken();
812    if (Tok.isNot(tok::identifier))
813      return ExprError(Diag(Tok, diag::err_expected_ident));
814
815    if (getCurScope()->getFnParent() == 0)
816      return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
817
818    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
819    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
820                                                Tok.getLocation());
821    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
822    ConsumeToken();
823    return move(Res);
824  }
825  case tok::kw_const_cast:
826  case tok::kw_dynamic_cast:
827  case tok::kw_reinterpret_cast:
828  case tok::kw_static_cast:
829    Res = ParseCXXCasts();
830    break;
831  case tok::kw_typeid:
832    Res = ParseCXXTypeid();
833    break;
834  case tok::kw___uuidof:
835    Res = ParseCXXUuidof();
836    break;
837  case tok::kw_this:
838    Res = ParseCXXThis();
839    break;
840
841  case tok::annot_typename:
842    if (isStartOfObjCClassMessageMissingOpenBracket()) {
843      ParsedType Type = getTypeAnnotation(Tok);
844
845      // Fake up a Declarator to use with ActOnTypeName.
846      DeclSpec DS(AttrFactory);
847      DS.SetRangeStart(Tok.getLocation());
848      DS.SetRangeEnd(Tok.getLastLoc());
849
850      const char *PrevSpec = 0;
851      unsigned DiagID;
852      DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
853                         PrevSpec, DiagID, Type);
854
855      Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
856      TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
857      if (Ty.isInvalid())
858        break;
859
860      ConsumeToken();
861      Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
862                                           Ty.get(), 0);
863      break;
864    }
865    // Fall through
866
867  case tok::kw_char:
868  case tok::kw_wchar_t:
869  case tok::kw_char16_t:
870  case tok::kw_char32_t:
871  case tok::kw_bool:
872  case tok::kw_short:
873  case tok::kw_int:
874  case tok::kw_long:
875  case tok::kw_signed:
876  case tok::kw_unsigned:
877  case tok::kw_float:
878  case tok::kw_double:
879  case tok::kw_void:
880  case tok::kw_typename:
881  case tok::kw_typeof:
882  case tok::kw___vector: {
883    if (!getLang().CPlusPlus) {
884      Diag(Tok, diag::err_expected_expression);
885      return ExprError();
886    }
887
888    if (SavedKind == tok::kw_typename) {
889      // postfix-expression: typename-specifier '(' expression-list[opt] ')'
890      if (TryAnnotateTypeOrScopeToken())
891        return ExprError();
892    }
893
894    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
895    //
896    DeclSpec DS(AttrFactory);
897    ParseCXXSimpleTypeSpecifier(DS);
898    if (Tok.isNot(tok::l_paren))
899      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
900                         << DS.getSourceRange());
901
902    Res = ParseCXXTypeConstructExpression(DS);
903    break;
904  }
905
906  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
907    // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
908    // (We can end up in this situation after tentative parsing.)
909    if (TryAnnotateTypeOrScopeToken())
910      return ExprError();
911    if (!Tok.is(tok::annot_cxxscope))
912      return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
913                                 NotCastExpr, TypeOfCast);
914
915    Token Next = NextToken();
916    if (Next.is(tok::annot_template_id)) {
917      TemplateIdAnnotation *TemplateId
918        = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue());
919      if (TemplateId->Kind == TNK_Type_template) {
920        // We have a qualified template-id that we know refers to a
921        // type, translate it into a type and continue parsing as a
922        // cast expression.
923        CXXScopeSpec SS;
924        ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
925        AnnotateTemplateIdTokenAsType();
926        return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
927                                   NotCastExpr, TypeOfCast);
928      }
929    }
930
931    // Parse as an id-expression.
932    Res = ParseCXXIdExpression(isAddressOfOperand);
933    break;
934  }
935
936  case tok::annot_template_id: { // [C++]          template-id
937    TemplateIdAnnotation *TemplateId
938      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
939    if (TemplateId->Kind == TNK_Type_template) {
940      // We have a template-id that we know refers to a type,
941      // translate it into a type and continue parsing as a cast
942      // expression.
943      AnnotateTemplateIdTokenAsType();
944      return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
945                                 NotCastExpr, TypeOfCast);
946    }
947
948    // Fall through to treat the template-id as an id-expression.
949  }
950
951  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
952    Res = ParseCXXIdExpression(isAddressOfOperand);
953    break;
954
955  case tok::coloncolon: {
956    // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
957    // annotates the token, tail recurse.
958    if (TryAnnotateTypeOrScopeToken())
959      return ExprError();
960    if (!Tok.is(tok::coloncolon))
961      return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
962
963    // ::new -> [C++] new-expression
964    // ::delete -> [C++] delete-expression
965    SourceLocation CCLoc = ConsumeToken();
966    if (Tok.is(tok::kw_new))
967      return ParseCXXNewExpression(true, CCLoc);
968    if (Tok.is(tok::kw_delete))
969      return ParseCXXDeleteExpression(true, CCLoc);
970
971    // This is not a type name or scope specifier, it is an invalid expression.
972    Diag(CCLoc, diag::err_expected_expression);
973    return ExprError();
974  }
975
976  case tok::kw_new: // [C++] new-expression
977    return ParseCXXNewExpression(false, Tok.getLocation());
978
979  case tok::kw_delete: // [C++] delete-expression
980    return ParseCXXDeleteExpression(false, Tok.getLocation());
981
982  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
983    SourceLocation KeyLoc = ConsumeToken();
984    SourceLocation LParen = Tok.getLocation();
985    if (ExpectAndConsume(tok::l_paren,
986                         diag::err_expected_lparen_after, "noexcept"))
987      return ExprError();
988    // C++ [expr.unary.noexcept]p1:
989    //   The noexcept operator determines whether the evaluation of its operand,
990    //   which is an unevaluated operand, can throw an exception.
991    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
992    ExprResult Result = ParseExpression();
993    SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
994    if (!Result.isInvalid())
995      Result = Actions.ActOnNoexceptExpr(KeyLoc, LParen, Result.take(), RParen);
996    return move(Result);
997  }
998
999  case tok::kw___is_abstract: // [GNU] unary-type-trait
1000  case tok::kw___is_class:
1001  case tok::kw___is_empty:
1002  case tok::kw___is_enum:
1003  case tok::kw___is_literal:
1004  case tok::kw___is_literal_type:
1005  case tok::kw___is_pod:
1006  case tok::kw___is_polymorphic:
1007  case tok::kw___is_trivial:
1008  case tok::kw___is_union:
1009  case tok::kw___has_trivial_constructor:
1010  case tok::kw___has_trivial_copy:
1011  case tok::kw___has_trivial_assign:
1012  case tok::kw___has_trivial_destructor:
1013  case tok::kw___has_nothrow_assign:
1014  case tok::kw___has_nothrow_copy:
1015  case tok::kw___has_nothrow_constructor:
1016  case tok::kw___has_virtual_destructor:
1017    return ParseUnaryTypeTrait();
1018
1019  case tok::kw___builtin_types_compatible_p:
1020  case tok::kw___is_base_of:
1021  case tok::kw___is_convertible_to:
1022    return ParseBinaryTypeTrait();
1023
1024  case tok::at: {
1025    SourceLocation AtLoc = ConsumeToken();
1026    return ParseObjCAtExpression(AtLoc);
1027  }
1028  case tok::caret:
1029    return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
1030  case tok::code_completion:
1031    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1032    ConsumeCodeCompletionToken();
1033    return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1034                               NotCastExpr, TypeOfCast);
1035  case tok::l_square:
1036    // These can be followed by postfix-expr pieces.
1037    if (getLang().ObjC1)
1038      return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
1039    // FALL THROUGH.
1040  default:
1041    NotCastExpr = true;
1042    return ExprError();
1043  }
1044
1045  // These can be followed by postfix-expr pieces.
1046  return ParsePostfixExpressionSuffix(Res);
1047}
1048
1049/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
1050/// is parsed, this method parses any suffixes that apply.
1051///
1052///       postfix-expression: [C99 6.5.2]
1053///         primary-expression
1054///         postfix-expression '[' expression ']'
1055///         postfix-expression '(' argument-expression-list[opt] ')'
1056///         postfix-expression '.' identifier
1057///         postfix-expression '->' identifier
1058///         postfix-expression '++'
1059///         postfix-expression '--'
1060///         '(' type-name ')' '{' initializer-list '}'
1061///         '(' type-name ')' '{' initializer-list ',' '}'
1062///
1063///       argument-expression-list: [C99 6.5.2]
1064///         argument-expression ...[opt]
1065///         argument-expression-list ',' assignment-expression ...[opt]
1066///
1067ExprResult
1068Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1069  // Now that the primary-expression piece of the postfix-expression has been
1070  // parsed, see if there are any postfix-expression pieces here.
1071  SourceLocation Loc;
1072  while (1) {
1073    switch (Tok.getKind()) {
1074    case tok::code_completion:
1075      if (InMessageExpression)
1076        return move(LHS);
1077
1078      Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1079      ConsumeCodeCompletionToken();
1080      LHS = ExprError();
1081      break;
1082
1083    case tok::identifier:
1084      // If we see identifier: after an expression, and we're not already in a
1085      // message send, then this is probably a message send with a missing
1086      // opening bracket '['.
1087      if (getLang().ObjC1 && !InMessageExpression &&
1088          (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1089        LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1090                                             ParsedType(), LHS.get());
1091        break;
1092      }
1093
1094      // Fall through; this isn't a message send.
1095
1096    default:  // Not a postfix-expression suffix.
1097      return move(LHS);
1098    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
1099      // If we have a array postfix expression that starts on a new line and
1100      // Objective-C is enabled, it is highly likely that the user forgot a
1101      // semicolon after the base expression and that the array postfix-expr is
1102      // actually another message send.  In this case, do some look-ahead to see
1103      // if the contents of the square brackets are obviously not a valid
1104      // expression and recover by pretending there is no suffix.
1105      if (getLang().ObjC1 && Tok.isAtStartOfLine() &&
1106          isSimpleObjCMessageExpression())
1107        return move(LHS);
1108
1109      Loc = ConsumeBracket();
1110      ExprResult Idx(ParseExpression());
1111
1112      SourceLocation RLoc = Tok.getLocation();
1113
1114      if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
1115        LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc,
1116                                              Idx.take(), RLoc);
1117      } else
1118        LHS = ExprError();
1119
1120      // Match the ']'.
1121      MatchRHSPunctuation(tok::r_square, Loc);
1122      break;
1123    }
1124
1125    case tok::l_paren:         // p-e: p-e '(' argument-expression-list[opt] ')'
1126    case tok::lesslessless: {  // p-e: p-e '<<<' argument-expression-list '>>>'
1127                               //   '(' argument-expression-list[opt] ')'
1128      tok::TokenKind OpKind = Tok.getKind();
1129      InMessageExpressionRAIIObject InMessage(*this, false);
1130
1131      Expr *ExecConfig = 0;
1132
1133      if (OpKind == tok::lesslessless) {
1134        ExprVector ExecConfigExprs(Actions);
1135        CommaLocsTy ExecConfigCommaLocs;
1136        SourceLocation LLLLoc, GGGLoc;
1137
1138        LLLLoc = ConsumeToken();
1139
1140        if (ParseExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1141          LHS = ExprError();
1142        }
1143
1144        if (LHS.isInvalid()) {
1145          SkipUntil(tok::greatergreatergreater);
1146        } else if (Tok.isNot(tok::greatergreatergreater)) {
1147          MatchRHSPunctuation(tok::greatergreatergreater, LLLLoc);
1148          LHS = ExprError();
1149        } else {
1150          GGGLoc = ConsumeToken();
1151        }
1152
1153        if (!LHS.isInvalid()) {
1154          if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, ""))
1155            LHS = ExprError();
1156          else
1157            Loc = PrevTokLocation;
1158        }
1159
1160        if (!LHS.isInvalid()) {
1161          ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1162                                     LLLLoc, move_arg(ExecConfigExprs), GGGLoc);
1163          if (ECResult.isInvalid())
1164            LHS = ExprError();
1165          else
1166            ExecConfig = ECResult.get();
1167        }
1168      } else {
1169        Loc = ConsumeParen();
1170      }
1171
1172      ExprVector ArgExprs(Actions);
1173      CommaLocsTy CommaLocs;
1174
1175      if (Tok.is(tok::code_completion)) {
1176        Actions.CodeCompleteCall(getCurScope(), LHS.get(), 0, 0);
1177        ConsumeCodeCompletionToken();
1178      }
1179
1180      if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1181        if (Tok.isNot(tok::r_paren)) {
1182          if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall,
1183                                  LHS.get())) {
1184            SkipUntil(tok::r_paren);
1185            LHS = ExprError();
1186          }
1187        }
1188      }
1189
1190      // Match the ')'.
1191      if (LHS.isInvalid()) {
1192        SkipUntil(tok::r_paren);
1193      } else if (Tok.isNot(tok::r_paren)) {
1194        MatchRHSPunctuation(tok::r_paren, Loc);
1195        LHS = ExprError();
1196      } else {
1197        assert((ArgExprs.size() == 0 ||
1198                ArgExprs.size()-1 == CommaLocs.size())&&
1199               "Unexpected number of commas!");
1200        LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc,
1201                                    move_arg(ArgExprs), Tok.getLocation(),
1202                                    ExecConfig);
1203        ConsumeParen();
1204      }
1205
1206      break;
1207    }
1208    case tok::arrow:
1209    case tok::period: {
1210      // postfix-expression: p-e '->' template[opt] id-expression
1211      // postfix-expression: p-e '.' template[opt] id-expression
1212      tok::TokenKind OpKind = Tok.getKind();
1213      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
1214
1215      CXXScopeSpec SS;
1216      ParsedType ObjectType;
1217      bool MayBePseudoDestructor = false;
1218      if (getLang().CPlusPlus && !LHS.isInvalid()) {
1219        LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.take(),
1220                                                   OpLoc, OpKind, ObjectType,
1221                                                   MayBePseudoDestructor);
1222        if (LHS.isInvalid())
1223          break;
1224
1225        ParseOptionalCXXScopeSpecifier(SS, ObjectType, false,
1226                                       &MayBePseudoDestructor);
1227        if (SS.isNotEmpty())
1228          ObjectType = ParsedType();
1229      }
1230
1231      if (Tok.is(tok::code_completion)) {
1232        // Code completion for a member access expression.
1233        Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1234                                                OpLoc, OpKind == tok::arrow);
1235
1236        ConsumeCodeCompletionToken();
1237      }
1238
1239      if (MayBePseudoDestructor && !LHS.isInvalid()) {
1240        LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS,
1241                                       ObjectType);
1242        break;
1243      }
1244
1245      // Either the action has told is that this cannot be a
1246      // pseudo-destructor expression (based on the type of base
1247      // expression), or we didn't see a '~' in the right place. We
1248      // can still parse a destructor name here, but in that case it
1249      // names a real destructor.
1250      // Allow explicit constructor calls in Microsoft mode.
1251      // FIXME: Add support for explicit call of template constructor.
1252      UnqualifiedId Name;
1253      if (ParseUnqualifiedId(SS,
1254                             /*EnteringContext=*/false,
1255                             /*AllowDestructorName=*/true,
1256                             /*AllowConstructorName=*/ getLang().Microsoft,
1257                             ObjectType,
1258                             Name))
1259        LHS = ExprError();
1260
1261      if (!LHS.isInvalid())
1262        LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc,
1263                                            OpKind, SS, Name, ObjCImpDecl,
1264                                            Tok.is(tok::l_paren));
1265      break;
1266    }
1267    case tok::plusplus:    // postfix-expression: postfix-expression '++'
1268    case tok::minusminus:  // postfix-expression: postfix-expression '--'
1269      if (!LHS.isInvalid()) {
1270        LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1271                                          Tok.getKind(), LHS.take());
1272      }
1273      ConsumeToken();
1274      break;
1275    }
1276  }
1277}
1278
1279/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1280/// vec_step and we are at the start of an expression or a parenthesized
1281/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1282/// expression (isCastExpr == false) or the type (isCastExpr == true).
1283///
1284///       unary-expression:  [C99 6.5.3]
1285///         'sizeof' unary-expression
1286///         'sizeof' '(' type-name ')'
1287/// [GNU]   '__alignof' unary-expression
1288/// [GNU]   '__alignof' '(' type-name ')'
1289/// [C++0x] 'alignof' '(' type-id ')'
1290///
1291/// [GNU]   typeof-specifier:
1292///           typeof ( expressions )
1293///           typeof ( type-name )
1294/// [GNU/C++] typeof unary-expression
1295///
1296/// [OpenCL 1.1 6.11.12] vec_step built-in function:
1297///           vec_step ( expressions )
1298///           vec_step ( type-name )
1299///
1300ExprResult
1301Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1302                                           bool &isCastExpr,
1303                                           ParsedType &CastTy,
1304                                           SourceRange &CastRange) {
1305
1306  assert((OpTok.is(tok::kw_typeof)    || OpTok.is(tok::kw_sizeof) ||
1307          OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) ||
1308          OpTok.is(tok::kw_vec_step)) &&
1309          "Not a typeof/sizeof/alignof/vec_step expression!");
1310
1311  ExprResult Operand;
1312
1313  // If the operand doesn't start with an '(', it must be an expression.
1314  if (Tok.isNot(tok::l_paren)) {
1315    isCastExpr = false;
1316    if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) {
1317      Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo();
1318      return ExprError();
1319    }
1320
1321    // C++0x [expr.sizeof]p1:
1322    //   [...] The operand is either an expression, which is an unevaluated
1323    //   operand (Clause 5) [...]
1324    //
1325    // The GNU typeof and alignof extensions also behave as unevaluated
1326    // operands.
1327    EnterExpressionEvaluationContext Unevaluated(Actions,
1328                                                 Sema::Unevaluated);
1329    Operand = ParseCastExpression(true/*isUnaryExpression*/);
1330  } else {
1331    // If it starts with a '(', we know that it is either a parenthesized
1332    // type-name, or it is a unary-expression that starts with a compound
1333    // literal, or starts with a primary-expression that is a parenthesized
1334    // expression.
1335    ParenParseOption ExprType = CastExpr;
1336    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1337
1338    // C++0x [expr.sizeof]p1:
1339    //   [...] The operand is either an expression, which is an unevaluated
1340    //   operand (Clause 5) [...]
1341    //
1342    // The GNU typeof and alignof extensions also behave as unevaluated
1343    // operands.
1344    EnterExpressionEvaluationContext Unevaluated(Actions,
1345                                                 Sema::Unevaluated);
1346    Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1347                                   ParsedType(), CastTy, RParenLoc);
1348    CastRange = SourceRange(LParenLoc, RParenLoc);
1349
1350    // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1351    // a type.
1352    if (ExprType == CastExpr) {
1353      isCastExpr = true;
1354      return ExprEmpty();
1355    }
1356
1357    if (getLang().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1358      // GNU typeof in C requires the expression to be parenthesized. Not so for
1359      // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1360      // the start of a unary-expression, but doesn't include any postfix
1361      // pieces. Parse these now if present.
1362      if (!Operand.isInvalid())
1363        Operand = ParsePostfixExpressionSuffix(Operand.get());
1364    }
1365  }
1366
1367  // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1368  isCastExpr = false;
1369  return move(Operand);
1370}
1371
1372
1373/// ParseUnaryExprOrTypeTraitExpression - Parse a sizeof or alignof expression.
1374///       unary-expression:  [C99 6.5.3]
1375///         'sizeof' unary-expression
1376///         'sizeof' '(' type-name ')'
1377/// [C++0x] 'sizeof' '...' '(' identifier ')'
1378/// [GNU]   '__alignof' unary-expression
1379/// [GNU]   '__alignof' '(' type-name ')'
1380/// [C++0x] 'alignof' '(' type-id ')'
1381ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1382  assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
1383          || Tok.is(tok::kw_alignof) || Tok.is(tok::kw_vec_step)) &&
1384         "Not a sizeof/alignof/vec_step expression!");
1385  Token OpTok = Tok;
1386  ConsumeToken();
1387
1388  // [C++0x] 'sizeof' '...' '(' identifier ')'
1389  if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1390    SourceLocation EllipsisLoc = ConsumeToken();
1391    SourceLocation LParenLoc, RParenLoc;
1392    IdentifierInfo *Name = 0;
1393    SourceLocation NameLoc;
1394    if (Tok.is(tok::l_paren)) {
1395      LParenLoc = ConsumeParen();
1396      if (Tok.is(tok::identifier)) {
1397        Name = Tok.getIdentifierInfo();
1398        NameLoc = ConsumeToken();
1399        RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1400        if (RParenLoc.isInvalid())
1401          RParenLoc = PP.getLocForEndOfToken(NameLoc);
1402      } else {
1403        Diag(Tok, diag::err_expected_parameter_pack);
1404        SkipUntil(tok::r_paren);
1405      }
1406    } else if (Tok.is(tok::identifier)) {
1407      Name = Tok.getIdentifierInfo();
1408      NameLoc = ConsumeToken();
1409      LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1410      RParenLoc = PP.getLocForEndOfToken(NameLoc);
1411      Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1412        << Name
1413        << FixItHint::CreateInsertion(LParenLoc, "(")
1414        << FixItHint::CreateInsertion(RParenLoc, ")");
1415    } else {
1416      Diag(Tok, diag::err_sizeof_parameter_pack);
1417    }
1418
1419    if (!Name)
1420      return ExprError();
1421
1422    return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1423                                                OpTok.getLocation(),
1424                                                *Name, NameLoc,
1425                                                RParenLoc);
1426  }
1427
1428  bool isCastExpr;
1429  ParsedType CastTy;
1430  SourceRange CastRange;
1431  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1432                                                          isCastExpr,
1433                                                          CastTy,
1434                                                          CastRange);
1435
1436  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1437  if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof))
1438    ExprKind = UETT_AlignOf;
1439  else if (OpTok.is(tok::kw_vec_step))
1440    ExprKind = UETT_VecStep;
1441
1442  if (isCastExpr)
1443    return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1444                                                 ExprKind,
1445                                                 /*isType=*/true,
1446                                                 CastTy.getAsOpaquePtr(),
1447                                                 CastRange);
1448
1449  // If we get here, the operand to the sizeof/alignof was an expresion.
1450  if (!Operand.isInvalid())
1451    Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1452                                                    ExprKind,
1453                                                    /*isType=*/false,
1454                                                    Operand.release(),
1455                                                    CastRange);
1456  return move(Operand);
1457}
1458
1459/// ParseBuiltinPrimaryExpression
1460///
1461///       primary-expression: [C99 6.5.1]
1462/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1463/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1464/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1465///                                     assign-expr ')'
1466/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1467///
1468/// [GNU] offsetof-member-designator:
1469/// [GNU]   identifier
1470/// [GNU]   offsetof-member-designator '.' identifier
1471/// [GNU]   offsetof-member-designator '[' expression ']'
1472///
1473ExprResult Parser::ParseBuiltinPrimaryExpression() {
1474  ExprResult Res;
1475  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1476
1477  tok::TokenKind T = Tok.getKind();
1478  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
1479
1480  // All of these start with an open paren.
1481  if (Tok.isNot(tok::l_paren))
1482    return ExprError(Diag(Tok, diag::err_expected_lparen_after_id)
1483                       << BuiltinII);
1484
1485  SourceLocation LParenLoc = ConsumeParen();
1486  // TODO: Build AST.
1487
1488  switch (T) {
1489  default: assert(0 && "Not a builtin primary expression!");
1490  case tok::kw___builtin_va_arg: {
1491    ExprResult Expr(ParseAssignmentExpression());
1492
1493    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1494      Expr = ExprError();
1495
1496    TypeResult Ty = ParseTypeName();
1497
1498    if (Tok.isNot(tok::r_paren)) {
1499      Diag(Tok, diag::err_expected_rparen);
1500      Expr = ExprError();
1501    }
1502
1503    if (Expr.isInvalid() || Ty.isInvalid())
1504      Res = ExprError();
1505    else
1506      Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen());
1507    break;
1508  }
1509  case tok::kw___builtin_offsetof: {
1510    SourceLocation TypeLoc = Tok.getLocation();
1511    TypeResult Ty = ParseTypeName();
1512    if (Ty.isInvalid()) {
1513      SkipUntil(tok::r_paren);
1514      return ExprError();
1515    }
1516
1517    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1518      return ExprError();
1519
1520    // We must have at least one identifier here.
1521    if (Tok.isNot(tok::identifier)) {
1522      Diag(Tok, diag::err_expected_ident);
1523      SkipUntil(tok::r_paren);
1524      return ExprError();
1525    }
1526
1527    // Keep track of the various subcomponents we see.
1528    llvm::SmallVector<Sema::OffsetOfComponent, 4> Comps;
1529
1530    Comps.push_back(Sema::OffsetOfComponent());
1531    Comps.back().isBrackets = false;
1532    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1533    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1534
1535    // FIXME: This loop leaks the index expressions on error.
1536    while (1) {
1537      if (Tok.is(tok::period)) {
1538        // offsetof-member-designator: offsetof-member-designator '.' identifier
1539        Comps.push_back(Sema::OffsetOfComponent());
1540        Comps.back().isBrackets = false;
1541        Comps.back().LocStart = ConsumeToken();
1542
1543        if (Tok.isNot(tok::identifier)) {
1544          Diag(Tok, diag::err_expected_ident);
1545          SkipUntil(tok::r_paren);
1546          return ExprError();
1547        }
1548        Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1549        Comps.back().LocEnd = ConsumeToken();
1550
1551      } else if (Tok.is(tok::l_square)) {
1552        // offsetof-member-designator: offsetof-member-design '[' expression ']'
1553        Comps.push_back(Sema::OffsetOfComponent());
1554        Comps.back().isBrackets = true;
1555        Comps.back().LocStart = ConsumeBracket();
1556        Res = ParseExpression();
1557        if (Res.isInvalid()) {
1558          SkipUntil(tok::r_paren);
1559          return move(Res);
1560        }
1561        Comps.back().U.E = Res.release();
1562
1563        Comps.back().LocEnd =
1564          MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
1565      } else {
1566        if (Tok.isNot(tok::r_paren)) {
1567          MatchRHSPunctuation(tok::r_paren, LParenLoc);
1568          Res = ExprError();
1569        } else if (Ty.isInvalid()) {
1570          Res = ExprError();
1571        } else {
1572          Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
1573                                             Ty.get(), &Comps[0],
1574                                             Comps.size(), ConsumeParen());
1575        }
1576        break;
1577      }
1578    }
1579    break;
1580  }
1581  case tok::kw___builtin_choose_expr: {
1582    ExprResult Cond(ParseAssignmentExpression());
1583    if (Cond.isInvalid()) {
1584      SkipUntil(tok::r_paren);
1585      return move(Cond);
1586    }
1587    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1588      return ExprError();
1589
1590    ExprResult Expr1(ParseAssignmentExpression());
1591    if (Expr1.isInvalid()) {
1592      SkipUntil(tok::r_paren);
1593      return move(Expr1);
1594    }
1595    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1596      return ExprError();
1597
1598    ExprResult Expr2(ParseAssignmentExpression());
1599    if (Expr2.isInvalid()) {
1600      SkipUntil(tok::r_paren);
1601      return move(Expr2);
1602    }
1603    if (Tok.isNot(tok::r_paren)) {
1604      Diag(Tok, diag::err_expected_rparen);
1605      return ExprError();
1606    }
1607    Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(),
1608                                  Expr2.take(), ConsumeParen());
1609    break;
1610  }
1611  }
1612
1613  if (Res.isInvalid())
1614    return ExprError();
1615
1616  // These can be followed by postfix-expr pieces because they are
1617  // primary-expressions.
1618  return ParsePostfixExpressionSuffix(Res.take());
1619}
1620
1621/// ParseParenExpression - This parses the unit that starts with a '(' token,
1622/// based on what is allowed by ExprType.  The actual thing parsed is returned
1623/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
1624/// not the parsed cast-expression.
1625///
1626///       primary-expression: [C99 6.5.1]
1627///         '(' expression ')'
1628/// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
1629///       postfix-expression: [C99 6.5.2]
1630///         '(' type-name ')' '{' initializer-list '}'
1631///         '(' type-name ')' '{' initializer-list ',' '}'
1632///       cast-expression: [C99 6.5.4]
1633///         '(' type-name ')' cast-expression
1634///
1635ExprResult
1636Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
1637                             ParsedType TypeOfCast, ParsedType &CastTy,
1638                             SourceLocation &RParenLoc) {
1639  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
1640  GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
1641  SourceLocation OpenLoc = ConsumeParen();
1642  ExprResult Result(true);
1643  bool isAmbiguousTypeId;
1644  CastTy = ParsedType();
1645
1646  if (Tok.is(tok::code_completion)) {
1647    Actions.CodeCompleteOrdinaryName(getCurScope(),
1648                 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
1649                                            : Sema::PCC_Expression);
1650    ConsumeCodeCompletionToken();
1651    return ExprError();
1652  }
1653
1654  // None of these cases should fall through with an invalid Result
1655  // unless they've already reported an error.
1656
1657  if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
1658    Diag(Tok, diag::ext_gnu_statement_expr);
1659    ParsedAttributes attrs(AttrFactory);
1660    StmtResult Stmt(ParseCompoundStatement(attrs, true));
1661    ExprType = CompoundStmt;
1662
1663    // If the substmt parsed correctly, build the AST node.
1664    if (!Stmt.isInvalid())
1665      Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation());
1666
1667  } else if (ExprType >= CompoundLiteral &&
1668             isTypeIdInParens(isAmbiguousTypeId)) {
1669
1670    // Otherwise, this is a compound literal expression or cast expression.
1671
1672    // In C++, if the type-id is ambiguous we disambiguate based on context.
1673    // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
1674    // in which case we should treat it as type-id.
1675    // if stopIfCastExpr is false, we need to determine the context past the
1676    // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
1677    if (isAmbiguousTypeId && !stopIfCastExpr)
1678      return ParseCXXAmbiguousParenExpression(ExprType, CastTy,
1679                                              OpenLoc, RParenLoc);
1680
1681    TypeResult Ty;
1682
1683    {
1684      InMessageExpressionRAIIObject InMessage(*this, false);
1685      Ty = ParseTypeName();
1686    }
1687
1688    // If our type is followed by an identifier and either ':' or ']', then
1689    // this is probably an Objective-C message send where the leading '[' is
1690    // missing. Recover as if that were the case.
1691    if (!Ty.isInvalid() && Tok.is(tok::identifier) && !InMessageExpression &&
1692        getLang().ObjC1 && !Ty.get().get().isNull() &&
1693        (NextToken().is(tok::colon) || NextToken().is(tok::r_square)) &&
1694        Ty.get().get()->isObjCObjectOrInterfaceType()) {
1695      Result = ParseObjCMessageExpressionBody(SourceLocation(),
1696                                              SourceLocation(),
1697                                              Ty.get(), 0);
1698    } else {
1699      // Match the ')'.
1700      if (Tok.is(tok::r_paren))
1701        RParenLoc = ConsumeParen();
1702      else
1703        MatchRHSPunctuation(tok::r_paren, OpenLoc);
1704
1705      if (Tok.is(tok::l_brace)) {
1706        ExprType = CompoundLiteral;
1707        return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
1708      }
1709
1710      if (ExprType == CastExpr) {
1711        // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
1712
1713        if (Ty.isInvalid())
1714          return ExprError();
1715
1716        CastTy = Ty.get();
1717
1718        // Note that this doesn't parse the subsequent cast-expression, it just
1719        // returns the parsed type to the callee.
1720        if (stopIfCastExpr)
1721          return ExprResult();
1722
1723        // Reject the cast of super idiom in ObjC.
1724        if (Tok.is(tok::identifier) && getLang().ObjC1 &&
1725            Tok.getIdentifierInfo() == Ident_super &&
1726            getCurScope()->isInObjcMethodScope() &&
1727            GetLookAheadToken(1).isNot(tok::period)) {
1728          Diag(Tok.getLocation(), diag::err_illegal_super_cast)
1729            << SourceRange(OpenLoc, RParenLoc);
1730          return ExprError();
1731        }
1732
1733        // Parse the cast-expression that follows it next.
1734        // TODO: For cast expression with CastTy.
1735        Result = ParseCastExpression(false, false, CastTy);
1736        if (!Result.isInvalid())
1737          Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, CastTy,
1738                                         RParenLoc, Result.take());
1739        return move(Result);
1740      }
1741
1742      Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1743      return ExprError();
1744    }
1745  } else if (TypeOfCast) {
1746    // Parse the expression-list.
1747    InMessageExpressionRAIIObject InMessage(*this, false);
1748
1749    ExprVector ArgExprs(Actions);
1750    CommaLocsTy CommaLocs;
1751
1752    if (!ParseExpressionList(ArgExprs, CommaLocs)) {
1753      ExprType = SimpleExpr;
1754      Result = Actions.ActOnParenOrParenListExpr(OpenLoc, Tok.getLocation(),
1755                                          move_arg(ArgExprs), TypeOfCast);
1756    }
1757  } else {
1758    InMessageExpressionRAIIObject InMessage(*this, false);
1759
1760    Result = ParseExpression();
1761    ExprType = SimpleExpr;
1762
1763    // Don't build a paren expression unless we actually match a ')'.
1764    if (!Result.isInvalid() && Tok.is(tok::r_paren))
1765      Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take());
1766  }
1767
1768  // Match the ')'.
1769  if (Result.isInvalid()) {
1770    SkipUntil(tok::r_paren);
1771    return ExprError();
1772  }
1773
1774  if (Tok.is(tok::r_paren))
1775    RParenLoc = ConsumeParen();
1776  else
1777    MatchRHSPunctuation(tok::r_paren, OpenLoc);
1778
1779  return move(Result);
1780}
1781
1782/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
1783/// and we are at the left brace.
1784///
1785///       postfix-expression: [C99 6.5.2]
1786///         '(' type-name ')' '{' initializer-list '}'
1787///         '(' type-name ')' '{' initializer-list ',' '}'
1788///
1789ExprResult
1790Parser::ParseCompoundLiteralExpression(ParsedType Ty,
1791                                       SourceLocation LParenLoc,
1792                                       SourceLocation RParenLoc) {
1793  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
1794  if (!getLang().C99)   // Compound literals don't exist in C90.
1795    Diag(LParenLoc, diag::ext_c99_compound_literal);
1796  ExprResult Result = ParseInitializer();
1797  if (!Result.isInvalid() && Ty)
1798    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take());
1799  return move(Result);
1800}
1801
1802/// ParseStringLiteralExpression - This handles the various token types that
1803/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1804/// translation phase #6].
1805///
1806///       primary-expression: [C99 6.5.1]
1807///         string-literal
1808ExprResult Parser::ParseStringLiteralExpression() {
1809  assert(isTokenStringLiteral() && "Not a string literal!");
1810
1811  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
1812  // considered to be strings for concatenation purposes.
1813  llvm::SmallVector<Token, 4> StringToks;
1814
1815  do {
1816    StringToks.push_back(Tok);
1817    ConsumeStringToken();
1818  } while (isTokenStringLiteral());
1819
1820  // Pass the set of string tokens, ready for concatenation, to the actions.
1821  return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
1822}
1823
1824/// ParseGenericSelectionExpression - Parse a C1X generic-selection
1825/// [C1X 6.5.1.1].
1826///
1827///    generic-selection:
1828///           _Generic ( assignment-expression , generic-assoc-list )
1829///    generic-assoc-list:
1830///           generic-association
1831///           generic-assoc-list , generic-association
1832///    generic-association:
1833///           type-name : assignment-expression
1834///           default : assignment-expression
1835ExprResult Parser::ParseGenericSelectionExpression() {
1836  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
1837  SourceLocation KeyLoc = ConsumeToken();
1838
1839  if (!getLang().C1X)
1840    Diag(KeyLoc, diag::ext_c1x_generic_selection);
1841
1842  SourceLocation LParenLoc = Tok.getLocation();
1843  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, ""))
1844    return ExprError();
1845
1846  ExprResult ControllingExpr;
1847  {
1848    // C1X 6.5.1.1p3 "The controlling expression of a generic selection is
1849    // not evaluated."
1850    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1851    ControllingExpr = ParseAssignmentExpression();
1852    if (ControllingExpr.isInvalid()) {
1853      SkipUntil(tok::r_paren);
1854      return ExprError();
1855    }
1856  }
1857
1858  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "")) {
1859    SkipUntil(tok::r_paren);
1860    return ExprError();
1861  }
1862
1863  SourceLocation DefaultLoc;
1864  TypeVector Types(Actions);
1865  ExprVector Exprs(Actions);
1866  while (1) {
1867    ParsedType Ty;
1868    if (Tok.is(tok::kw_default)) {
1869      // C1X 6.5.1.1p2 "A generic selection shall have no more than one default
1870      // generic association."
1871      if (!DefaultLoc.isInvalid()) {
1872        Diag(Tok, diag::err_duplicate_default_assoc);
1873        Diag(DefaultLoc, diag::note_previous_default_assoc);
1874        SkipUntil(tok::r_paren);
1875        return ExprError();
1876      }
1877      DefaultLoc = ConsumeToken();
1878      Ty = ParsedType();
1879    } else {
1880      ColonProtectionRAIIObject X(*this);
1881      TypeResult TR = ParseTypeName();
1882      if (TR.isInvalid()) {
1883        SkipUntil(tok::r_paren);
1884        return ExprError();
1885      }
1886      Ty = TR.release();
1887    }
1888    Types.push_back(Ty);
1889
1890    if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "")) {
1891      SkipUntil(tok::r_paren);
1892      return ExprError();
1893    }
1894
1895    // FIXME: These expressions should be parsed in a potentially potentially
1896    // evaluated context.
1897    ExprResult ER(ParseAssignmentExpression());
1898    if (ER.isInvalid()) {
1899      SkipUntil(tok::r_paren);
1900      return ExprError();
1901    }
1902    Exprs.push_back(ER.release());
1903
1904    if (Tok.isNot(tok::comma))
1905      break;
1906    ConsumeToken();
1907  }
1908
1909  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1910  if (RParenLoc.isInvalid())
1911    return ExprError();
1912
1913  return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1914                                           ControllingExpr.release(),
1915                                           move_arg(Types), move_arg(Exprs));
1916}
1917
1918/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1919///
1920///       argument-expression-list:
1921///         assignment-expression
1922///         argument-expression-list , assignment-expression
1923///
1924/// [C++] expression-list:
1925/// [C++]   assignment-expression ...[opt]
1926/// [C++]   expression-list , assignment-expression ...[opt]
1927///
1928bool Parser::ParseExpressionList(llvm::SmallVectorImpl<Expr*> &Exprs,
1929                            llvm::SmallVectorImpl<SourceLocation> &CommaLocs,
1930                                 void (Sema::*Completer)(Scope *S,
1931                                                           Expr *Data,
1932                                                           Expr **Args,
1933                                                           unsigned NumArgs),
1934                                 Expr *Data) {
1935  while (1) {
1936    if (Tok.is(tok::code_completion)) {
1937      if (Completer)
1938        (Actions.*Completer)(getCurScope(), Data, Exprs.data(), Exprs.size());
1939      else
1940        Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1941      ConsumeCodeCompletionToken();
1942    }
1943
1944    ExprResult Expr(ParseAssignmentExpression());
1945    if (Tok.is(tok::ellipsis))
1946      Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
1947    if (Expr.isInvalid())
1948      return true;
1949
1950    Exprs.push_back(Expr.release());
1951
1952    if (Tok.isNot(tok::comma))
1953      return false;
1954    // Move to the next argument, remember where the comma was.
1955    CommaLocs.push_back(ConsumeToken());
1956  }
1957}
1958
1959/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
1960///
1961/// [clang] block-id:
1962/// [clang]   specifier-qualifier-list block-declarator
1963///
1964void Parser::ParseBlockId() {
1965  if (Tok.is(tok::code_completion)) {
1966    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1967    ConsumeCodeCompletionToken();
1968  }
1969
1970  // Parse the specifier-qualifier-list piece.
1971  DeclSpec DS(AttrFactory);
1972  ParseSpecifierQualifierList(DS);
1973
1974  // Parse the block-declarator.
1975  Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
1976  ParseDeclarator(DeclaratorInfo);
1977
1978  // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes.
1979  DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation());
1980
1981  MaybeParseGNUAttributes(DeclaratorInfo);
1982
1983  // Inform sema that we are starting a block.
1984  Actions.ActOnBlockArguments(DeclaratorInfo, getCurScope());
1985}
1986
1987/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
1988/// like ^(int x){ return x+1; }
1989///
1990///         block-literal:
1991/// [clang]   '^' block-args[opt] compound-statement
1992/// [clang]   '^' block-id compound-statement
1993/// [clang] block-args:
1994/// [clang]   '(' parameter-list ')'
1995///
1996ExprResult Parser::ParseBlockLiteralExpression() {
1997  assert(Tok.is(tok::caret) && "block literal starts with ^");
1998  SourceLocation CaretLoc = ConsumeToken();
1999
2000  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2001                                "block literal parsing");
2002
2003  // Enter a scope to hold everything within the block.  This includes the
2004  // argument decls, decls within the compound expression, etc.  This also
2005  // allows determining whether a variable reference inside the block is
2006  // within or outside of the block.
2007  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2008                              Scope::BreakScope | Scope::ContinueScope |
2009                              Scope::DeclScope);
2010
2011  // Inform sema that we are starting a block.
2012  Actions.ActOnBlockStart(CaretLoc, getCurScope());
2013
2014  // Parse the return type if present.
2015  DeclSpec DS(AttrFactory);
2016  Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2017  // FIXME: Since the return type isn't actually parsed, it can't be used to
2018  // fill ParamInfo with an initial valid range, so do it manually.
2019  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2020
2021  // If this block has arguments, parse them.  There is no ambiguity here with
2022  // the expression case, because the expression case requires a parameter list.
2023  if (Tok.is(tok::l_paren)) {
2024    ParseParenDeclarator(ParamInfo);
2025    // Parse the pieces after the identifier as if we had "int(...)".
2026    // SetIdentifier sets the source range end, but in this case we're past
2027    // that location.
2028    SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2029    ParamInfo.SetIdentifier(0, CaretLoc);
2030    ParamInfo.SetRangeEnd(Tmp);
2031    if (ParamInfo.isInvalidType()) {
2032      // If there was an error parsing the arguments, they may have
2033      // tried to use ^(x+y) which requires an argument list.  Just
2034      // skip the whole block literal.
2035      Actions.ActOnBlockError(CaretLoc, getCurScope());
2036      return ExprError();
2037    }
2038
2039    MaybeParseGNUAttributes(ParamInfo);
2040
2041    // Inform sema that we are starting a block.
2042    Actions.ActOnBlockArguments(ParamInfo, getCurScope());
2043  } else if (!Tok.is(tok::l_brace)) {
2044    ParseBlockId();
2045  } else {
2046    // Otherwise, pretend we saw (void).
2047    ParsedAttributes attrs(AttrFactory);
2048    ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
2049                                                       SourceLocation(),
2050                                                       0, 0, 0,
2051                                                       true, SourceLocation(),
2052                                                       EST_None,
2053                                                       SourceLocation(),
2054                                                       0, 0, 0, 0,
2055                                                       CaretLoc, CaretLoc,
2056                                                       ParamInfo),
2057                          attrs, CaretLoc);
2058
2059    MaybeParseGNUAttributes(ParamInfo);
2060
2061    // Inform sema that we are starting a block.
2062    Actions.ActOnBlockArguments(ParamInfo, getCurScope());
2063  }
2064
2065
2066  ExprResult Result(true);
2067  if (!Tok.is(tok::l_brace)) {
2068    // Saw something like: ^expr
2069    Diag(Tok, diag::err_expected_expression);
2070    Actions.ActOnBlockError(CaretLoc, getCurScope());
2071    return ExprError();
2072  }
2073
2074  StmtResult Stmt(ParseCompoundStatementBody());
2075  BlockScope.Exit();
2076  if (!Stmt.isInvalid())
2077    Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope());
2078  else
2079    Actions.ActOnBlockError(CaretLoc, getCurScope());
2080  return move(Result);
2081}
2082