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