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