ParseExprCXX.cpp revision ccf43505dbc47da041c06125f90b3bd3ac7eac97
1//===--- ParseExprCXX.cpp - C++ 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 for C++.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/ParseDiagnostic.h"
15#include "clang/Parse/Parser.h"
16#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Template.h"
18#include "llvm/Support/ErrorHandling.h"
19
20using namespace clang;
21
22/// \brief Parse global scope or nested-name-specifier if present.
23///
24/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
25/// may be preceded by '::'). Note that this routine will not parse ::new or
26/// ::delete; it will just leave them in the token stream.
27///
28///       '::'[opt] nested-name-specifier
29///       '::'
30///
31///       nested-name-specifier:
32///         type-name '::'
33///         namespace-name '::'
34///         nested-name-specifier identifier '::'
35///         nested-name-specifier 'template'[opt] simple-template-id '::'
36///
37///
38/// \param SS the scope specifier that will be set to the parsed
39/// nested-name-specifier (or empty)
40///
41/// \param ObjectType if this nested-name-specifier is being parsed following
42/// the "." or "->" of a member access expression, this parameter provides the
43/// type of the object whose members are being accessed.
44///
45/// \param EnteringContext whether we will be entering into the context of
46/// the nested-name-specifier after parsing it.
47///
48/// \returns true if a scope specifier was parsed.
49bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
50                                            Action::TypeTy *ObjectType,
51                                            bool EnteringContext) {
52  assert(getLang().CPlusPlus &&
53         "Call sites of this function should be guarded by checking for C++");
54
55  if (Tok.is(tok::annot_cxxscope)) {
56    SS.setScopeRep(Tok.getAnnotationValue());
57    SS.setRange(Tok.getAnnotationRange());
58    ConsumeToken();
59    return true;
60  }
61
62  bool HasScopeSpecifier = false;
63
64  if (Tok.is(tok::coloncolon)) {
65    // ::new and ::delete aren't nested-name-specifiers.
66    tok::TokenKind NextKind = NextToken().getKind();
67    if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
68      return false;
69
70    // '::' - Global scope qualifier.
71    SourceLocation CCLoc = ConsumeToken();
72    SS.setBeginLoc(CCLoc);
73    SS.setScopeRep(Actions.ActOnCXXGlobalScopeSpecifier(CurScope, CCLoc));
74    SS.setEndLoc(CCLoc);
75    HasScopeSpecifier = true;
76  }
77
78  while (true) {
79    if (HasScopeSpecifier) {
80      // C++ [basic.lookup.classref]p5:
81      //   If the qualified-id has the form
82      //
83      //       ::class-name-or-namespace-name::...
84      //
85      //   the class-name-or-namespace-name is looked up in global scope as a
86      //   class-name or namespace-name.
87      //
88      // To implement this, we clear out the object type as soon as we've
89      // seen a leading '::' or part of a nested-name-specifier.
90      ObjectType = 0;
91
92      if (Tok.is(tok::code_completion)) {
93        // Code completion for a nested-name-specifier, where the code
94        // code completion token follows the '::'.
95        Actions.CodeCompleteQualifiedId(CurScope, SS, EnteringContext);
96        ConsumeToken();
97      }
98    }
99
100    // nested-name-specifier:
101    //   nested-name-specifier 'template'[opt] simple-template-id '::'
102
103    // Parse the optional 'template' keyword, then make sure we have
104    // 'identifier <' after it.
105    if (Tok.is(tok::kw_template)) {
106      // If we don't have a scope specifier or an object type, this isn't a
107      // nested-name-specifier, since they aren't allowed to start with
108      // 'template'.
109      if (!HasScopeSpecifier && !ObjectType)
110        break;
111
112      TentativeParsingAction TPA(*this);
113      SourceLocation TemplateKWLoc = ConsumeToken();
114
115      UnqualifiedId TemplateName;
116      if (Tok.is(tok::identifier)) {
117        // Consume the identifier.
118        TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
119        ConsumeToken();
120      } else if (Tok.is(tok::kw_operator)) {
121        if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
122                                       TemplateName)) {
123          TPA.Commit();
124          break;
125        }
126
127        if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
128            TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
129          Diag(TemplateName.getSourceRange().getBegin(),
130               diag::err_id_after_template_in_nested_name_spec)
131            << TemplateName.getSourceRange();
132          TPA.Commit();
133          break;
134        }
135      } else {
136        TPA.Revert();
137        break;
138      }
139
140      // If the next token is not '<', we have a qualified-id that refers
141      // to a template name, such as T::template apply, but is not a
142      // template-id.
143      if (Tok.isNot(tok::less)) {
144        TPA.Revert();
145        break;
146      }
147
148      // Commit to parsing the template-id.
149      TPA.Commit();
150      TemplateTy Template
151        = Actions.ActOnDependentTemplateName(TemplateKWLoc, SS, TemplateName,
152                                             ObjectType, EnteringContext);
153      if (!Template)
154        break;
155      if (AnnotateTemplateIdToken(Template, TNK_Dependent_template_name,
156                                  &SS, TemplateName, TemplateKWLoc, false))
157        break;
158
159      continue;
160    }
161
162    if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
163      // We have
164      //
165      //   simple-template-id '::'
166      //
167      // So we need to check whether the simple-template-id is of the
168      // right kind (it should name a type or be dependent), and then
169      // convert it into a type within the nested-name-specifier.
170      TemplateIdAnnotation *TemplateId
171        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
172
173      if (TemplateId->Kind == TNK_Type_template ||
174          TemplateId->Kind == TNK_Dependent_template_name) {
175        AnnotateTemplateIdTokenAsType(&SS);
176
177        assert(Tok.is(tok::annot_typename) &&
178               "AnnotateTemplateIdTokenAsType isn't working");
179        Token TypeToken = Tok;
180        ConsumeToken();
181        assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
182        SourceLocation CCLoc = ConsumeToken();
183
184        if (!HasScopeSpecifier) {
185          SS.setBeginLoc(TypeToken.getLocation());
186          HasScopeSpecifier = true;
187        }
188
189        if (TypeToken.getAnnotationValue())
190          SS.setScopeRep(
191            Actions.ActOnCXXNestedNameSpecifier(CurScope, SS,
192                                                TypeToken.getAnnotationValue(),
193                                                TypeToken.getAnnotationRange(),
194                                                CCLoc));
195        else
196          SS.setScopeRep(0);
197        SS.setEndLoc(CCLoc);
198        continue;
199      }
200
201      assert(false && "FIXME: Only type template names supported here");
202    }
203
204
205    // The rest of the nested-name-specifier possibilities start with
206    // tok::identifier.
207    if (Tok.isNot(tok::identifier))
208      break;
209
210    IdentifierInfo &II = *Tok.getIdentifierInfo();
211
212    // nested-name-specifier:
213    //   type-name '::'
214    //   namespace-name '::'
215    //   nested-name-specifier identifier '::'
216    Token Next = NextToken();
217    if (Next.is(tok::coloncolon)) {
218      // We have an identifier followed by a '::'. Lookup this name
219      // as the name in a nested-name-specifier.
220      SourceLocation IdLoc = ConsumeToken();
221      assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
222      SourceLocation CCLoc = ConsumeToken();
223
224      if (!HasScopeSpecifier) {
225        SS.setBeginLoc(IdLoc);
226        HasScopeSpecifier = true;
227      }
228
229      if (SS.isInvalid())
230        continue;
231
232      SS.setScopeRep(
233        Actions.ActOnCXXNestedNameSpecifier(CurScope, SS, IdLoc, CCLoc, II,
234                                            ObjectType, EnteringContext));
235      SS.setEndLoc(CCLoc);
236      continue;
237    }
238
239    // nested-name-specifier:
240    //   type-name '<'
241    if (Next.is(tok::less)) {
242      TemplateTy Template;
243      UnqualifiedId TemplateName;
244      TemplateName.setIdentifier(&II, Tok.getLocation());
245      if (TemplateNameKind TNK = Actions.isTemplateName(CurScope, SS,
246                                                        TemplateName,
247                                                        ObjectType,
248                                                        EnteringContext,
249                                                        Template)) {
250        // We have found a template name, so annotate this this token
251        // with a template-id annotation. We do not permit the
252        // template-id to be translated into a type annotation,
253        // because some clients (e.g., the parsing of class template
254        // specializations) still want to see the original template-id
255        // token.
256        ConsumeToken();
257        if (AnnotateTemplateIdToken(Template, TNK, &SS, TemplateName,
258                                    SourceLocation(), false))
259          break;
260        continue;
261      }
262    }
263
264    // We don't have any tokens that form the beginning of a
265    // nested-name-specifier, so we're done.
266    break;
267  }
268
269  return HasScopeSpecifier;
270}
271
272/// ParseCXXIdExpression - Handle id-expression.
273///
274///       id-expression:
275///         unqualified-id
276///         qualified-id
277///
278///       qualified-id:
279///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
280///         '::' identifier
281///         '::' operator-function-id
282///         '::' template-id
283///
284/// NOTE: The standard specifies that, for qualified-id, the parser does not
285/// expect:
286///
287///   '::' conversion-function-id
288///   '::' '~' class-name
289///
290/// This may cause a slight inconsistency on diagnostics:
291///
292/// class C {};
293/// namespace A {}
294/// void f() {
295///   :: A :: ~ C(); // Some Sema error about using destructor with a
296///                  // namespace.
297///   :: ~ C(); // Some Parser error like 'unexpected ~'.
298/// }
299///
300/// We simplify the parser a bit and make it work like:
301///
302///       qualified-id:
303///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
304///         '::' unqualified-id
305///
306/// That way Sema can handle and report similar errors for namespaces and the
307/// global scope.
308///
309/// The isAddressOfOperand parameter indicates that this id-expression is a
310/// direct operand of the address-of operator. This is, besides member contexts,
311/// the only place where a qualified-id naming a non-static class member may
312/// appear.
313///
314Parser::OwningExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
315  // qualified-id:
316  //   '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
317  //   '::' unqualified-id
318  //
319  CXXScopeSpec SS;
320  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
321
322  UnqualifiedId Name;
323  if (ParseUnqualifiedId(SS,
324                         /*EnteringContext=*/false,
325                         /*AllowDestructorName=*/false,
326                         /*AllowConstructorName=*/false,
327                         /*ObjectType=*/0,
328                         Name))
329    return ExprError();
330
331  // This is only the direct operand of an & operator if it is not
332  // followed by a postfix-expression suffix.
333  if (isAddressOfOperand) {
334    switch (Tok.getKind()) {
335    case tok::l_square:
336    case tok::l_paren:
337    case tok::arrow:
338    case tok::period:
339    case tok::plusplus:
340    case tok::minusminus:
341      isAddressOfOperand = false;
342      break;
343
344    default:
345      break;
346    }
347  }
348
349  return Actions.ActOnIdExpression(CurScope, SS, Name, Tok.is(tok::l_paren),
350                                   isAddressOfOperand);
351
352}
353
354/// ParseCXXCasts - This handles the various ways to cast expressions to another
355/// type.
356///
357///       postfix-expression: [C++ 5.2p1]
358///         'dynamic_cast' '<' type-name '>' '(' expression ')'
359///         'static_cast' '<' type-name '>' '(' expression ')'
360///         'reinterpret_cast' '<' type-name '>' '(' expression ')'
361///         'const_cast' '<' type-name '>' '(' expression ')'
362///
363Parser::OwningExprResult Parser::ParseCXXCasts() {
364  tok::TokenKind Kind = Tok.getKind();
365  const char *CastName = 0;     // For error messages
366
367  switch (Kind) {
368  default: assert(0 && "Unknown C++ cast!"); abort();
369  case tok::kw_const_cast:       CastName = "const_cast";       break;
370  case tok::kw_dynamic_cast:     CastName = "dynamic_cast";     break;
371  case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
372  case tok::kw_static_cast:      CastName = "static_cast";      break;
373  }
374
375  SourceLocation OpLoc = ConsumeToken();
376  SourceLocation LAngleBracketLoc = Tok.getLocation();
377
378  if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
379    return ExprError();
380
381  TypeResult CastTy = ParseTypeName();
382  SourceLocation RAngleBracketLoc = Tok.getLocation();
383
384  if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
385    return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
386
387  SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
388
389  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, CastName))
390    return ExprError();
391
392  OwningExprResult Result = ParseExpression();
393
394  // Match the ')'.
395  RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
396
397  if (!Result.isInvalid() && !CastTy.isInvalid())
398    Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
399                                       LAngleBracketLoc, CastTy.get(),
400                                       RAngleBracketLoc,
401                                       LParenLoc, move(Result), RParenLoc);
402
403  return move(Result);
404}
405
406/// ParseCXXTypeid - This handles the C++ typeid expression.
407///
408///       postfix-expression: [C++ 5.2p1]
409///         'typeid' '(' expression ')'
410///         'typeid' '(' type-id ')'
411///
412Parser::OwningExprResult Parser::ParseCXXTypeid() {
413  assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
414
415  SourceLocation OpLoc = ConsumeToken();
416  SourceLocation LParenLoc = Tok.getLocation();
417  SourceLocation RParenLoc;
418
419  // typeid expressions are always parenthesized.
420  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
421      "typeid"))
422    return ExprError();
423
424  OwningExprResult Result(Actions);
425
426  if (isTypeIdInParens()) {
427    TypeResult Ty = ParseTypeName();
428
429    // Match the ')'.
430    MatchRHSPunctuation(tok::r_paren, LParenLoc);
431
432    if (Ty.isInvalid())
433      return ExprError();
434
435    Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
436                                    Ty.get(), RParenLoc);
437  } else {
438    // C++0x [expr.typeid]p3:
439    //   When typeid is applied to an expression other than an lvalue of a
440    //   polymorphic class type [...] The expression is an unevaluated
441    //   operand (Clause 5).
442    //
443    // Note that we can't tell whether the expression is an lvalue of a
444    // polymorphic class type until after we've parsed the expression, so
445    // we the expression is potentially potentially evaluated.
446    EnterExpressionEvaluationContext Unevaluated(Actions,
447                                       Action::PotentiallyPotentiallyEvaluated);
448    Result = ParseExpression();
449
450    // Match the ')'.
451    if (Result.isInvalid())
452      SkipUntil(tok::r_paren);
453    else {
454      MatchRHSPunctuation(tok::r_paren, LParenLoc);
455
456      Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
457                                      Result.release(), RParenLoc);
458    }
459  }
460
461  return move(Result);
462}
463
464/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
465///
466///       boolean-literal: [C++ 2.13.5]
467///         'true'
468///         'false'
469Parser::OwningExprResult Parser::ParseCXXBoolLiteral() {
470  tok::TokenKind Kind = Tok.getKind();
471  return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
472}
473
474/// ParseThrowExpression - This handles the C++ throw expression.
475///
476///       throw-expression: [C++ 15]
477///         'throw' assignment-expression[opt]
478Parser::OwningExprResult Parser::ParseThrowExpression() {
479  assert(Tok.is(tok::kw_throw) && "Not throw!");
480  SourceLocation ThrowLoc = ConsumeToken();           // Eat the throw token.
481
482  // If the current token isn't the start of an assignment-expression,
483  // then the expression is not present.  This handles things like:
484  //   "C ? throw : (void)42", which is crazy but legal.
485  switch (Tok.getKind()) {  // FIXME: move this predicate somewhere common.
486  case tok::semi:
487  case tok::r_paren:
488  case tok::r_square:
489  case tok::r_brace:
490  case tok::colon:
491  case tok::comma:
492    return Actions.ActOnCXXThrow(ThrowLoc, ExprArg(Actions));
493
494  default:
495    OwningExprResult Expr(ParseAssignmentExpression());
496    if (Expr.isInvalid()) return move(Expr);
497    return Actions.ActOnCXXThrow(ThrowLoc, move(Expr));
498  }
499}
500
501/// ParseCXXThis - This handles the C++ 'this' pointer.
502///
503/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
504/// a non-lvalue expression whose value is the address of the object for which
505/// the function is called.
506Parser::OwningExprResult Parser::ParseCXXThis() {
507  assert(Tok.is(tok::kw_this) && "Not 'this'!");
508  SourceLocation ThisLoc = ConsumeToken();
509  return Actions.ActOnCXXThis(ThisLoc);
510}
511
512/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
513/// Can be interpreted either as function-style casting ("int(x)")
514/// or class type construction ("ClassType(x,y,z)")
515/// or creation of a value-initialized type ("int()").
516///
517///       postfix-expression: [C++ 5.2p1]
518///         simple-type-specifier '(' expression-list[opt] ')'      [C++ 5.2.3]
519///         typename-specifier '(' expression-list[opt] ')'         [TODO]
520///
521Parser::OwningExprResult
522Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
523  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
524  TypeTy *TypeRep = Actions.ActOnTypeName(CurScope, DeclaratorInfo).get();
525
526  assert(Tok.is(tok::l_paren) && "Expected '('!");
527  SourceLocation LParenLoc = ConsumeParen();
528
529  ExprVector Exprs(Actions);
530  CommaLocsTy CommaLocs;
531
532  if (Tok.isNot(tok::r_paren)) {
533    if (ParseExpressionList(Exprs, CommaLocs)) {
534      SkipUntil(tok::r_paren);
535      return ExprError();
536    }
537  }
538
539  // Match the ')'.
540  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
541
542  // TypeRep could be null, if it references an invalid typedef.
543  if (!TypeRep)
544    return ExprError();
545
546  assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
547         "Unexpected number of commas!");
548  return Actions.ActOnCXXTypeConstructExpr(DS.getSourceRange(), TypeRep,
549                                           LParenLoc, move_arg(Exprs),
550                                           CommaLocs.data(), RParenLoc);
551}
552
553/// ParseCXXCondition - if/switch/while condition expression.
554///
555///       condition:
556///         expression
557///         type-specifier-seq declarator '=' assignment-expression
558/// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
559///             '=' assignment-expression
560///
561/// \param ExprResult if the condition was parsed as an expression, the
562/// parsed expression.
563///
564/// \param DeclResult if the condition was parsed as a declaration, the
565/// parsed declaration.
566///
567/// \returns true if there was a parsing, false otherwise.
568bool Parser::ParseCXXCondition(OwningExprResult &ExprResult,
569                               DeclPtrTy &DeclResult) {
570  if (!isCXXConditionDeclaration()) {
571    ExprResult = ParseExpression(); // expression
572    DeclResult = DeclPtrTy();
573    return ExprResult.isInvalid();
574  }
575
576  // type-specifier-seq
577  DeclSpec DS;
578  ParseSpecifierQualifierList(DS);
579
580  // declarator
581  Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
582  ParseDeclarator(DeclaratorInfo);
583
584  // simple-asm-expr[opt]
585  if (Tok.is(tok::kw_asm)) {
586    SourceLocation Loc;
587    OwningExprResult AsmLabel(ParseSimpleAsm(&Loc));
588    if (AsmLabel.isInvalid()) {
589      SkipUntil(tok::semi);
590      return true;
591    }
592    DeclaratorInfo.setAsmLabel(AsmLabel.release());
593    DeclaratorInfo.SetRangeEnd(Loc);
594  }
595
596  // If attributes are present, parse them.
597  if (Tok.is(tok::kw___attribute)) {
598    SourceLocation Loc;
599    AttributeList *AttrList = ParseGNUAttributes(&Loc);
600    DeclaratorInfo.AddAttributes(AttrList, Loc);
601  }
602
603  // Type-check the declaration itself.
604  Action::DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(CurScope,
605                                                                DeclaratorInfo);
606  DeclResult = Dcl.get();
607  ExprResult = ExprError();
608
609  // '=' assignment-expression
610  if (Tok.is(tok::equal)) {
611    SourceLocation EqualLoc = ConsumeToken();
612    OwningExprResult AssignExpr(ParseAssignmentExpression());
613    if (!AssignExpr.isInvalid())
614      Actions.AddInitializerToDecl(DeclResult, move(AssignExpr));
615  } else {
616    // FIXME: C++0x allows a braced-init-list
617    Diag(Tok, diag::err_expected_equal_after_declarator);
618  }
619
620  return false;
621}
622
623/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
624/// This should only be called when the current token is known to be part of
625/// simple-type-specifier.
626///
627///       simple-type-specifier:
628///         '::'[opt] nested-name-specifier[opt] type-name
629///         '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
630///         char
631///         wchar_t
632///         bool
633///         short
634///         int
635///         long
636///         signed
637///         unsigned
638///         float
639///         double
640///         void
641/// [GNU]   typeof-specifier
642/// [C++0x] auto               [TODO]
643///
644///       type-name:
645///         class-name
646///         enum-name
647///         typedef-name
648///
649void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
650  DS.SetRangeStart(Tok.getLocation());
651  const char *PrevSpec;
652  unsigned DiagID;
653  SourceLocation Loc = Tok.getLocation();
654
655  switch (Tok.getKind()) {
656  case tok::identifier:   // foo::bar
657  case tok::coloncolon:   // ::foo::bar
658    assert(0 && "Annotation token should already be formed!");
659  default:
660    assert(0 && "Not a simple-type-specifier token!");
661    abort();
662
663  // type-name
664  case tok::annot_typename: {
665    DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
666                       Tok.getAnnotationValue());
667    break;
668  }
669
670  // builtin types
671  case tok::kw_short:
672    DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
673    break;
674  case tok::kw_long:
675    DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
676    break;
677  case tok::kw_signed:
678    DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
679    break;
680  case tok::kw_unsigned:
681    DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
682    break;
683  case tok::kw_void:
684    DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
685    break;
686  case tok::kw_char:
687    DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
688    break;
689  case tok::kw_int:
690    DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
691    break;
692  case tok::kw_float:
693    DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
694    break;
695  case tok::kw_double:
696    DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
697    break;
698  case tok::kw_wchar_t:
699    DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
700    break;
701  case tok::kw_char16_t:
702    DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
703    break;
704  case tok::kw_char32_t:
705    DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
706    break;
707  case tok::kw_bool:
708    DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
709    break;
710
711  // GNU typeof support.
712  case tok::kw_typeof:
713    ParseTypeofSpecifier(DS);
714    DS.Finish(Diags, PP);
715    return;
716  }
717  if (Tok.is(tok::annot_typename))
718    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
719  else
720    DS.SetRangeEnd(Tok.getLocation());
721  ConsumeToken();
722  DS.Finish(Diags, PP);
723}
724
725/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
726/// [dcl.name]), which is a non-empty sequence of type-specifiers,
727/// e.g., "const short int". Note that the DeclSpec is *not* finished
728/// by parsing the type-specifier-seq, because these sequences are
729/// typically followed by some form of declarator. Returns true and
730/// emits diagnostics if this is not a type-specifier-seq, false
731/// otherwise.
732///
733///   type-specifier-seq: [C++ 8.1]
734///     type-specifier type-specifier-seq[opt]
735///
736bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
737  DS.SetRangeStart(Tok.getLocation());
738  const char *PrevSpec = 0;
739  unsigned DiagID;
740  bool isInvalid = 0;
741
742  // Parse one or more of the type specifiers.
743  if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID)) {
744    Diag(Tok, diag::err_operator_missing_type_specifier);
745    return true;
746  }
747
748  while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID)) ;
749
750  return false;
751}
752
753/// \brief Finish parsing a C++ unqualified-id that is a template-id of
754/// some form.
755///
756/// This routine is invoked when a '<' is encountered after an identifier or
757/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
758/// whether the unqualified-id is actually a template-id. This routine will
759/// then parse the template arguments and form the appropriate template-id to
760/// return to the caller.
761///
762/// \param SS the nested-name-specifier that precedes this template-id, if
763/// we're actually parsing a qualified-id.
764///
765/// \param Name for constructor and destructor names, this is the actual
766/// identifier that may be a template-name.
767///
768/// \param NameLoc the location of the class-name in a constructor or
769/// destructor.
770///
771/// \param EnteringContext whether we're entering the scope of the
772/// nested-name-specifier.
773///
774/// \param ObjectType if this unqualified-id occurs within a member access
775/// expression, the type of the base object whose member is being accessed.
776///
777/// \param Id as input, describes the template-name or operator-function-id
778/// that precedes the '<'. If template arguments were parsed successfully,
779/// will be updated with the template-id.
780///
781/// \returns true if a parse error occurred, false otherwise.
782bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
783                                          IdentifierInfo *Name,
784                                          SourceLocation NameLoc,
785                                          bool EnteringContext,
786                                          TypeTy *ObjectType,
787                                          UnqualifiedId &Id) {
788  assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
789
790  TemplateTy Template;
791  TemplateNameKind TNK = TNK_Non_template;
792  switch (Id.getKind()) {
793  case UnqualifiedId::IK_Identifier:
794  case UnqualifiedId::IK_OperatorFunctionId:
795  case UnqualifiedId::IK_LiteralOperatorId:
796    TNK = Actions.isTemplateName(CurScope, SS, Id, ObjectType, EnteringContext,
797                                 Template);
798    break;
799
800  case UnqualifiedId::IK_ConstructorName: {
801    UnqualifiedId TemplateName;
802    TemplateName.setIdentifier(Name, NameLoc);
803    TNK = Actions.isTemplateName(CurScope, SS, TemplateName, ObjectType,
804                                 EnteringContext, Template);
805    break;
806  }
807
808  case UnqualifiedId::IK_DestructorName: {
809    UnqualifiedId TemplateName;
810    TemplateName.setIdentifier(Name, NameLoc);
811    if (ObjectType) {
812      Template = Actions.ActOnDependentTemplateName(SourceLocation(), SS,
813                                                    TemplateName, ObjectType,
814                                                    EnteringContext);
815      TNK = TNK_Dependent_template_name;
816      if (!Template.get())
817        return true;
818    } else {
819      TNK = Actions.isTemplateName(CurScope, SS, TemplateName, ObjectType,
820                                   EnteringContext, Template);
821
822      if (TNK == TNK_Non_template && Id.DestructorName == 0) {
823        // The identifier following the destructor did not refer to a template
824        // or to a type. Complain.
825        if (ObjectType)
826          Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
827            << Name;
828        else
829          Diag(NameLoc, diag::err_destructor_class_name);
830        return true;
831      }
832    }
833    break;
834  }
835
836  default:
837    return false;
838  }
839
840  if (TNK == TNK_Non_template)
841    return false;
842
843  // Parse the enclosed template argument list.
844  SourceLocation LAngleLoc, RAngleLoc;
845  TemplateArgList TemplateArgs;
846  if (ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
847                                       &SS, true, LAngleLoc,
848                                       TemplateArgs,
849                                       RAngleLoc))
850    return true;
851
852  if (Id.getKind() == UnqualifiedId::IK_Identifier ||
853      Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
854      Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
855    // Form a parsed representation of the template-id to be stored in the
856    // UnqualifiedId.
857    TemplateIdAnnotation *TemplateId
858      = TemplateIdAnnotation::Allocate(TemplateArgs.size());
859
860    if (Id.getKind() == UnqualifiedId::IK_Identifier) {
861      TemplateId->Name = Id.Identifier;
862      TemplateId->Operator = OO_None;
863      TemplateId->TemplateNameLoc = Id.StartLocation;
864    } else {
865      TemplateId->Name = 0;
866      TemplateId->Operator = Id.OperatorFunctionId.Operator;
867      TemplateId->TemplateNameLoc = Id.StartLocation;
868    }
869
870    TemplateId->Template = Template.getAs<void*>();
871    TemplateId->Kind = TNK;
872    TemplateId->LAngleLoc = LAngleLoc;
873    TemplateId->RAngleLoc = RAngleLoc;
874    ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
875    for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
876         Arg != ArgEnd; ++Arg)
877      Args[Arg] = TemplateArgs[Arg];
878
879    Id.setTemplateId(TemplateId);
880    return false;
881  }
882
883  // Bundle the template arguments together.
884  ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
885                                     TemplateArgs.size());
886
887  // Constructor and destructor names.
888  Action::TypeResult Type
889    = Actions.ActOnTemplateIdType(Template, NameLoc,
890                                  LAngleLoc, TemplateArgsPtr,
891                                  RAngleLoc);
892  if (Type.isInvalid())
893    return true;
894
895  if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
896    Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
897  else
898    Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
899
900  return false;
901}
902
903/// \brief Parse an operator-function-id or conversion-function-id as part
904/// of a C++ unqualified-id.
905///
906/// This routine is responsible only for parsing the operator-function-id or
907/// conversion-function-id; it does not handle template arguments in any way.
908///
909/// \code
910///       operator-function-id: [C++ 13.5]
911///         'operator' operator
912///
913///       operator: one of
914///            new   delete  new[]   delete[]
915///            +     -    *  /    %  ^    &   |   ~
916///            !     =    <  >    += -=   *=  /=  %=
917///            ^=    &=   |= <<   >> >>= <<=  ==  !=
918///            <=    >=   && ||   ++ --   ,   ->* ->
919///            ()    []
920///
921///       conversion-function-id: [C++ 12.3.2]
922///         operator conversion-type-id
923///
924///       conversion-type-id:
925///         type-specifier-seq conversion-declarator[opt]
926///
927///       conversion-declarator:
928///         ptr-operator conversion-declarator[opt]
929/// \endcode
930///
931/// \param The nested-name-specifier that preceded this unqualified-id. If
932/// non-empty, then we are parsing the unqualified-id of a qualified-id.
933///
934/// \param EnteringContext whether we are entering the scope of the
935/// nested-name-specifier.
936///
937/// \param ObjectType if this unqualified-id occurs within a member access
938/// expression, the type of the base object whose member is being accessed.
939///
940/// \param Result on a successful parse, contains the parsed unqualified-id.
941///
942/// \returns true if parsing fails, false otherwise.
943bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
944                                        TypeTy *ObjectType,
945                                        UnqualifiedId &Result) {
946  assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
947
948  // Consume the 'operator' keyword.
949  SourceLocation KeywordLoc = ConsumeToken();
950
951  // Determine what kind of operator name we have.
952  unsigned SymbolIdx = 0;
953  SourceLocation SymbolLocations[3];
954  OverloadedOperatorKind Op = OO_None;
955  switch (Tok.getKind()) {
956    case tok::kw_new:
957    case tok::kw_delete: {
958      bool isNew = Tok.getKind() == tok::kw_new;
959      // Consume the 'new' or 'delete'.
960      SymbolLocations[SymbolIdx++] = ConsumeToken();
961      if (Tok.is(tok::l_square)) {
962        // Consume the '['.
963        SourceLocation LBracketLoc = ConsumeBracket();
964        // Consume the ']'.
965        SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square,
966                                                         LBracketLoc);
967        if (RBracketLoc.isInvalid())
968          return true;
969
970        SymbolLocations[SymbolIdx++] = LBracketLoc;
971        SymbolLocations[SymbolIdx++] = RBracketLoc;
972        Op = isNew? OO_Array_New : OO_Array_Delete;
973      } else {
974        Op = isNew? OO_New : OO_Delete;
975      }
976      break;
977    }
978
979#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
980    case tok::Token:                                                     \
981      SymbolLocations[SymbolIdx++] = ConsumeToken();                     \
982      Op = OO_##Name;                                                    \
983      break;
984#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
985#include "clang/Basic/OperatorKinds.def"
986
987    case tok::l_paren: {
988      // Consume the '('.
989      SourceLocation LParenLoc = ConsumeParen();
990      // Consume the ')'.
991      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren,
992                                                     LParenLoc);
993      if (RParenLoc.isInvalid())
994        return true;
995
996      SymbolLocations[SymbolIdx++] = LParenLoc;
997      SymbolLocations[SymbolIdx++] = RParenLoc;
998      Op = OO_Call;
999      break;
1000    }
1001
1002    case tok::l_square: {
1003      // Consume the '['.
1004      SourceLocation LBracketLoc = ConsumeBracket();
1005      // Consume the ']'.
1006      SourceLocation RBracketLoc = MatchRHSPunctuation(tok::r_square,
1007                                                       LBracketLoc);
1008      if (RBracketLoc.isInvalid())
1009        return true;
1010
1011      SymbolLocations[SymbolIdx++] = LBracketLoc;
1012      SymbolLocations[SymbolIdx++] = RBracketLoc;
1013      Op = OO_Subscript;
1014      break;
1015    }
1016
1017    case tok::code_completion: {
1018      // Code completion for the operator name.
1019      Actions.CodeCompleteOperatorName(CurScope);
1020
1021      // Consume the operator token.
1022      ConsumeToken();
1023
1024      // Don't try to parse any further.
1025      return true;
1026    }
1027
1028    default:
1029      break;
1030  }
1031
1032  if (Op != OO_None) {
1033    // We have parsed an operator-function-id.
1034    Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1035    return false;
1036  }
1037
1038  // Parse a literal-operator-id.
1039  //
1040  //   literal-operator-id: [C++0x 13.5.8]
1041  //     operator "" identifier
1042
1043  if (getLang().CPlusPlus0x && Tok.is(tok::string_literal)) {
1044    if (Tok.getLength() != 2)
1045      Diag(Tok.getLocation(), diag::err_operator_string_not_empty);
1046    ConsumeStringToken();
1047
1048    if (Tok.isNot(tok::identifier)) {
1049      Diag(Tok.getLocation(), diag::err_expected_ident);
1050      return true;
1051    }
1052
1053    IdentifierInfo *II = Tok.getIdentifierInfo();
1054    Result.setLiteralOperatorId(II, KeywordLoc, ConsumeToken());
1055    return false;
1056  }
1057
1058  // Parse a conversion-function-id.
1059  //
1060  //   conversion-function-id: [C++ 12.3.2]
1061  //     operator conversion-type-id
1062  //
1063  //   conversion-type-id:
1064  //     type-specifier-seq conversion-declarator[opt]
1065  //
1066  //   conversion-declarator:
1067  //     ptr-operator conversion-declarator[opt]
1068
1069  // Parse the type-specifier-seq.
1070  DeclSpec DS;
1071  if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
1072    return true;
1073
1074  // Parse the conversion-declarator, which is merely a sequence of
1075  // ptr-operators.
1076  Declarator D(DS, Declarator::TypeNameContext);
1077  ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
1078
1079  // Finish up the type.
1080  Action::TypeResult Ty = Actions.ActOnTypeName(CurScope, D);
1081  if (Ty.isInvalid())
1082    return true;
1083
1084  // Note that this is a conversion-function-id.
1085  Result.setConversionFunctionId(KeywordLoc, Ty.get(),
1086                                 D.getSourceRange().getEnd());
1087  return false;
1088}
1089
1090/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
1091/// name of an entity.
1092///
1093/// \code
1094///       unqualified-id: [C++ expr.prim.general]
1095///         identifier
1096///         operator-function-id
1097///         conversion-function-id
1098/// [C++0x] literal-operator-id [TODO]
1099///         ~ class-name
1100///         template-id
1101///
1102/// \endcode
1103///
1104/// \param The nested-name-specifier that preceded this unqualified-id. If
1105/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1106///
1107/// \param EnteringContext whether we are entering the scope of the
1108/// nested-name-specifier.
1109///
1110/// \param AllowDestructorName whether we allow parsing of a destructor name.
1111///
1112/// \param AllowConstructorName whether we allow parsing a constructor name.
1113///
1114/// \param ObjectType if this unqualified-id occurs within a member access
1115/// expression, the type of the base object whose member is being accessed.
1116///
1117/// \param Result on a successful parse, contains the parsed unqualified-id.
1118///
1119/// \returns true if parsing fails, false otherwise.
1120bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
1121                                bool AllowDestructorName,
1122                                bool AllowConstructorName,
1123                                TypeTy *ObjectType,
1124                                UnqualifiedId &Result) {
1125  // unqualified-id:
1126  //   identifier
1127  //   template-id (when it hasn't already been annotated)
1128  if (Tok.is(tok::identifier)) {
1129    // Consume the identifier.
1130    IdentifierInfo *Id = Tok.getIdentifierInfo();
1131    SourceLocation IdLoc = ConsumeToken();
1132
1133    if (AllowConstructorName &&
1134        Actions.isCurrentClassName(*Id, CurScope, &SS)) {
1135      // We have parsed a constructor name.
1136      Result.setConstructorName(Actions.getTypeName(*Id, IdLoc, CurScope,
1137                                                    &SS, false),
1138                                IdLoc, IdLoc);
1139    } else {
1140      // We have parsed an identifier.
1141      Result.setIdentifier(Id, IdLoc);
1142    }
1143
1144    // If the next token is a '<', we may have a template.
1145    if (Tok.is(tok::less))
1146      return ParseUnqualifiedIdTemplateId(SS, Id, IdLoc, EnteringContext,
1147                                          ObjectType, Result);
1148
1149    return false;
1150  }
1151
1152  // unqualified-id:
1153  //   template-id (already parsed and annotated)
1154  if (Tok.is(tok::annot_template_id)) {
1155    // FIXME: Could this be a constructor name???
1156
1157    // We have already parsed a template-id; consume the annotation token as
1158    // our unqualified-id.
1159    Result.setTemplateId(
1160                  static_cast<TemplateIdAnnotation*>(Tok.getAnnotationValue()));
1161    ConsumeToken();
1162    return false;
1163  }
1164
1165  // unqualified-id:
1166  //   operator-function-id
1167  //   conversion-function-id
1168  if (Tok.is(tok::kw_operator)) {
1169    if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
1170      return true;
1171
1172    // If we have an operator-function-id or a literal-operator-id and the next
1173    // token is a '<', we may have a
1174    //
1175    //   template-id:
1176    //     operator-function-id < template-argument-list[opt] >
1177    if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1178         Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
1179        Tok.is(tok::less))
1180      return ParseUnqualifiedIdTemplateId(SS, 0, SourceLocation(),
1181                                          EnteringContext, ObjectType,
1182                                          Result);
1183
1184    return false;
1185  }
1186
1187  if ((AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
1188    // C++ [expr.unary.op]p10:
1189    //   There is an ambiguity in the unary-expression ~X(), where X is a
1190    //   class-name. The ambiguity is resolved in favor of treating ~ as a
1191    //    unary complement rather than treating ~X as referring to a destructor.
1192
1193    // Parse the '~'.
1194    SourceLocation TildeLoc = ConsumeToken();
1195
1196    // Parse the class-name.
1197    if (Tok.isNot(tok::identifier)) {
1198      Diag(Tok, diag::err_destructor_class_name);
1199      return true;
1200    }
1201
1202    // Parse the class-name (or template-name in a simple-template-id).
1203    IdentifierInfo *ClassName = Tok.getIdentifierInfo();
1204    SourceLocation ClassNameLoc = ConsumeToken();
1205
1206    if (Tok.is(tok::less)) {
1207      Result.setDestructorName(TildeLoc, 0, ClassNameLoc);
1208      return ParseUnqualifiedIdTemplateId(SS, ClassName, ClassNameLoc,
1209                                          EnteringContext, ObjectType, Result);
1210    }
1211
1212    // Note that this is a destructor name.
1213    Action::TypeTy *Ty = Actions.getTypeName(*ClassName, ClassNameLoc,
1214                                             CurScope, &SS, false, ObjectType);
1215    if (!Ty) {
1216      if (ObjectType)
1217        Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
1218          << ClassName;
1219      else
1220        Diag(ClassNameLoc, diag::err_destructor_class_name);
1221      return true;
1222    }
1223
1224    Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
1225    return false;
1226  }
1227
1228  Diag(Tok, diag::err_expected_unqualified_id)
1229    << getLang().CPlusPlus;
1230  return true;
1231}
1232
1233/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
1234/// memory in a typesafe manner and call constructors.
1235///
1236/// This method is called to parse the new expression after the optional :: has
1237/// been already parsed.  If the :: was present, "UseGlobal" is true and "Start"
1238/// is its location.  Otherwise, "Start" is the location of the 'new' token.
1239///
1240///        new-expression:
1241///                   '::'[opt] 'new' new-placement[opt] new-type-id
1242///                                     new-initializer[opt]
1243///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
1244///                                     new-initializer[opt]
1245///
1246///        new-placement:
1247///                   '(' expression-list ')'
1248///
1249///        new-type-id:
1250///                   type-specifier-seq new-declarator[opt]
1251///
1252///        new-declarator:
1253///                   ptr-operator new-declarator[opt]
1254///                   direct-new-declarator
1255///
1256///        new-initializer:
1257///                   '(' expression-list[opt] ')'
1258/// [C++0x]           braced-init-list                                   [TODO]
1259///
1260Parser::OwningExprResult
1261Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
1262  assert(Tok.is(tok::kw_new) && "expected 'new' token");
1263  ConsumeToken();   // Consume 'new'
1264
1265  // A '(' now can be a new-placement or the '(' wrapping the type-id in the
1266  // second form of new-expression. It can't be a new-type-id.
1267
1268  ExprVector PlacementArgs(Actions);
1269  SourceLocation PlacementLParen, PlacementRParen;
1270
1271  bool ParenTypeId;
1272  DeclSpec DS;
1273  Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1274  if (Tok.is(tok::l_paren)) {
1275    // If it turns out to be a placement, we change the type location.
1276    PlacementLParen = ConsumeParen();
1277    if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
1278      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1279      return ExprError();
1280    }
1281
1282    PlacementRParen = MatchRHSPunctuation(tok::r_paren, PlacementLParen);
1283    if (PlacementRParen.isInvalid()) {
1284      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1285      return ExprError();
1286    }
1287
1288    if (PlacementArgs.empty()) {
1289      // Reset the placement locations. There was no placement.
1290      PlacementLParen = PlacementRParen = SourceLocation();
1291      ParenTypeId = true;
1292    } else {
1293      // We still need the type.
1294      if (Tok.is(tok::l_paren)) {
1295        SourceLocation LParen = ConsumeParen();
1296        ParseSpecifierQualifierList(DS);
1297        DeclaratorInfo.SetSourceRange(DS.getSourceRange());
1298        ParseDeclarator(DeclaratorInfo);
1299        MatchRHSPunctuation(tok::r_paren, LParen);
1300        ParenTypeId = true;
1301      } else {
1302        if (ParseCXXTypeSpecifierSeq(DS))
1303          DeclaratorInfo.setInvalidType(true);
1304        else {
1305          DeclaratorInfo.SetSourceRange(DS.getSourceRange());
1306          ParseDeclaratorInternal(DeclaratorInfo,
1307                                  &Parser::ParseDirectNewDeclarator);
1308        }
1309        ParenTypeId = false;
1310      }
1311    }
1312  } else {
1313    // A new-type-id is a simplified type-id, where essentially the
1314    // direct-declarator is replaced by a direct-new-declarator.
1315    if (ParseCXXTypeSpecifierSeq(DS))
1316      DeclaratorInfo.setInvalidType(true);
1317    else {
1318      DeclaratorInfo.SetSourceRange(DS.getSourceRange());
1319      ParseDeclaratorInternal(DeclaratorInfo,
1320                              &Parser::ParseDirectNewDeclarator);
1321    }
1322    ParenTypeId = false;
1323  }
1324  if (DeclaratorInfo.isInvalidType()) {
1325    SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1326    return ExprError();
1327  }
1328
1329  ExprVector ConstructorArgs(Actions);
1330  SourceLocation ConstructorLParen, ConstructorRParen;
1331
1332  if (Tok.is(tok::l_paren)) {
1333    ConstructorLParen = ConsumeParen();
1334    if (Tok.isNot(tok::r_paren)) {
1335      CommaLocsTy CommaLocs;
1336      if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
1337        SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1338        return ExprError();
1339      }
1340    }
1341    ConstructorRParen = MatchRHSPunctuation(tok::r_paren, ConstructorLParen);
1342    if (ConstructorRParen.isInvalid()) {
1343      SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
1344      return ExprError();
1345    }
1346  }
1347
1348  return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
1349                             move_arg(PlacementArgs), PlacementRParen,
1350                             ParenTypeId, DeclaratorInfo, ConstructorLParen,
1351                             move_arg(ConstructorArgs), ConstructorRParen);
1352}
1353
1354/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
1355/// passed to ParseDeclaratorInternal.
1356///
1357///        direct-new-declarator:
1358///                   '[' expression ']'
1359///                   direct-new-declarator '[' constant-expression ']'
1360///
1361void Parser::ParseDirectNewDeclarator(Declarator &D) {
1362  // Parse the array dimensions.
1363  bool first = true;
1364  while (Tok.is(tok::l_square)) {
1365    SourceLocation LLoc = ConsumeBracket();
1366    OwningExprResult Size(first ? ParseExpression()
1367                                : ParseConstantExpression());
1368    if (Size.isInvalid()) {
1369      // Recover
1370      SkipUntil(tok::r_square);
1371      return;
1372    }
1373    first = false;
1374
1375    SourceLocation RLoc = MatchRHSPunctuation(tok::r_square, LLoc);
1376    D.AddTypeInfo(DeclaratorChunk::getArray(0, /*static=*/false, /*star=*/false,
1377                                            Size.release(), LLoc, RLoc),
1378                  RLoc);
1379
1380    if (RLoc.isInvalid())
1381      return;
1382  }
1383}
1384
1385/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
1386/// This ambiguity appears in the syntax of the C++ new operator.
1387///
1388///        new-expression:
1389///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
1390///                                     new-initializer[opt]
1391///
1392///        new-placement:
1393///                   '(' expression-list ')'
1394///
1395bool Parser::ParseExpressionListOrTypeId(ExprListTy &PlacementArgs,
1396                                         Declarator &D) {
1397  // The '(' was already consumed.
1398  if (isTypeIdInParens()) {
1399    ParseSpecifierQualifierList(D.getMutableDeclSpec());
1400    D.SetSourceRange(D.getDeclSpec().getSourceRange());
1401    ParseDeclarator(D);
1402    return D.isInvalidType();
1403  }
1404
1405  // It's not a type, it has to be an expression list.
1406  // Discard the comma locations - ActOnCXXNew has enough parameters.
1407  CommaLocsTy CommaLocs;
1408  return ParseExpressionList(PlacementArgs, CommaLocs);
1409}
1410
1411/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
1412/// to free memory allocated by new.
1413///
1414/// This method is called to parse the 'delete' expression after the optional
1415/// '::' has been already parsed.  If the '::' was present, "UseGlobal" is true
1416/// and "Start" is its location.  Otherwise, "Start" is the location of the
1417/// 'delete' token.
1418///
1419///        delete-expression:
1420///                   '::'[opt] 'delete' cast-expression
1421///                   '::'[opt] 'delete' '[' ']' cast-expression
1422Parser::OwningExprResult
1423Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
1424  assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
1425  ConsumeToken(); // Consume 'delete'
1426
1427  // Array delete?
1428  bool ArrayDelete = false;
1429  if (Tok.is(tok::l_square)) {
1430    ArrayDelete = true;
1431    SourceLocation LHS = ConsumeBracket();
1432    SourceLocation RHS = MatchRHSPunctuation(tok::r_square, LHS);
1433    if (RHS.isInvalid())
1434      return ExprError();
1435  }
1436
1437  OwningExprResult Operand(ParseCastExpression(false));
1438  if (Operand.isInvalid())
1439    return move(Operand);
1440
1441  return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, move(Operand));
1442}
1443
1444static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
1445  switch(kind) {
1446  default: assert(false && "Not a known unary type trait.");
1447  case tok::kw___has_nothrow_assign:      return UTT_HasNothrowAssign;
1448  case tok::kw___has_nothrow_copy:        return UTT_HasNothrowCopy;
1449  case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
1450  case tok::kw___has_trivial_assign:      return UTT_HasTrivialAssign;
1451  case tok::kw___has_trivial_copy:        return UTT_HasTrivialCopy;
1452  case tok::kw___has_trivial_constructor: return UTT_HasTrivialConstructor;
1453  case tok::kw___has_trivial_destructor:  return UTT_HasTrivialDestructor;
1454  case tok::kw___has_virtual_destructor:  return UTT_HasVirtualDestructor;
1455  case tok::kw___is_abstract:             return UTT_IsAbstract;
1456  case tok::kw___is_class:                return UTT_IsClass;
1457  case tok::kw___is_empty:                return UTT_IsEmpty;
1458  case tok::kw___is_enum:                 return UTT_IsEnum;
1459  case tok::kw___is_pod:                  return UTT_IsPOD;
1460  case tok::kw___is_polymorphic:          return UTT_IsPolymorphic;
1461  case tok::kw___is_union:                return UTT_IsUnion;
1462  case tok::kw___is_literal:              return UTT_IsLiteral;
1463  }
1464}
1465
1466/// ParseUnaryTypeTrait - Parse the built-in unary type-trait
1467/// pseudo-functions that allow implementation of the TR1/C++0x type traits
1468/// templates.
1469///
1470///       primary-expression:
1471/// [GNU]             unary-type-trait '(' type-id ')'
1472///
1473Parser::OwningExprResult Parser::ParseUnaryTypeTrait() {
1474  UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
1475  SourceLocation Loc = ConsumeToken();
1476
1477  SourceLocation LParen = Tok.getLocation();
1478  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen))
1479    return ExprError();
1480
1481  // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
1482  // there will be cryptic errors about mismatched parentheses and missing
1483  // specifiers.
1484  TypeResult Ty = ParseTypeName();
1485
1486  SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen);
1487
1488  if (Ty.isInvalid())
1489    return ExprError();
1490
1491  return Actions.ActOnUnaryTypeTrait(UTT, Loc, LParen, Ty.get(), RParen);
1492}
1493
1494/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
1495/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
1496/// based on the context past the parens.
1497Parser::OwningExprResult
1498Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
1499                                         TypeTy *&CastTy,
1500                                         SourceLocation LParenLoc,
1501                                         SourceLocation &RParenLoc) {
1502  assert(getLang().CPlusPlus && "Should only be called for C++!");
1503  assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
1504  assert(isTypeIdInParens() && "Not a type-id!");
1505
1506  OwningExprResult Result(Actions, true);
1507  CastTy = 0;
1508
1509  // We need to disambiguate a very ugly part of the C++ syntax:
1510  //
1511  // (T())x;  - type-id
1512  // (T())*x; - type-id
1513  // (T())/x; - expression
1514  // (T());   - expression
1515  //
1516  // The bad news is that we cannot use the specialized tentative parser, since
1517  // it can only verify that the thing inside the parens can be parsed as
1518  // type-id, it is not useful for determining the context past the parens.
1519  //
1520  // The good news is that the parser can disambiguate this part without
1521  // making any unnecessary Action calls.
1522  //
1523  // It uses a scheme similar to parsing inline methods. The parenthesized
1524  // tokens are cached, the context that follows is determined (possibly by
1525  // parsing a cast-expression), and then we re-introduce the cached tokens
1526  // into the token stream and parse them appropriately.
1527
1528  ParenParseOption ParseAs;
1529  CachedTokens Toks;
1530
1531  // Store the tokens of the parentheses. We will parse them after we determine
1532  // the context that follows them.
1533  if (!ConsumeAndStoreUntil(tok::r_paren, tok::unknown, Toks, tok::semi)) {
1534    // We didn't find the ')' we expected.
1535    MatchRHSPunctuation(tok::r_paren, LParenLoc);
1536    return ExprError();
1537  }
1538
1539  if (Tok.is(tok::l_brace)) {
1540    ParseAs = CompoundLiteral;
1541  } else {
1542    bool NotCastExpr;
1543    // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
1544    if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
1545      NotCastExpr = true;
1546    } else {
1547      // Try parsing the cast-expression that may follow.
1548      // If it is not a cast-expression, NotCastExpr will be true and no token
1549      // will be consumed.
1550      Result = ParseCastExpression(false/*isUnaryExpression*/,
1551                                   false/*isAddressofOperand*/,
1552                                   NotCastExpr, false);
1553    }
1554
1555    // If we parsed a cast-expression, it's really a type-id, otherwise it's
1556    // an expression.
1557    ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
1558  }
1559
1560  // The current token should go after the cached tokens.
1561  Toks.push_back(Tok);
1562  // Re-enter the stored parenthesized tokens into the token stream, so we may
1563  // parse them now.
1564  PP.EnterTokenStream(Toks.data(), Toks.size(),
1565                      true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
1566  // Drop the current token and bring the first cached one. It's the same token
1567  // as when we entered this function.
1568  ConsumeAnyToken();
1569
1570  if (ParseAs >= CompoundLiteral) {
1571    TypeResult Ty = ParseTypeName();
1572
1573    // Match the ')'.
1574    if (Tok.is(tok::r_paren))
1575      RParenLoc = ConsumeParen();
1576    else
1577      MatchRHSPunctuation(tok::r_paren, LParenLoc);
1578
1579    if (ParseAs == CompoundLiteral) {
1580      ExprType = CompoundLiteral;
1581      return ParseCompoundLiteralExpression(Ty.get(), LParenLoc, RParenLoc);
1582    }
1583
1584    // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
1585    assert(ParseAs == CastExpr);
1586
1587    if (Ty.isInvalid())
1588      return ExprError();
1589
1590    CastTy = Ty.get();
1591
1592    // Result is what ParseCastExpression returned earlier.
1593    if (!Result.isInvalid())
1594      Result = Actions.ActOnCastExpr(CurScope, LParenLoc, CastTy, RParenLoc,
1595                                     move(Result));
1596    return move(Result);
1597  }
1598
1599  // Not a compound literal, and not followed by a cast-expression.
1600  assert(ParseAs == SimpleExpr);
1601
1602  ExprType = SimpleExpr;
1603  Result = ParseExpression();
1604  if (!Result.isInvalid() && Tok.is(tok::r_paren))
1605    Result = Actions.ActOnParenExpr(LParenLoc, Tok.getLocation(), move(Result));
1606
1607  // Match the ')'.
1608  if (Result.isInvalid()) {
1609    SkipUntil(tok::r_paren);
1610    return ExprError();
1611  }
1612
1613  if (Tok.is(tok::r_paren))
1614    RParenLoc = ConsumeParen();
1615  else
1616    MatchRHSPunctuation(tok::r_paren, LParenLoc);
1617
1618  return move(Result);
1619}
1620