ParseDeclCXX.cpp revision 9cfbe48a7a20a217fdb2920b29b67ae7941cb116
1//===--- ParseDeclCXX.cpp - C++ Declaration 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 C++ Declaration portions of the Parser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "clang/Parse/ParseDiagnostic.h"
16#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
18#include "ExtensionRAIIObject.h"
19using namespace clang;
20
21/// ParseNamespace - We know that the current token is a namespace keyword. This
22/// may either be a top level namespace or a block-level namespace alias.
23///
24///       namespace-definition: [C++ 7.3: basic.namespace]
25///         named-namespace-definition
26///         unnamed-namespace-definition
27///
28///       unnamed-namespace-definition:
29///         'namespace' attributes[opt] '{' namespace-body '}'
30///
31///       named-namespace-definition:
32///         original-namespace-definition
33///         extension-namespace-definition
34///
35///       original-namespace-definition:
36///         'namespace' identifier attributes[opt] '{' namespace-body '}'
37///
38///       extension-namespace-definition:
39///         'namespace' original-namespace-name '{' namespace-body '}'
40///
41///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
42///         'namespace' identifier '=' qualified-namespace-specifier ';'
43///
44Parser::DeclPtrTy Parser::ParseNamespace(unsigned Context,
45                                         SourceLocation &DeclEnd) {
46  assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
47  SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
48
49  SourceLocation IdentLoc;
50  IdentifierInfo *Ident = 0;
51
52  Token attrTok;
53
54  if (Tok.is(tok::identifier)) {
55    Ident = Tok.getIdentifierInfo();
56    IdentLoc = ConsumeToken();  // eat the identifier.
57  }
58
59  // Read label attributes, if present.
60  Action::AttrTy *AttrList = 0;
61  if (Tok.is(tok::kw___attribute)) {
62    attrTok = Tok;
63
64    // FIXME: save these somewhere.
65    AttrList = ParseAttributes();
66  }
67
68  if (Tok.is(tok::equal)) {
69    if (AttrList)
70      Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
71
72    return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
73  }
74
75  if (Tok.isNot(tok::l_brace)) {
76    Diag(Tok, Ident ? diag::err_expected_lbrace :
77         diag::err_expected_ident_lbrace);
78    return DeclPtrTy();
79  }
80
81  SourceLocation LBrace = ConsumeBrace();
82
83  // Enter a scope for the namespace.
84  ParseScope NamespaceScope(this, Scope::DeclScope);
85
86  DeclPtrTy NamespcDecl =
87    Actions.ActOnStartNamespaceDef(CurScope, IdentLoc, Ident, LBrace);
88
89  PrettyStackTraceActionsDecl CrashInfo(NamespcDecl, NamespaceLoc, Actions,
90                                        PP.getSourceManager(),
91                                        "parsing namespace");
92
93  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof))
94    ParseExternalDeclaration();
95
96  // Leave the namespace scope.
97  NamespaceScope.Exit();
98
99  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBrace);
100  Actions.ActOnFinishNamespaceDef(NamespcDecl, RBraceLoc);
101
102  DeclEnd = RBraceLoc;
103  return NamespcDecl;
104}
105
106/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
107/// alias definition.
108///
109Parser::DeclPtrTy Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
110                                              SourceLocation AliasLoc,
111                                              IdentifierInfo *Alias,
112                                              SourceLocation &DeclEnd) {
113  assert(Tok.is(tok::equal) && "Not equal token");
114
115  ConsumeToken(); // eat the '='.
116
117  CXXScopeSpec SS;
118  // Parse (optional) nested-name-specifier.
119  ParseOptionalCXXScopeSpecifier(SS);
120
121  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
122    Diag(Tok, diag::err_expected_namespace_name);
123    // Skip to end of the definition and eat the ';'.
124    SkipUntil(tok::semi);
125    return DeclPtrTy();
126  }
127
128  // Parse identifier.
129  IdentifierInfo *Ident = Tok.getIdentifierInfo();
130  SourceLocation IdentLoc = ConsumeToken();
131
132  // Eat the ';'.
133  DeclEnd = Tok.getLocation();
134  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
135                   "", tok::semi);
136
137  return Actions.ActOnNamespaceAliasDef(CurScope, NamespaceLoc, AliasLoc, Alias,
138                                        SS, IdentLoc, Ident);
139}
140
141/// ParseLinkage - We know that the current token is a string_literal
142/// and just before that, that extern was seen.
143///
144///       linkage-specification: [C++ 7.5p2: dcl.link]
145///         'extern' string-literal '{' declaration-seq[opt] '}'
146///         'extern' string-literal declaration
147///
148Parser::DeclPtrTy Parser::ParseLinkage(unsigned Context) {
149  assert(Tok.is(tok::string_literal) && "Not a string literal!");
150  llvm::SmallVector<char, 8> LangBuffer;
151  // LangBuffer is guaranteed to be big enough.
152  LangBuffer.resize(Tok.getLength());
153  const char *LangBufPtr = &LangBuffer[0];
154  unsigned StrSize = PP.getSpelling(Tok, LangBufPtr);
155
156  SourceLocation Loc = ConsumeStringToken();
157
158  ParseScope LinkageScope(this, Scope::DeclScope);
159  DeclPtrTy LinkageSpec
160    = Actions.ActOnStartLinkageSpecification(CurScope,
161                                             /*FIXME: */SourceLocation(),
162                                             Loc, LangBufPtr, StrSize,
163                                       Tok.is(tok::l_brace)? Tok.getLocation()
164                                                           : SourceLocation());
165
166  if (Tok.isNot(tok::l_brace)) {
167    ParseDeclarationOrFunctionDefinition();
168    return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec,
169                                                   SourceLocation());
170  }
171
172  SourceLocation LBrace = ConsumeBrace();
173  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
174    ParseExternalDeclaration();
175  }
176
177  SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
178  return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec, RBrace);
179}
180
181/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
182/// using-directive. Assumes that current token is 'using'.
183Parser::DeclPtrTy Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
184                                                     SourceLocation &DeclEnd) {
185  assert(Tok.is(tok::kw_using) && "Not using token");
186
187  // Eat 'using'.
188  SourceLocation UsingLoc = ConsumeToken();
189
190  if (Tok.is(tok::kw_namespace))
191    // Next token after 'using' is 'namespace' so it must be using-directive
192    return ParseUsingDirective(Context, UsingLoc, DeclEnd);
193
194  // Otherwise, it must be using-declaration.
195  return ParseUsingDeclaration(Context, UsingLoc, DeclEnd);
196}
197
198/// ParseUsingDirective - Parse C++ using-directive, assumes
199/// that current token is 'namespace' and 'using' was already parsed.
200///
201///       using-directive: [C++ 7.3.p4: namespace.udir]
202///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
203///                 namespace-name ;
204/// [GNU] using-directive:
205///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
206///                 namespace-name attributes[opt] ;
207///
208Parser::DeclPtrTy Parser::ParseUsingDirective(unsigned Context,
209                                              SourceLocation UsingLoc,
210                                              SourceLocation &DeclEnd) {
211  assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
212
213  // Eat 'namespace'.
214  SourceLocation NamespcLoc = ConsumeToken();
215
216  CXXScopeSpec SS;
217  // Parse (optional) nested-name-specifier.
218  ParseOptionalCXXScopeSpecifier(SS);
219
220  AttributeList *AttrList = 0;
221  IdentifierInfo *NamespcName = 0;
222  SourceLocation IdentLoc = SourceLocation();
223
224  // Parse namespace-name.
225  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
226    Diag(Tok, diag::err_expected_namespace_name);
227    // If there was invalid namespace name, skip to end of decl, and eat ';'.
228    SkipUntil(tok::semi);
229    // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
230    return DeclPtrTy();
231  }
232
233  // Parse identifier.
234  NamespcName = Tok.getIdentifierInfo();
235  IdentLoc = ConsumeToken();
236
237  // Parse (optional) attributes (most likely GNU strong-using extension).
238  if (Tok.is(tok::kw___attribute))
239    AttrList = ParseAttributes();
240
241  // Eat ';'.
242  DeclEnd = Tok.getLocation();
243  ExpectAndConsume(tok::semi,
244                   AttrList ? diag::err_expected_semi_after_attribute_list :
245                   diag::err_expected_semi_after_namespace_name, "", tok::semi);
246
247  return Actions.ActOnUsingDirective(CurScope, UsingLoc, NamespcLoc, SS,
248                                      IdentLoc, NamespcName, AttrList);
249}
250
251/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that
252/// 'using' was already seen.
253///
254///     using-declaration: [C++ 7.3.p3: namespace.udecl]
255///       'using' 'typename'[opt] ::[opt] nested-name-specifier
256///               unqualified-id
257///       'using' :: unqualified-id
258///
259Parser::DeclPtrTy Parser::ParseUsingDeclaration(unsigned Context,
260                                                SourceLocation UsingLoc,
261                                                SourceLocation &DeclEnd) {
262  CXXScopeSpec SS;
263  bool IsTypeName;
264
265  // Ignore optional 'typename'.
266  if (Tok.is(tok::kw_typename)) {
267    ConsumeToken();
268    IsTypeName = true;
269  }
270  else
271    IsTypeName = false;
272
273  // Parse nested-name-specifier.
274  ParseOptionalCXXScopeSpecifier(SS);
275
276  AttributeList *AttrList = 0;
277  IdentifierInfo *TargetName = 0;
278  SourceLocation IdentLoc = SourceLocation();
279
280  // Check nested-name specifier.
281  if (SS.isInvalid()) {
282    SkipUntil(tok::semi);
283    return DeclPtrTy();
284  }
285  if (Tok.is(tok::annot_template_id)) {
286    Diag(Tok, diag::err_unexpected_template_spec_in_using);
287    SkipUntil(tok::semi);
288    return DeclPtrTy();
289  }
290  if (Tok.isNot(tok::identifier)) {
291    Diag(Tok, diag::err_expected_ident_in_using);
292    // If there was invalid identifier, skip to end of decl, and eat ';'.
293    SkipUntil(tok::semi);
294    return DeclPtrTy();
295  }
296
297  // Parse identifier.
298  TargetName = Tok.getIdentifierInfo();
299  IdentLoc = ConsumeToken();
300
301  // Parse (optional) attributes (most likely GNU strong-using extension).
302  if (Tok.is(tok::kw___attribute))
303    AttrList = ParseAttributes();
304
305  // Eat ';'.
306  DeclEnd = Tok.getLocation();
307  ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
308                   AttrList ? "attributes list" : "namespace name", tok::semi);
309
310  return Actions.ActOnUsingDeclaration(CurScope, UsingLoc, SS,
311                                      IdentLoc, TargetName, AttrList, IsTypeName);
312}
313
314/// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion.
315///
316///      static_assert-declaration:
317///        static_assert ( constant-expression  ,  string-literal  ) ;
318///
319Parser::DeclPtrTy Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
320  assert(Tok.is(tok::kw_static_assert) && "Not a static_assert declaration");
321  SourceLocation StaticAssertLoc = ConsumeToken();
322
323  if (Tok.isNot(tok::l_paren)) {
324    Diag(Tok, diag::err_expected_lparen);
325    return DeclPtrTy();
326  }
327
328  SourceLocation LParenLoc = ConsumeParen();
329
330  OwningExprResult AssertExpr(ParseConstantExpression());
331  if (AssertExpr.isInvalid()) {
332    SkipUntil(tok::semi);
333    return DeclPtrTy();
334  }
335
336  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
337    return DeclPtrTy();
338
339  if (Tok.isNot(tok::string_literal)) {
340    Diag(Tok, diag::err_expected_string_literal);
341    SkipUntil(tok::semi);
342    return DeclPtrTy();
343  }
344
345  OwningExprResult AssertMessage(ParseStringLiteralExpression());
346  if (AssertMessage.isInvalid())
347    return DeclPtrTy();
348
349  MatchRHSPunctuation(tok::r_paren, LParenLoc);
350
351  DeclEnd = Tok.getLocation();
352  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_static_assert);
353
354  return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, move(AssertExpr),
355                                              move(AssertMessage));
356}
357
358/// ParseClassName - Parse a C++ class-name, which names a class. Note
359/// that we only check that the result names a type; semantic analysis
360/// will need to verify that the type names a class. The result is
361/// either a type or NULL, depending on whether a type name was
362/// found.
363///
364///       class-name: [C++ 9.1]
365///         identifier
366///         simple-template-id
367///
368Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation,
369                                          const CXXScopeSpec *SS) {
370  // Check whether we have a template-id that names a type.
371  if (Tok.is(tok::annot_template_id)) {
372    TemplateIdAnnotation *TemplateId
373      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
374    if (TemplateId->Kind == TNK_Type_template) {
375      AnnotateTemplateIdTokenAsType(SS);
376
377      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
378      TypeTy *Type = Tok.getAnnotationValue();
379      EndLocation = Tok.getAnnotationEndLoc();
380      ConsumeToken();
381
382      if (Type)
383        return Type;
384      return true;
385    }
386
387    // Fall through to produce an error below.
388  }
389
390  if (Tok.isNot(tok::identifier)) {
391    Diag(Tok, diag::err_expected_class_name);
392    return true;
393  }
394
395  // We have an identifier; check whether it is actually a type.
396  TypeTy *Type = Actions.getTypeName(*Tok.getIdentifierInfo(),
397                                     Tok.getLocation(), CurScope, SS);
398  if (!Type) {
399    Diag(Tok, diag::err_expected_class_name);
400    return true;
401  }
402
403  // Consume the identifier.
404  EndLocation = ConsumeToken();
405  return Type;
406}
407
408/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
409/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
410/// until we reach the start of a definition or see a token that
411/// cannot start a definition.
412///
413///       class-specifier: [C++ class]
414///         class-head '{' member-specification[opt] '}'
415///         class-head '{' member-specification[opt] '}' attributes[opt]
416///       class-head:
417///         class-key identifier[opt] base-clause[opt]
418///         class-key nested-name-specifier identifier base-clause[opt]
419///         class-key nested-name-specifier[opt] simple-template-id
420///                          base-clause[opt]
421/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
422/// [GNU]   class-key attributes[opt] nested-name-specifier
423///                          identifier base-clause[opt]
424/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
425///                          simple-template-id base-clause[opt]
426///       class-key:
427///         'class'
428///         'struct'
429///         'union'
430///
431///       elaborated-type-specifier: [C++ dcl.type.elab]
432///         class-key ::[opt] nested-name-specifier[opt] identifier
433///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
434///                          simple-template-id
435///
436///  Note that the C++ class-specifier and elaborated-type-specifier,
437///  together, subsume the C99 struct-or-union-specifier:
438///
439///       struct-or-union-specifier: [C99 6.7.2.1]
440///         struct-or-union identifier[opt] '{' struct-contents '}'
441///         struct-or-union identifier
442/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
443///                                                         '}' attributes[opt]
444/// [GNU]   struct-or-union attributes[opt] identifier
445///       struct-or-union:
446///         'struct'
447///         'union'
448void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
449                                 SourceLocation StartLoc, DeclSpec &DS,
450                                 const ParsedTemplateInfo &TemplateInfo,
451                                 AccessSpecifier AS) {
452  DeclSpec::TST TagType;
453  if (TagTokKind == tok::kw_struct)
454    TagType = DeclSpec::TST_struct;
455  else if (TagTokKind == tok::kw_class)
456    TagType = DeclSpec::TST_class;
457  else {
458    assert(TagTokKind == tok::kw_union && "Not a class specifier");
459    TagType = DeclSpec::TST_union;
460  }
461
462  AttributeList *Attr = 0;
463  // If attributes exist after tag, parse them.
464  if (Tok.is(tok::kw___attribute))
465    Attr = ParseAttributes();
466
467  // If declspecs exist after tag, parse them.
468  if (Tok.is(tok::kw___declspec))
469    Attr = ParseMicrosoftDeclSpec(Attr);
470
471  // Parse the (optional) nested-name-specifier.
472  CXXScopeSpec SS;
473  if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS))
474    if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
475      Diag(Tok, diag::err_expected_ident);
476
477  // Parse the (optional) class name or simple-template-id.
478  IdentifierInfo *Name = 0;
479  SourceLocation NameLoc;
480  TemplateIdAnnotation *TemplateId = 0;
481  if (Tok.is(tok::identifier)) {
482    Name = Tok.getIdentifierInfo();
483    NameLoc = ConsumeToken();
484  } else if (Tok.is(tok::annot_template_id)) {
485    TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
486    NameLoc = ConsumeToken();
487
488    if (TemplateId->Kind != TNK_Type_template) {
489      // The template-name in the simple-template-id refers to
490      // something other than a class template. Give an appropriate
491      // error message and skip to the ';'.
492      SourceRange Range(NameLoc);
493      if (SS.isNotEmpty())
494        Range.setBegin(SS.getBeginLoc());
495
496      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
497        << Name << static_cast<int>(TemplateId->Kind) << Range;
498
499      DS.SetTypeSpecError();
500      SkipUntil(tok::semi, false, true);
501      TemplateId->Destroy();
502      return;
503    }
504  }
505
506  // There are three options here.  If we have 'struct foo;', then
507  // this is a forward declaration.  If we have 'struct foo {...' or
508  // 'struct foo :...' then this is a definition. Otherwise we have
509  // something like 'struct foo xyz', a reference.
510  Action::TagKind TK;
511  if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon)))
512    TK = Action::TK_Definition;
513  else if (Tok.is(tok::semi) && !DS.isFriendSpecified())
514    TK = Action::TK_Declaration;
515  else
516    TK = Action::TK_Reference;
517
518  if (!Name && !TemplateId && TK != Action::TK_Definition) {
519    // We have a declaration or reference to an anonymous class.
520    Diag(StartLoc, diag::err_anon_type_definition)
521      << DeclSpec::getSpecifierName(TagType);
522
523    // Skip the rest of this declarator, up until the comma or semicolon.
524    SkipUntil(tok::comma, true);
525
526    if (TemplateId)
527      TemplateId->Destroy();
528    return;
529  }
530
531  // Create the tag portion of the class or class template.
532  Action::DeclResult TagOrTempResult;
533  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
534
535  // FIXME: When TK == TK_Reference and we have a template-id, we need
536  // to turn that template-id into a type.
537
538  bool Owned = false;
539  if (TemplateId && TK != Action::TK_Reference) {
540    // Explicit specialization, class template partial specialization,
541    // or explicit instantiation.
542    ASTTemplateArgsPtr TemplateArgsPtr(Actions,
543                                       TemplateId->getTemplateArgs(),
544                                       TemplateId->getTemplateArgIsType(),
545                                       TemplateId->NumArgs);
546    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
547        TK == Action::TK_Declaration) {
548      // This is an explicit instantiation of a class template.
549      TagOrTempResult
550        = Actions.ActOnExplicitInstantiation(CurScope,
551                                             TemplateInfo.TemplateLoc,
552                                             TagType,
553                                             StartLoc,
554                                             SS,
555                                     TemplateTy::make(TemplateId->Template),
556                                             TemplateId->TemplateNameLoc,
557                                             TemplateId->LAngleLoc,
558                                             TemplateArgsPtr,
559                                      TemplateId->getTemplateArgLocations(),
560                                             TemplateId->RAngleLoc,
561                                             Attr);
562    } else {
563      // This is an explicit specialization or a class template
564      // partial specialization.
565      TemplateParameterLists FakedParamLists;
566
567      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
568        // This looks like an explicit instantiation, because we have
569        // something like
570        //
571        //   template class Foo<X>
572        //
573        // but it actually has a definition. Most likely, this was
574        // meant to be an explicit specialization, but the user forgot
575        // the '<>' after 'template'.
576        assert(TK == Action::TK_Definition && "Expected a definition here");
577
578        SourceLocation LAngleLoc
579          = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
580        Diag(TemplateId->TemplateNameLoc,
581             diag::err_explicit_instantiation_with_definition)
582          << SourceRange(TemplateInfo.TemplateLoc)
583          << CodeModificationHint::CreateInsertion(LAngleLoc, "<>");
584
585        // Create a fake template parameter list that contains only
586        // "template<>", so that we treat this construct as a class
587        // template specialization.
588        FakedParamLists.push_back(
589          Actions.ActOnTemplateParameterList(0, SourceLocation(),
590                                             TemplateInfo.TemplateLoc,
591                                             LAngleLoc,
592                                             0, 0,
593                                             LAngleLoc));
594        TemplateParams = &FakedParamLists;
595      }
596
597      // Build the class template specialization.
598      TagOrTempResult
599        = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TK,
600                       StartLoc, SS,
601                       TemplateTy::make(TemplateId->Template),
602                       TemplateId->TemplateNameLoc,
603                       TemplateId->LAngleLoc,
604                       TemplateArgsPtr,
605                       TemplateId->getTemplateArgLocations(),
606                       TemplateId->RAngleLoc,
607                       Attr,
608                       Action::MultiTemplateParamsArg(Actions,
609                                    TemplateParams? &(*TemplateParams)[0] : 0,
610                                 TemplateParams? TemplateParams->size() : 0));
611    }
612    TemplateId->Destroy();
613  } else if (TemplateParams && TK != Action::TK_Reference) {
614    // Class template declaration or definition.
615    TagOrTempResult = Actions.ActOnClassTemplate(CurScope, TagType, TK,
616                                                 StartLoc, SS, Name, NameLoc,
617                                                 Attr,
618                       Action::MultiTemplateParamsArg(Actions,
619                                                      &(*TemplateParams)[0],
620                                                      TemplateParams->size()),
621                                                 AS);
622  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
623             TK == Action::TK_Declaration) {
624    // Explicit instantiation of a member of a class template
625    // specialization, e.g.,
626    //
627    //   template struct Outer<int>::Inner;
628    //
629    TagOrTempResult
630      = Actions.ActOnExplicitInstantiation(CurScope,
631                                           TemplateInfo.TemplateLoc,
632                                           TagType, StartLoc, SS, Name,
633                                           NameLoc, Attr);
634  } else {
635    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
636        TK == Action::TK_Definition) {
637      // FIXME: Diagnose this particular error.
638    }
639
640    // Declaration or definition of a class type
641    TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, SS,
642                                       Name, NameLoc, Attr, AS, Owned);
643  }
644
645  // Parse the optional base clause (C++ only).
646  if (getLang().CPlusPlus && Tok.is(tok::colon))
647    ParseBaseClause(TagOrTempResult.get());
648
649  // If there is a body, parse it and inform the actions module.
650  if (Tok.is(tok::l_brace))
651    if (getLang().CPlusPlus)
652      ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
653    else
654      ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
655  else if (TK == Action::TK_Definition) {
656    // FIXME: Complain that we have a base-specifier list but no
657    // definition.
658    Diag(Tok, diag::err_expected_lbrace);
659  }
660
661  const char *PrevSpec = 0;
662  if (TagOrTempResult.isInvalid()) {
663    DS.SetTypeSpecError();
664    return;
665  }
666
667  if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec,
668                         TagOrTempResult.get().getAs<void>(), Owned))
669    Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
670
671  if (DS.isFriendSpecified())
672    Actions.ActOnFriendDecl(CurScope, DS.getFriendSpecLoc(),
673                            TagOrTempResult.get());
674}
675
676/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
677///
678///       base-clause : [C++ class.derived]
679///         ':' base-specifier-list
680///       base-specifier-list:
681///         base-specifier '...'[opt]
682///         base-specifier-list ',' base-specifier '...'[opt]
683void Parser::ParseBaseClause(DeclPtrTy ClassDecl) {
684  assert(Tok.is(tok::colon) && "Not a base clause");
685  ConsumeToken();
686
687  // Build up an array of parsed base specifiers.
688  llvm::SmallVector<BaseTy *, 8> BaseInfo;
689
690  while (true) {
691    // Parse a base-specifier.
692    BaseResult Result = ParseBaseSpecifier(ClassDecl);
693    if (Result.isInvalid()) {
694      // Skip the rest of this base specifier, up until the comma or
695      // opening brace.
696      SkipUntil(tok::comma, tok::l_brace, true, true);
697    } else {
698      // Add this to our array of base specifiers.
699      BaseInfo.push_back(Result.get());
700    }
701
702    // If the next token is a comma, consume it and keep reading
703    // base-specifiers.
704    if (Tok.isNot(tok::comma)) break;
705
706    // Consume the comma.
707    ConsumeToken();
708  }
709
710  // Attach the base specifiers
711  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
712}
713
714/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
715/// one entry in the base class list of a class specifier, for example:
716///    class foo : public bar, virtual private baz {
717/// 'public bar' and 'virtual private baz' are each base-specifiers.
718///
719///       base-specifier: [C++ class.derived]
720///         ::[opt] nested-name-specifier[opt] class-name
721///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
722///                        class-name
723///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
724///                        class-name
725Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) {
726  bool IsVirtual = false;
727  SourceLocation StartLoc = Tok.getLocation();
728
729  // Parse the 'virtual' keyword.
730  if (Tok.is(tok::kw_virtual))  {
731    ConsumeToken();
732    IsVirtual = true;
733  }
734
735  // Parse an (optional) access specifier.
736  AccessSpecifier Access = getAccessSpecifierIfPresent();
737  if (Access)
738    ConsumeToken();
739
740  // Parse the 'virtual' keyword (again!), in case it came after the
741  // access specifier.
742  if (Tok.is(tok::kw_virtual))  {
743    SourceLocation VirtualLoc = ConsumeToken();
744    if (IsVirtual) {
745      // Complain about duplicate 'virtual'
746      Diag(VirtualLoc, diag::err_dup_virtual)
747        << CodeModificationHint::CreateRemoval(SourceRange(VirtualLoc));
748    }
749
750    IsVirtual = true;
751  }
752
753  // Parse optional '::' and optional nested-name-specifier.
754  CXXScopeSpec SS;
755  ParseOptionalCXXScopeSpecifier(SS);
756
757  // The location of the base class itself.
758  SourceLocation BaseLoc = Tok.getLocation();
759
760  // Parse the class-name.
761  SourceLocation EndLocation;
762  TypeResult BaseType = ParseClassName(EndLocation, &SS);
763  if (BaseType.isInvalid())
764    return true;
765
766  // Find the complete source range for the base-specifier.
767  SourceRange Range(StartLoc, EndLocation);
768
769  // Notify semantic analysis that we have parsed a complete
770  // base-specifier.
771  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
772                                    BaseType.get(), BaseLoc);
773}
774
775/// getAccessSpecifierIfPresent - Determine whether the next token is
776/// a C++ access-specifier.
777///
778///       access-specifier: [C++ class.derived]
779///         'private'
780///         'protected'
781///         'public'
782AccessSpecifier Parser::getAccessSpecifierIfPresent() const
783{
784  switch (Tok.getKind()) {
785  default: return AS_none;
786  case tok::kw_private: return AS_private;
787  case tok::kw_protected: return AS_protected;
788  case tok::kw_public: return AS_public;
789  }
790}
791
792/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
793///
794///       member-declaration:
795///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
796///         function-definition ';'[opt]
797///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
798///         using-declaration                                            [TODO]
799/// [C++0x] static_assert-declaration
800///         template-declaration
801/// [GNU]   '__extension__' member-declaration
802///
803///       member-declarator-list:
804///         member-declarator
805///         member-declarator-list ',' member-declarator
806///
807///       member-declarator:
808///         declarator pure-specifier[opt]
809///         declarator constant-initializer[opt]
810///         identifier[opt] ':' constant-expression
811///
812///       pure-specifier:
813///         '= 0'
814///
815///       constant-initializer:
816///         '=' constant-expression
817///
818void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) {
819  // static_assert-declaration
820  if (Tok.is(tok::kw_static_assert)) {
821    SourceLocation DeclEnd;
822    ParseStaticAssertDeclaration(DeclEnd);
823    return;
824  }
825
826  if (Tok.is(tok::kw_template)) {
827    SourceLocation DeclEnd;
828    ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
829                                         AS);
830    return;
831  }
832
833  // Handle:  member-declaration ::= '__extension__' member-declaration
834  if (Tok.is(tok::kw___extension__)) {
835    // __extension__ silences extension warnings in the subexpression.
836    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
837    ConsumeToken();
838    return ParseCXXClassMemberDeclaration(AS);
839  }
840
841  if (Tok.is(tok::kw_using)) {
842    // Eat 'using'.
843    SourceLocation UsingLoc = ConsumeToken();
844
845    if (Tok.is(tok::kw_namespace)) {
846      Diag(UsingLoc, diag::err_using_namespace_in_class);
847      SkipUntil(tok::semi, true, true);
848    }
849    else {
850      SourceLocation DeclEnd;
851      // Otherwise, it must be using-declaration.
852      ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd);
853    }
854    return;
855  }
856
857  SourceLocation DSStart = Tok.getLocation();
858  // decl-specifier-seq:
859  // Parse the common declaration-specifiers piece.
860  DeclSpec DS;
861  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS);
862
863  if (Tok.is(tok::semi)) {
864    ConsumeToken();
865    // C++ 9.2p7: The member-declarator-list can be omitted only after a
866    // class-specifier or an enum-specifier or in a friend declaration.
867    // FIXME: Friend declarations.
868    switch (DS.getTypeSpecType()) {
869    case DeclSpec::TST_struct:
870    case DeclSpec::TST_union:
871    case DeclSpec::TST_class:
872    case DeclSpec::TST_enum:
873      Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
874      return;
875    default:
876      Diag(DSStart, diag::err_no_declarators);
877      return;
878    }
879  }
880
881  Declarator DeclaratorInfo(DS, Declarator::MemberContext);
882
883  if (Tok.isNot(tok::colon)) {
884    // Parse the first declarator.
885    ParseDeclarator(DeclaratorInfo);
886    // Error parsing the declarator?
887    if (!DeclaratorInfo.hasName()) {
888      // If so, skip until the semi-colon or a }.
889      SkipUntil(tok::r_brace, true);
890      if (Tok.is(tok::semi))
891        ConsumeToken();
892      return;
893    }
894
895    // function-definition:
896    if (Tok.is(tok::l_brace)
897        || (DeclaratorInfo.isFunctionDeclarator() &&
898            (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) {
899      if (!DeclaratorInfo.isFunctionDeclarator()) {
900        Diag(Tok, diag::err_func_def_no_params);
901        ConsumeBrace();
902        SkipUntil(tok::r_brace, true);
903        return;
904      }
905
906      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
907        Diag(Tok, diag::err_function_declared_typedef);
908        // This recovery skips the entire function body. It would be nice
909        // to simply call ParseCXXInlineMethodDef() below, however Sema
910        // assumes the declarator represents a function, not a typedef.
911        ConsumeBrace();
912        SkipUntil(tok::r_brace, true);
913        return;
914      }
915
916      ParseCXXInlineMethodDef(AS, DeclaratorInfo);
917      return;
918    }
919  }
920
921  // member-declarator-list:
922  //   member-declarator
923  //   member-declarator-list ',' member-declarator
924
925  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
926  OwningExprResult BitfieldSize(Actions);
927  OwningExprResult Init(Actions);
928  bool Deleted = false;
929
930  while (1) {
931
932    // member-declarator:
933    //   declarator pure-specifier[opt]
934    //   declarator constant-initializer[opt]
935    //   identifier[opt] ':' constant-expression
936
937    if (Tok.is(tok::colon)) {
938      ConsumeToken();
939      BitfieldSize = ParseConstantExpression();
940      if (BitfieldSize.isInvalid())
941        SkipUntil(tok::comma, true, true);
942    }
943
944    // pure-specifier:
945    //   '= 0'
946    //
947    // constant-initializer:
948    //   '=' constant-expression
949    //
950    // defaulted/deleted function-definition:
951    //   '=' 'default'                          [TODO]
952    //   '=' 'delete'
953
954    if (Tok.is(tok::equal)) {
955      ConsumeToken();
956      if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
957        ConsumeToken();
958        Deleted = true;
959      } else {
960        Init = ParseInitializer();
961        if (Init.isInvalid())
962          SkipUntil(tok::comma, true, true);
963      }
964    }
965
966    // If attributes exist after the declarator, parse them.
967    if (Tok.is(tok::kw___attribute)) {
968      SourceLocation Loc;
969      AttributeList *AttrList = ParseAttributes(&Loc);
970      DeclaratorInfo.AddAttributes(AttrList, Loc);
971    }
972
973    // NOTE: If Sema is the Action module and declarator is an instance field,
974    // this call will *not* return the created decl; It will return null.
975    // See Sema::ActOnCXXMemberDeclarator for details.
976    DeclPtrTy ThisDecl = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
977                                                          DeclaratorInfo,
978                                                          BitfieldSize.release(),
979                                                          Init.release(),
980                                                          Deleted);
981    if (ThisDecl)
982      DeclsInGroup.push_back(ThisDecl);
983
984    if (DeclaratorInfo.isFunctionDeclarator() &&
985        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
986          != DeclSpec::SCS_typedef) {
987      // We just declared a member function. If this member function
988      // has any default arguments, we'll need to parse them later.
989      LateParsedMethodDeclaration *LateMethod = 0;
990      DeclaratorChunk::FunctionTypeInfo &FTI
991        = DeclaratorInfo.getTypeObject(0).Fun;
992      for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
993        if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
994          if (!LateMethod) {
995            // Push this method onto the stack of late-parsed method
996            // declarations.
997            getCurrentClass().MethodDecls.push_back(
998                                   LateParsedMethodDeclaration(ThisDecl));
999            LateMethod = &getCurrentClass().MethodDecls.back();
1000
1001            // Add all of the parameters prior to this one (they don't
1002            // have default arguments).
1003            LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1004            for (unsigned I = 0; I < ParamIdx; ++I)
1005              LateMethod->DefaultArgs.push_back(
1006                        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param));
1007          }
1008
1009          // Add this parameter to the list of parameters (it or may
1010          // not have a default argument).
1011          LateMethod->DefaultArgs.push_back(
1012            LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1013                                      FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1014        }
1015      }
1016    }
1017
1018    // If we don't have a comma, it is either the end of the list (a ';')
1019    // or an error, bail out.
1020    if (Tok.isNot(tok::comma))
1021      break;
1022
1023    // Consume the comma.
1024    ConsumeToken();
1025
1026    // Parse the next declarator.
1027    DeclaratorInfo.clear();
1028    BitfieldSize = 0;
1029    Init = 0;
1030    Deleted = false;
1031
1032    // Attributes are only allowed on the second declarator.
1033    if (Tok.is(tok::kw___attribute)) {
1034      SourceLocation Loc;
1035      AttributeList *AttrList = ParseAttributes(&Loc);
1036      DeclaratorInfo.AddAttributes(AttrList, Loc);
1037    }
1038
1039    if (Tok.isNot(tok::colon))
1040      ParseDeclarator(DeclaratorInfo);
1041  }
1042
1043  if (Tok.is(tok::semi)) {
1044    ConsumeToken();
1045    Actions.FinalizeDeclaratorGroup(CurScope, DS, DeclsInGroup.data(),
1046                                    DeclsInGroup.size());
1047    return;
1048  }
1049
1050  Diag(Tok, diag::err_expected_semi_decl_list);
1051  // Skip to end of block or statement
1052  SkipUntil(tok::r_brace, true, true);
1053  if (Tok.is(tok::semi))
1054    ConsumeToken();
1055  return;
1056}
1057
1058/// ParseCXXMemberSpecification - Parse the class definition.
1059///
1060///       member-specification:
1061///         member-declaration member-specification[opt]
1062///         access-specifier ':' member-specification[opt]
1063///
1064void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
1065                                         unsigned TagType, DeclPtrTy TagDecl) {
1066  assert((TagType == DeclSpec::TST_struct ||
1067         TagType == DeclSpec::TST_union  ||
1068         TagType == DeclSpec::TST_class) && "Invalid TagType!");
1069
1070  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1071                                        PP.getSourceManager(),
1072                                        "parsing struct/union/class body");
1073
1074  SourceLocation LBraceLoc = ConsumeBrace();
1075
1076  // Determine whether this is a top-level (non-nested) class.
1077  bool TopLevelClass = ClassStack.empty() ||
1078    CurScope->isInCXXInlineMethodScope();
1079
1080  // Enter a scope for the class.
1081  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
1082
1083  // Note that we are parsing a new (potentially-nested) class definition.
1084  ParsingClassDefinition ParsingDef(*this, TagDecl, TopLevelClass);
1085
1086  if (TagDecl)
1087    Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1088  else {
1089    SkipUntil(tok::r_brace, false, false);
1090    return;
1091  }
1092
1093  // C++ 11p3: Members of a class defined with the keyword class are private
1094  // by default. Members of a class defined with the keywords struct or union
1095  // are public by default.
1096  AccessSpecifier CurAS;
1097  if (TagType == DeclSpec::TST_class)
1098    CurAS = AS_private;
1099  else
1100    CurAS = AS_public;
1101
1102  // While we still have something to read, read the member-declarations.
1103  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1104    // Each iteration of this loop reads one member-declaration.
1105
1106    // Check for extraneous top-level semicolon.
1107    if (Tok.is(tok::semi)) {
1108      Diag(Tok, diag::ext_extra_struct_semi);
1109      ConsumeToken();
1110      continue;
1111    }
1112
1113    AccessSpecifier AS = getAccessSpecifierIfPresent();
1114    if (AS != AS_none) {
1115      // Current token is a C++ access specifier.
1116      CurAS = AS;
1117      ConsumeToken();
1118      ExpectAndConsume(tok::colon, diag::err_expected_colon);
1119      continue;
1120    }
1121
1122    // Parse all the comma separated declarators.
1123    ParseCXXClassMemberDeclaration(CurAS);
1124  }
1125
1126  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1127
1128  AttributeList *AttrList = 0;
1129  // If attributes exist after class contents, parse them.
1130  if (Tok.is(tok::kw___attribute))
1131    AttrList = ParseAttributes(); // FIXME: where should I put them?
1132
1133  Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
1134                                            LBraceLoc, RBraceLoc);
1135
1136  // C++ 9.2p2: Within the class member-specification, the class is regarded as
1137  // complete within function bodies, default arguments,
1138  // exception-specifications, and constructor ctor-initializers (including
1139  // such things in nested classes).
1140  //
1141  // FIXME: Only function bodies and constructor ctor-initializers are
1142  // parsed correctly, fix the rest.
1143  if (TopLevelClass) {
1144    // We are not inside a nested class. This class and its nested classes
1145    // are complete and we can parse the delayed portions of method
1146    // declarations and the lexed inline method definitions.
1147    ParseLexedMethodDeclarations(getCurrentClass());
1148    ParseLexedMethodDefs(getCurrentClass());
1149  }
1150
1151  // Leave the class scope.
1152  ParsingDef.Pop();
1153  ClassScope.Exit();
1154
1155  Actions.ActOnTagFinishDefinition(CurScope, TagDecl);
1156}
1157
1158/// ParseConstructorInitializer - Parse a C++ constructor initializer,
1159/// which explicitly initializes the members or base classes of a
1160/// class (C++ [class.base.init]). For example, the three initializers
1161/// after the ':' in the Derived constructor below:
1162///
1163/// @code
1164/// class Base { };
1165/// class Derived : Base {
1166///   int x;
1167///   float f;
1168/// public:
1169///   Derived(float f) : Base(), x(17), f(f) { }
1170/// };
1171/// @endcode
1172///
1173/// [C++]  ctor-initializer:
1174///          ':' mem-initializer-list
1175///
1176/// [C++]  mem-initializer-list:
1177///          mem-initializer
1178///          mem-initializer , mem-initializer-list
1179void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) {
1180  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
1181
1182  SourceLocation ColonLoc = ConsumeToken();
1183
1184  llvm::SmallVector<MemInitTy*, 4> MemInitializers;
1185
1186  do {
1187    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
1188    if (!MemInit.isInvalid())
1189      MemInitializers.push_back(MemInit.get());
1190
1191    if (Tok.is(tok::comma))
1192      ConsumeToken();
1193    else if (Tok.is(tok::l_brace))
1194      break;
1195    else {
1196      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1197      Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
1198      SkipUntil(tok::l_brace, true, true);
1199      break;
1200    }
1201  } while (true);
1202
1203  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
1204                               MemInitializers.data(), MemInitializers.size());
1205}
1206
1207/// ParseMemInitializer - Parse a C++ member initializer, which is
1208/// part of a constructor initializer that explicitly initializes one
1209/// member or base class (C++ [class.base.init]). See
1210/// ParseConstructorInitializer for an example.
1211///
1212/// [C++] mem-initializer:
1213///         mem-initializer-id '(' expression-list[opt] ')'
1214///
1215/// [C++] mem-initializer-id:
1216///         '::'[opt] nested-name-specifier[opt] class-name
1217///         identifier
1218Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) {
1219  // FIXME: parse '::'[opt] nested-name-specifier[opt]
1220
1221  if (Tok.isNot(tok::identifier)) {
1222    Diag(Tok, diag::err_expected_member_or_base_name);
1223    return true;
1224  }
1225
1226  // Get the identifier. This may be a member name or a class name,
1227  // but we'll let the semantic analysis determine which it is.
1228  IdentifierInfo *II = Tok.getIdentifierInfo();
1229  SourceLocation IdLoc = ConsumeToken();
1230
1231  // Parse the '('.
1232  if (Tok.isNot(tok::l_paren)) {
1233    Diag(Tok, diag::err_expected_lparen);
1234    return true;
1235  }
1236  SourceLocation LParenLoc = ConsumeParen();
1237
1238  // Parse the optional expression-list.
1239  ExprVector ArgExprs(Actions);
1240  CommaLocsTy CommaLocs;
1241  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
1242    SkipUntil(tok::r_paren);
1243    return true;
1244  }
1245
1246  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1247
1248  return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, II, IdLoc,
1249                                     LParenLoc, ArgExprs.take(),
1250                                     ArgExprs.size(), CommaLocs.data(),
1251                                     RParenLoc);
1252}
1253
1254/// ParseExceptionSpecification - Parse a C++ exception-specification
1255/// (C++ [except.spec]).
1256///
1257///       exception-specification:
1258///         'throw' '(' type-id-list [opt] ')'
1259/// [MS]    'throw' '(' '...' ')'
1260///
1261///       type-id-list:
1262///         type-id
1263///         type-id-list ',' type-id
1264///
1265bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc,
1266                                         llvm::SmallVector<TypeTy*, 2>
1267                                             &Exceptions,
1268                                         llvm::SmallVector<SourceRange, 2>
1269                                             &Ranges,
1270                                         bool &hasAnyExceptionSpec) {
1271  assert(Tok.is(tok::kw_throw) && "expected throw");
1272
1273  SourceLocation ThrowLoc = ConsumeToken();
1274
1275  if (!Tok.is(tok::l_paren)) {
1276    return Diag(Tok, diag::err_expected_lparen_after) << "throw";
1277  }
1278  SourceLocation LParenLoc = ConsumeParen();
1279
1280  // Parse throw(...), a Microsoft extension that means "this function
1281  // can throw anything".
1282  if (Tok.is(tok::ellipsis)) {
1283    hasAnyExceptionSpec = true;
1284    SourceLocation EllipsisLoc = ConsumeToken();
1285    if (!getLang().Microsoft)
1286      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
1287    EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1288    return false;
1289  }
1290
1291  // Parse the sequence of type-ids.
1292  SourceRange Range;
1293  while (Tok.isNot(tok::r_paren)) {
1294    TypeResult Res(ParseTypeName(&Range));
1295    if (!Res.isInvalid()) {
1296      Exceptions.push_back(Res.get());
1297      Ranges.push_back(Range);
1298    }
1299    if (Tok.is(tok::comma))
1300      ConsumeToken();
1301    else
1302      break;
1303  }
1304
1305  EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1306  return false;
1307}
1308
1309/// \brief We have just started parsing the definition of a new class,
1310/// so push that class onto our stack of classes that is currently
1311/// being parsed.
1312void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool TopLevelClass) {
1313  assert((TopLevelClass || !ClassStack.empty()) &&
1314         "Nested class without outer class");
1315  ClassStack.push(new ParsingClass(ClassDecl, TopLevelClass));
1316}
1317
1318/// \brief Deallocate the given parsed class and all of its nested
1319/// classes.
1320void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
1321  for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I)
1322    DeallocateParsedClasses(Class->NestedClasses[I]);
1323  delete Class;
1324}
1325
1326/// \brief Pop the top class of the stack of classes that are
1327/// currently being parsed.
1328///
1329/// This routine should be called when we have finished parsing the
1330/// definition of a class, but have not yet popped the Scope
1331/// associated with the class's definition.
1332///
1333/// \returns true if the class we've popped is a top-level class,
1334/// false otherwise.
1335void Parser::PopParsingClass() {
1336  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
1337
1338  ParsingClass *Victim = ClassStack.top();
1339  ClassStack.pop();
1340  if (Victim->TopLevelClass) {
1341    // Deallocate all of the nested classes of this class,
1342    // recursively: we don't need to keep any of this information.
1343    DeallocateParsedClasses(Victim);
1344    return;
1345  }
1346  assert(!ClassStack.empty() && "Missing top-level class?");
1347
1348  if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() &&
1349      Victim->NestedClasses.empty()) {
1350    // The victim is a nested class, but we will not need to perform
1351    // any processing after the definition of this class since it has
1352    // no members whose handling was delayed. Therefore, we can just
1353    // remove this nested class.
1354    delete Victim;
1355    return;
1356  }
1357
1358  // This nested class has some members that will need to be processed
1359  // after the top-level class is completely defined. Therefore, add
1360  // it to the list of nested classes within its parent.
1361  assert(CurScope->isClassScope() && "Nested class outside of class scope?");
1362  ClassStack.top()->NestedClasses.push_back(Victim);
1363  Victim->TemplateScope = CurScope->getParent()->isTemplateParamScope();
1364}
1365