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