ParseDeclCXX.cpp revision 3f9a8a60614b763785d54ad08821745d03a4af70
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  unsigned DiagID;
414  // Check for duplicate type specifiers (e.g. "int decltype(a)").
415  if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
416                         DiagID, Result.release()))
417    Diag(StartLoc, DiagID) << PrevSpec;
418}
419
420/// ParseClassName - Parse a C++ class-name, which names a class. Note
421/// that we only check that the result names a type; semantic analysis
422/// will need to verify that the type names a class. The result is
423/// either a type or NULL, depending on whether a type name was
424/// found.
425///
426///       class-name: [C++ 9.1]
427///         identifier
428///         simple-template-id
429///
430Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation,
431                                          const CXXScopeSpec *SS,
432                                          bool DestrExpected) {
433  // Check whether we have a template-id that names a type.
434  if (Tok.is(tok::annot_template_id)) {
435    TemplateIdAnnotation *TemplateId
436      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
437    if (TemplateId->Kind == TNK_Type_template) {
438      AnnotateTemplateIdTokenAsType(SS);
439
440      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
441      TypeTy *Type = Tok.getAnnotationValue();
442      EndLocation = Tok.getAnnotationEndLoc();
443      ConsumeToken();
444
445      if (Type)
446        return Type;
447      return true;
448    }
449
450    // Fall through to produce an error below.
451  }
452
453  if (Tok.isNot(tok::identifier)) {
454    Diag(Tok, diag::err_expected_class_name);
455    return true;
456  }
457
458  // We have an identifier; check whether it is actually a type.
459  TypeTy *Type = Actions.getTypeName(*Tok.getIdentifierInfo(),
460                                     Tok.getLocation(), CurScope, SS);
461  if (!Type) {
462    Diag(Tok, DestrExpected ? diag::err_destructor_class_name
463                            : diag::err_expected_class_name);
464    return true;
465  }
466
467  // Consume the identifier.
468  EndLocation = ConsumeToken();
469  return Type;
470}
471
472/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
473/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
474/// until we reach the start of a definition or see a token that
475/// cannot start a definition.
476///
477///       class-specifier: [C++ class]
478///         class-head '{' member-specification[opt] '}'
479///         class-head '{' member-specification[opt] '}' attributes[opt]
480///       class-head:
481///         class-key identifier[opt] base-clause[opt]
482///         class-key nested-name-specifier identifier base-clause[opt]
483///         class-key nested-name-specifier[opt] simple-template-id
484///                          base-clause[opt]
485/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
486/// [GNU]   class-key attributes[opt] nested-name-specifier
487///                          identifier base-clause[opt]
488/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
489///                          simple-template-id base-clause[opt]
490///       class-key:
491///         'class'
492///         'struct'
493///         'union'
494///
495///       elaborated-type-specifier: [C++ dcl.type.elab]
496///         class-key ::[opt] nested-name-specifier[opt] identifier
497///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
498///                          simple-template-id
499///
500///  Note that the C++ class-specifier and elaborated-type-specifier,
501///  together, subsume the C99 struct-or-union-specifier:
502///
503///       struct-or-union-specifier: [C99 6.7.2.1]
504///         struct-or-union identifier[opt] '{' struct-contents '}'
505///         struct-or-union identifier
506/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
507///                                                         '}' attributes[opt]
508/// [GNU]   struct-or-union attributes[opt] identifier
509///       struct-or-union:
510///         'struct'
511///         'union'
512void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
513                                 SourceLocation StartLoc, DeclSpec &DS,
514                                 const ParsedTemplateInfo &TemplateInfo,
515                                 AccessSpecifier AS) {
516  DeclSpec::TST TagType;
517  if (TagTokKind == tok::kw_struct)
518    TagType = DeclSpec::TST_struct;
519  else if (TagTokKind == tok::kw_class)
520    TagType = DeclSpec::TST_class;
521  else {
522    assert(TagTokKind == tok::kw_union && "Not a class specifier");
523    TagType = DeclSpec::TST_union;
524  }
525
526  AttributeList *Attr = 0;
527  // If attributes exist after tag, parse them.
528  if (Tok.is(tok::kw___attribute))
529    Attr = ParseAttributes();
530
531  // If declspecs exist after tag, parse them.
532  if (Tok.is(tok::kw___declspec))
533    Attr = ParseMicrosoftDeclSpec(Attr);
534
535  // Parse the (optional) nested-name-specifier.
536  CXXScopeSpec SS;
537  if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS))
538    if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
539      Diag(Tok, diag::err_expected_ident);
540
541  // Parse the (optional) class name or simple-template-id.
542  IdentifierInfo *Name = 0;
543  SourceLocation NameLoc;
544  TemplateIdAnnotation *TemplateId = 0;
545  if (Tok.is(tok::identifier)) {
546    Name = Tok.getIdentifierInfo();
547    NameLoc = ConsumeToken();
548  } else if (Tok.is(tok::annot_template_id)) {
549    TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
550    NameLoc = ConsumeToken();
551
552    if (TemplateId->Kind != TNK_Type_template) {
553      // The template-name in the simple-template-id refers to
554      // something other than a class template. Give an appropriate
555      // error message and skip to the ';'.
556      SourceRange Range(NameLoc);
557      if (SS.isNotEmpty())
558        Range.setBegin(SS.getBeginLoc());
559
560      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
561        << Name << static_cast<int>(TemplateId->Kind) << Range;
562
563      DS.SetTypeSpecError();
564      SkipUntil(tok::semi, false, true);
565      TemplateId->Destroy();
566      return;
567    }
568  }
569
570  // There are four options here.  If we have 'struct foo;', then this
571  // is either a forward declaration or a friend declaration, which
572  // have to be treated differently.  If we have 'struct foo {...' or
573  // 'struct foo :...' then this is a definition. Otherwise we have
574  // something like 'struct foo xyz', a reference.
575  Action::TagUseKind TUK;
576  if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon)))
577    TUK = Action::TUK_Definition;
578  else if (Tok.is(tok::semi))
579    TUK = DS.isFriendSpecified() ? Action::TUK_Friend : Action::TUK_Declaration;
580  else
581    TUK = Action::TUK_Reference;
582
583  if (!Name && !TemplateId && TUK != Action::TUK_Definition) {
584    // We have a declaration or reference to an anonymous class.
585    Diag(StartLoc, diag::err_anon_type_definition)
586      << DeclSpec::getSpecifierName(TagType);
587
588    // Skip the rest of this declarator, up until the comma or semicolon.
589    SkipUntil(tok::comma, true);
590
591    if (TemplateId)
592      TemplateId->Destroy();
593    return;
594  }
595
596  // Create the tag portion of the class or class template.
597  Action::DeclResult TagOrTempResult;
598  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
599
600  // FIXME: When TUK == TUK_Reference and we have a template-id, we need
601  // to turn that template-id into a type.
602
603  bool Owned = false;
604  if (TemplateId && TUK != Action::TUK_Reference && TUK != Action::TUK_Friend) {
605    // Explicit specialization, class template partial specialization,
606    // or explicit instantiation.
607    ASTTemplateArgsPtr TemplateArgsPtr(Actions,
608                                       TemplateId->getTemplateArgs(),
609                                       TemplateId->getTemplateArgIsType(),
610                                       TemplateId->NumArgs);
611    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
612        TUK == Action::TUK_Declaration) {
613      // This is an explicit instantiation of a class template.
614      TagOrTempResult
615        = Actions.ActOnExplicitInstantiation(CurScope,
616                                             TemplateInfo.TemplateLoc,
617                                             TagType,
618                                             StartLoc,
619                                             SS,
620                                     TemplateTy::make(TemplateId->Template),
621                                             TemplateId->TemplateNameLoc,
622                                             TemplateId->LAngleLoc,
623                                             TemplateArgsPtr,
624                                      TemplateId->getTemplateArgLocations(),
625                                             TemplateId->RAngleLoc,
626                                             Attr);
627    } else {
628      // This is an explicit specialization or a class template
629      // partial specialization.
630      TemplateParameterLists FakedParamLists;
631
632      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
633        // This looks like an explicit instantiation, because we have
634        // something like
635        //
636        //   template class Foo<X>
637        //
638        // but it actually has a definition. Most likely, this was
639        // meant to be an explicit specialization, but the user forgot
640        // the '<>' after 'template'.
641        assert(TUK == Action::TUK_Definition && "Expected a definition here");
642
643        SourceLocation LAngleLoc
644          = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
645        Diag(TemplateId->TemplateNameLoc,
646             diag::err_explicit_instantiation_with_definition)
647          << SourceRange(TemplateInfo.TemplateLoc)
648          << CodeModificationHint::CreateInsertion(LAngleLoc, "<>");
649
650        // Create a fake template parameter list that contains only
651        // "template<>", so that we treat this construct as a class
652        // template specialization.
653        FakedParamLists.push_back(
654          Actions.ActOnTemplateParameterList(0, SourceLocation(),
655                                             TemplateInfo.TemplateLoc,
656                                             LAngleLoc,
657                                             0, 0,
658                                             LAngleLoc));
659        TemplateParams = &FakedParamLists;
660      }
661
662      // Build the class template specialization.
663      TagOrTempResult
664        = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TUK,
665                       StartLoc, SS,
666                       TemplateTy::make(TemplateId->Template),
667                       TemplateId->TemplateNameLoc,
668                       TemplateId->LAngleLoc,
669                       TemplateArgsPtr,
670                       TemplateId->getTemplateArgLocations(),
671                       TemplateId->RAngleLoc,
672                       Attr,
673                       Action::MultiTemplateParamsArg(Actions,
674                                    TemplateParams? &(*TemplateParams)[0] : 0,
675                                 TemplateParams? TemplateParams->size() : 0));
676    }
677    TemplateId->Destroy();
678  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
679             TUK == Action::TUK_Declaration) {
680    // Explicit instantiation of a member of a class template
681    // specialization, e.g.,
682    //
683    //   template struct Outer<int>::Inner;
684    //
685    TagOrTempResult
686      = Actions.ActOnExplicitInstantiation(CurScope,
687                                           TemplateInfo.TemplateLoc,
688                                           TagType, StartLoc, SS, Name,
689                                           NameLoc, Attr);
690  } else {
691    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
692        TUK == Action::TUK_Definition) {
693      // FIXME: Diagnose this particular error.
694    }
695
696    // Declaration or definition of a class type
697    TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TUK, StartLoc, SS,
698                                       Name, NameLoc, Attr, AS,
699                                  Action::MultiTemplateParamsArg(Actions,
700                                    TemplateParams? &(*TemplateParams)[0] : 0,
701                                    TemplateParams? TemplateParams->size() : 0),
702                                       Owned);
703  }
704
705  // Parse the optional base clause (C++ only).
706  if (getLang().CPlusPlus && Tok.is(tok::colon))
707    ParseBaseClause(TagOrTempResult.get());
708
709  // If there is a body, parse it and inform the actions module.
710  if (Tok.is(tok::l_brace))
711    if (getLang().CPlusPlus)
712      ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
713    else
714      ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
715  else if (TUK == Action::TUK_Definition) {
716    // FIXME: Complain that we have a base-specifier list but no
717    // definition.
718    Diag(Tok, diag::err_expected_lbrace);
719  }
720
721  if (TagOrTempResult.isInvalid()) {
722    DS.SetTypeSpecError();
723    return;
724  }
725
726  const char *PrevSpec = 0;
727  unsigned DiagID;
728  if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, DiagID,
729                         TagOrTempResult.get().getAs<void>(), Owned))
730    Diag(StartLoc, DiagID) << PrevSpec;
731}
732
733/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
734///
735///       base-clause : [C++ class.derived]
736///         ':' base-specifier-list
737///       base-specifier-list:
738///         base-specifier '...'[opt]
739///         base-specifier-list ',' base-specifier '...'[opt]
740void Parser::ParseBaseClause(DeclPtrTy ClassDecl) {
741  assert(Tok.is(tok::colon) && "Not a base clause");
742  ConsumeToken();
743
744  // Build up an array of parsed base specifiers.
745  llvm::SmallVector<BaseTy *, 8> BaseInfo;
746
747  while (true) {
748    // Parse a base-specifier.
749    BaseResult Result = ParseBaseSpecifier(ClassDecl);
750    if (Result.isInvalid()) {
751      // Skip the rest of this base specifier, up until the comma or
752      // opening brace.
753      SkipUntil(tok::comma, tok::l_brace, true, true);
754    } else {
755      // Add this to our array of base specifiers.
756      BaseInfo.push_back(Result.get());
757    }
758
759    // If the next token is a comma, consume it and keep reading
760    // base-specifiers.
761    if (Tok.isNot(tok::comma)) break;
762
763    // Consume the comma.
764    ConsumeToken();
765  }
766
767  // Attach the base specifiers
768  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
769}
770
771/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
772/// one entry in the base class list of a class specifier, for example:
773///    class foo : public bar, virtual private baz {
774/// 'public bar' and 'virtual private baz' are each base-specifiers.
775///
776///       base-specifier: [C++ class.derived]
777///         ::[opt] nested-name-specifier[opt] class-name
778///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
779///                        class-name
780///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
781///                        class-name
782Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) {
783  bool IsVirtual = false;
784  SourceLocation StartLoc = Tok.getLocation();
785
786  // Parse the 'virtual' keyword.
787  if (Tok.is(tok::kw_virtual))  {
788    ConsumeToken();
789    IsVirtual = true;
790  }
791
792  // Parse an (optional) access specifier.
793  AccessSpecifier Access = getAccessSpecifierIfPresent();
794  if (Access)
795    ConsumeToken();
796
797  // Parse the 'virtual' keyword (again!), in case it came after the
798  // access specifier.
799  if (Tok.is(tok::kw_virtual))  {
800    SourceLocation VirtualLoc = ConsumeToken();
801    if (IsVirtual) {
802      // Complain about duplicate 'virtual'
803      Diag(VirtualLoc, diag::err_dup_virtual)
804        << CodeModificationHint::CreateRemoval(SourceRange(VirtualLoc));
805    }
806
807    IsVirtual = true;
808  }
809
810  // Parse optional '::' and optional nested-name-specifier.
811  CXXScopeSpec SS;
812  ParseOptionalCXXScopeSpecifier(SS);
813
814  // The location of the base class itself.
815  SourceLocation BaseLoc = Tok.getLocation();
816
817  // Parse the class-name.
818  SourceLocation EndLocation;
819  TypeResult BaseType = ParseClassName(EndLocation, &SS);
820  if (BaseType.isInvalid())
821    return true;
822
823  // Find the complete source range for the base-specifier.
824  SourceRange Range(StartLoc, EndLocation);
825
826  // Notify semantic analysis that we have parsed a complete
827  // base-specifier.
828  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
829                                    BaseType.get(), BaseLoc);
830}
831
832/// getAccessSpecifierIfPresent - Determine whether the next token is
833/// a C++ access-specifier.
834///
835///       access-specifier: [C++ class.derived]
836///         'private'
837///         'protected'
838///         'public'
839AccessSpecifier Parser::getAccessSpecifierIfPresent() const
840{
841  switch (Tok.getKind()) {
842  default: return AS_none;
843  case tok::kw_private: return AS_private;
844  case tok::kw_protected: return AS_protected;
845  case tok::kw_public: return AS_public;
846  }
847}
848
849void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo,
850                                             DeclPtrTy ThisDecl) {
851  // We just declared a member function. If this member function
852  // has any default arguments, we'll need to parse them later.
853  LateParsedMethodDeclaration *LateMethod = 0;
854  DeclaratorChunk::FunctionTypeInfo &FTI
855    = DeclaratorInfo.getTypeObject(0).Fun;
856  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
857    if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
858      if (!LateMethod) {
859        // Push this method onto the stack of late-parsed method
860        // declarations.
861        getCurrentClass().MethodDecls.push_back(
862                                LateParsedMethodDeclaration(ThisDecl));
863        LateMethod = &getCurrentClass().MethodDecls.back();
864
865        // Add all of the parameters prior to this one (they don't
866        // have default arguments).
867        LateMethod->DefaultArgs.reserve(FTI.NumArgs);
868        for (unsigned I = 0; I < ParamIdx; ++I)
869          LateMethod->DefaultArgs.push_back(
870                    LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param));
871      }
872
873      // Add this parameter to the list of parameters (it or may
874      // not have a default argument).
875      LateMethod->DefaultArgs.push_back(
876        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
877                                  FTI.ArgInfo[ParamIdx].DefaultArgTokens));
878    }
879  }
880}
881
882/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
883///
884///       member-declaration:
885///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
886///         function-definition ';'[opt]
887///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
888///         using-declaration                                            [TODO]
889/// [C++0x] static_assert-declaration
890///         template-declaration
891/// [GNU]   '__extension__' member-declaration
892///
893///       member-declarator-list:
894///         member-declarator
895///         member-declarator-list ',' member-declarator
896///
897///       member-declarator:
898///         declarator pure-specifier[opt]
899///         declarator constant-initializer[opt]
900///         identifier[opt] ':' constant-expression
901///
902///       pure-specifier:
903///         '= 0'
904///
905///       constant-initializer:
906///         '=' constant-expression
907///
908void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) {
909  // static_assert-declaration
910  if (Tok.is(tok::kw_static_assert)) {
911    SourceLocation DeclEnd;
912    ParseStaticAssertDeclaration(DeclEnd);
913    return;
914  }
915
916  if (Tok.is(tok::kw_template)) {
917    SourceLocation DeclEnd;
918    ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
919                                         AS);
920    return;
921  }
922
923  // Handle:  member-declaration ::= '__extension__' member-declaration
924  if (Tok.is(tok::kw___extension__)) {
925    // __extension__ silences extension warnings in the subexpression.
926    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
927    ConsumeToken();
928    return ParseCXXClassMemberDeclaration(AS);
929  }
930
931  if (Tok.is(tok::kw_using)) {
932    // Eat 'using'.
933    SourceLocation UsingLoc = ConsumeToken();
934
935    if (Tok.is(tok::kw_namespace)) {
936      Diag(UsingLoc, diag::err_using_namespace_in_class);
937      SkipUntil(tok::semi, true, true);
938    }
939    else {
940      SourceLocation DeclEnd;
941      // Otherwise, it must be using-declaration.
942      ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd);
943    }
944    return;
945  }
946
947  SourceLocation DSStart = Tok.getLocation();
948  // decl-specifier-seq:
949  // Parse the common declaration-specifiers piece.
950  DeclSpec DS;
951  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_class);
952
953  if (Tok.is(tok::semi)) {
954    ConsumeToken();
955
956    if (DS.isFriendSpecified())
957      Actions.ActOnFriendDecl(CurScope, &DS, /*IsDefinition*/ false);
958    else
959      Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
960
961    return;
962  }
963
964  Declarator DeclaratorInfo(DS, Declarator::MemberContext);
965
966  if (Tok.isNot(tok::colon)) {
967    // Parse the first declarator.
968    ParseDeclarator(DeclaratorInfo);
969    // Error parsing the declarator?
970    if (!DeclaratorInfo.hasName()) {
971      // If so, skip until the semi-colon or a }.
972      SkipUntil(tok::r_brace, true);
973      if (Tok.is(tok::semi))
974        ConsumeToken();
975      return;
976    }
977
978    // function-definition:
979    if (Tok.is(tok::l_brace)
980        || (DeclaratorInfo.isFunctionDeclarator() &&
981            (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) {
982      if (!DeclaratorInfo.isFunctionDeclarator()) {
983        Diag(Tok, diag::err_func_def_no_params);
984        ConsumeBrace();
985        SkipUntil(tok::r_brace, true);
986        return;
987      }
988
989      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
990        Diag(Tok, diag::err_function_declared_typedef);
991        // This recovery skips the entire function body. It would be nice
992        // to simply call ParseCXXInlineMethodDef() below, however Sema
993        // assumes the declarator represents a function, not a typedef.
994        ConsumeBrace();
995        SkipUntil(tok::r_brace, true);
996        return;
997      }
998
999      ParseCXXInlineMethodDef(AS, DeclaratorInfo);
1000      return;
1001    }
1002  }
1003
1004  // member-declarator-list:
1005  //   member-declarator
1006  //   member-declarator-list ',' member-declarator
1007
1008  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
1009  OwningExprResult BitfieldSize(Actions);
1010  OwningExprResult Init(Actions);
1011  bool Deleted = false;
1012
1013  while (1) {
1014
1015    // member-declarator:
1016    //   declarator pure-specifier[opt]
1017    //   declarator constant-initializer[opt]
1018    //   identifier[opt] ':' constant-expression
1019
1020    if (Tok.is(tok::colon)) {
1021      ConsumeToken();
1022      BitfieldSize = ParseConstantExpression();
1023      if (BitfieldSize.isInvalid())
1024        SkipUntil(tok::comma, true, true);
1025    }
1026
1027    // pure-specifier:
1028    //   '= 0'
1029    //
1030    // constant-initializer:
1031    //   '=' constant-expression
1032    //
1033    // defaulted/deleted function-definition:
1034    //   '=' 'default'                          [TODO]
1035    //   '=' 'delete'
1036
1037    if (Tok.is(tok::equal)) {
1038      ConsumeToken();
1039      if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
1040        ConsumeToken();
1041        Deleted = true;
1042      } else {
1043        Init = ParseInitializer();
1044        if (Init.isInvalid())
1045          SkipUntil(tok::comma, true, true);
1046      }
1047    }
1048
1049    // If attributes exist after the declarator, parse them.
1050    if (Tok.is(tok::kw___attribute)) {
1051      SourceLocation Loc;
1052      AttributeList *AttrList = ParseAttributes(&Loc);
1053      DeclaratorInfo.AddAttributes(AttrList, Loc);
1054    }
1055
1056    // NOTE: If Sema is the Action module and declarator is an instance field,
1057    // this call will *not* return the created decl; It will return null.
1058    // See Sema::ActOnCXXMemberDeclarator for details.
1059
1060    DeclPtrTy ThisDecl;
1061    if (DS.isFriendSpecified()) {
1062      // TODO: handle initializers, bitfields, 'delete'
1063      ThisDecl = Actions.ActOnFriendDecl(CurScope, &DeclaratorInfo,
1064                                         /*IsDefinition*/ false);
1065    } else
1066      ThisDecl = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
1067                                                  DeclaratorInfo,
1068                                                  BitfieldSize.release(),
1069                                                  Init.release(),
1070                                                  Deleted);
1071    if (ThisDecl)
1072      DeclsInGroup.push_back(ThisDecl);
1073
1074    if (DeclaratorInfo.isFunctionDeclarator() &&
1075        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
1076          != DeclSpec::SCS_typedef) {
1077      HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl);
1078    }
1079
1080    // If we don't have a comma, it is either the end of the list (a ';')
1081    // or an error, bail out.
1082    if (Tok.isNot(tok::comma))
1083      break;
1084
1085    // Consume the comma.
1086    ConsumeToken();
1087
1088    // Parse the next declarator.
1089    DeclaratorInfo.clear();
1090    BitfieldSize = 0;
1091    Init = 0;
1092    Deleted = false;
1093
1094    // Attributes are only allowed on the second declarator.
1095    if (Tok.is(tok::kw___attribute)) {
1096      SourceLocation Loc;
1097      AttributeList *AttrList = ParseAttributes(&Loc);
1098      DeclaratorInfo.AddAttributes(AttrList, Loc);
1099    }
1100
1101    if (Tok.isNot(tok::colon))
1102      ParseDeclarator(DeclaratorInfo);
1103  }
1104
1105  if (Tok.is(tok::semi)) {
1106    ConsumeToken();
1107    Actions.FinalizeDeclaratorGroup(CurScope, DS, DeclsInGroup.data(),
1108                                    DeclsInGroup.size());
1109    return;
1110  }
1111
1112  Diag(Tok, diag::err_expected_semi_decl_list);
1113  // Skip to end of block or statement
1114  SkipUntil(tok::r_brace, true, true);
1115  if (Tok.is(tok::semi))
1116    ConsumeToken();
1117  return;
1118}
1119
1120/// ParseCXXMemberSpecification - Parse the class definition.
1121///
1122///       member-specification:
1123///         member-declaration member-specification[opt]
1124///         access-specifier ':' member-specification[opt]
1125///
1126void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
1127                                         unsigned TagType, DeclPtrTy TagDecl) {
1128  assert((TagType == DeclSpec::TST_struct ||
1129         TagType == DeclSpec::TST_union  ||
1130         TagType == DeclSpec::TST_class) && "Invalid TagType!");
1131
1132  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1133                                        PP.getSourceManager(),
1134                                        "parsing struct/union/class body");
1135
1136  SourceLocation LBraceLoc = ConsumeBrace();
1137
1138  // Determine whether this is a top-level (non-nested) class.
1139  bool TopLevelClass = ClassStack.empty() ||
1140    CurScope->isInCXXInlineMethodScope();
1141
1142  // Enter a scope for the class.
1143  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
1144
1145  // Note that we are parsing a new (potentially-nested) class definition.
1146  ParsingClassDefinition ParsingDef(*this, TagDecl, TopLevelClass);
1147
1148  if (TagDecl)
1149    Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1150  else {
1151    SkipUntil(tok::r_brace, false, false);
1152    return;
1153  }
1154
1155  // C++ 11p3: Members of a class defined with the keyword class are private
1156  // by default. Members of a class defined with the keywords struct or union
1157  // are public by default.
1158  AccessSpecifier CurAS;
1159  if (TagType == DeclSpec::TST_class)
1160    CurAS = AS_private;
1161  else
1162    CurAS = AS_public;
1163
1164  // While we still have something to read, read the member-declarations.
1165  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1166    // Each iteration of this loop reads one member-declaration.
1167
1168    // Check for extraneous top-level semicolon.
1169    if (Tok.is(tok::semi)) {
1170      Diag(Tok, diag::ext_extra_struct_semi);
1171      ConsumeToken();
1172      continue;
1173    }
1174
1175    AccessSpecifier AS = getAccessSpecifierIfPresent();
1176    if (AS != AS_none) {
1177      // Current token is a C++ access specifier.
1178      CurAS = AS;
1179      ConsumeToken();
1180      ExpectAndConsume(tok::colon, diag::err_expected_colon);
1181      continue;
1182    }
1183
1184    // Parse all the comma separated declarators.
1185    ParseCXXClassMemberDeclaration(CurAS);
1186  }
1187
1188  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1189
1190  AttributeList *AttrList = 0;
1191  // If attributes exist after class contents, parse them.
1192  if (Tok.is(tok::kw___attribute))
1193    AttrList = ParseAttributes(); // FIXME: where should I put them?
1194
1195  Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
1196                                            LBraceLoc, RBraceLoc);
1197
1198  // C++ 9.2p2: Within the class member-specification, the class is regarded as
1199  // complete within function bodies, default arguments,
1200  // exception-specifications, and constructor ctor-initializers (including
1201  // such things in nested classes).
1202  //
1203  // FIXME: Only function bodies and constructor ctor-initializers are
1204  // parsed correctly, fix the rest.
1205  if (TopLevelClass) {
1206    // We are not inside a nested class. This class and its nested classes
1207    // are complete and we can parse the delayed portions of method
1208    // declarations and the lexed inline method definitions.
1209    ParseLexedMethodDeclarations(getCurrentClass());
1210    ParseLexedMethodDefs(getCurrentClass());
1211  }
1212
1213  // Leave the class scope.
1214  ParsingDef.Pop();
1215  ClassScope.Exit();
1216
1217  Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1218}
1219
1220/// ParseConstructorInitializer - Parse a C++ constructor initializer,
1221/// which explicitly initializes the members or base classes of a
1222/// class (C++ [class.base.init]). For example, the three initializers
1223/// after the ':' in the Derived constructor below:
1224///
1225/// @code
1226/// class Base { };
1227/// class Derived : Base {
1228///   int x;
1229///   float f;
1230/// public:
1231///   Derived(float f) : Base(), x(17), f(f) { }
1232/// };
1233/// @endcode
1234///
1235/// [C++]  ctor-initializer:
1236///          ':' mem-initializer-list
1237///
1238/// [C++]  mem-initializer-list:
1239///          mem-initializer
1240///          mem-initializer , mem-initializer-list
1241void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) {
1242  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
1243
1244  SourceLocation ColonLoc = ConsumeToken();
1245
1246  llvm::SmallVector<MemInitTy*, 4> MemInitializers;
1247
1248  do {
1249    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
1250    if (!MemInit.isInvalid())
1251      MemInitializers.push_back(MemInit.get());
1252
1253    if (Tok.is(tok::comma))
1254      ConsumeToken();
1255    else if (Tok.is(tok::l_brace))
1256      break;
1257    else {
1258      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1259      Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
1260      SkipUntil(tok::l_brace, true, true);
1261      break;
1262    }
1263  } while (true);
1264
1265  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
1266                               MemInitializers.data(), MemInitializers.size());
1267}
1268
1269/// ParseMemInitializer - Parse a C++ member initializer, which is
1270/// part of a constructor initializer that explicitly initializes one
1271/// member or base class (C++ [class.base.init]). See
1272/// ParseConstructorInitializer for an example.
1273///
1274/// [C++] mem-initializer:
1275///         mem-initializer-id '(' expression-list[opt] ')'
1276///
1277/// [C++] mem-initializer-id:
1278///         '::'[opt] nested-name-specifier[opt] class-name
1279///         identifier
1280Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) {
1281  // parse '::'[opt] nested-name-specifier[opt]
1282  CXXScopeSpec SS;
1283  ParseOptionalCXXScopeSpecifier(SS);
1284  TypeTy *TemplateTypeTy = 0;
1285  if (Tok.is(tok::annot_template_id)) {
1286    TemplateIdAnnotation *TemplateId
1287      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1288    if (TemplateId->Kind == TNK_Type_template) {
1289      AnnotateTemplateIdTokenAsType(&SS);
1290      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1291      TemplateTypeTy = Tok.getAnnotationValue();
1292    }
1293    // FIXME. May need to check for TNK_Dependent_template as well.
1294  }
1295  if (!TemplateTypeTy && Tok.isNot(tok::identifier)) {
1296    Diag(Tok, diag::err_expected_member_or_base_name);
1297    return true;
1298  }
1299
1300  // Get the identifier. This may be a member name or a class name,
1301  // but we'll let the semantic analysis determine which it is.
1302  IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0;
1303  SourceLocation IdLoc = ConsumeToken();
1304
1305  // Parse the '('.
1306  if (Tok.isNot(tok::l_paren)) {
1307    Diag(Tok, diag::err_expected_lparen);
1308    return true;
1309  }
1310  SourceLocation LParenLoc = ConsumeParen();
1311
1312  // Parse the optional expression-list.
1313  ExprVector ArgExprs(Actions);
1314  CommaLocsTy CommaLocs;
1315  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
1316    SkipUntil(tok::r_paren);
1317    return true;
1318  }
1319
1320  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1321
1322  return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, SS, II,
1323                                     TemplateTypeTy, IdLoc,
1324                                     LParenLoc, ArgExprs.take(),
1325                                     ArgExprs.size(), CommaLocs.data(),
1326                                     RParenLoc);
1327}
1328
1329/// ParseExceptionSpecification - Parse a C++ exception-specification
1330/// (C++ [except.spec]).
1331///
1332///       exception-specification:
1333///         'throw' '(' type-id-list [opt] ')'
1334/// [MS]    'throw' '(' '...' ')'
1335///
1336///       type-id-list:
1337///         type-id
1338///         type-id-list ',' type-id
1339///
1340bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc,
1341                                         llvm::SmallVector<TypeTy*, 2>
1342                                             &Exceptions,
1343                                         llvm::SmallVector<SourceRange, 2>
1344                                             &Ranges,
1345                                         bool &hasAnyExceptionSpec) {
1346  assert(Tok.is(tok::kw_throw) && "expected throw");
1347
1348  SourceLocation ThrowLoc = ConsumeToken();
1349
1350  if (!Tok.is(tok::l_paren)) {
1351    return Diag(Tok, diag::err_expected_lparen_after) << "throw";
1352  }
1353  SourceLocation LParenLoc = ConsumeParen();
1354
1355  // Parse throw(...), a Microsoft extension that means "this function
1356  // can throw anything".
1357  if (Tok.is(tok::ellipsis)) {
1358    hasAnyExceptionSpec = true;
1359    SourceLocation EllipsisLoc = ConsumeToken();
1360    if (!getLang().Microsoft)
1361      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
1362    EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1363    return false;
1364  }
1365
1366  // Parse the sequence of type-ids.
1367  SourceRange Range;
1368  while (Tok.isNot(tok::r_paren)) {
1369    TypeResult Res(ParseTypeName(&Range));
1370    if (!Res.isInvalid()) {
1371      Exceptions.push_back(Res.get());
1372      Ranges.push_back(Range);
1373    }
1374    if (Tok.is(tok::comma))
1375      ConsumeToken();
1376    else
1377      break;
1378  }
1379
1380  EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1381  return false;
1382}
1383
1384/// \brief We have just started parsing the definition of a new class,
1385/// so push that class onto our stack of classes that is currently
1386/// being parsed.
1387void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool TopLevelClass) {
1388  assert((TopLevelClass || !ClassStack.empty()) &&
1389         "Nested class without outer class");
1390  ClassStack.push(new ParsingClass(ClassDecl, TopLevelClass));
1391}
1392
1393/// \brief Deallocate the given parsed class and all of its nested
1394/// classes.
1395void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
1396  for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I)
1397    DeallocateParsedClasses(Class->NestedClasses[I]);
1398  delete Class;
1399}
1400
1401/// \brief Pop the top class of the stack of classes that are
1402/// currently being parsed.
1403///
1404/// This routine should be called when we have finished parsing the
1405/// definition of a class, but have not yet popped the Scope
1406/// associated with the class's definition.
1407///
1408/// \returns true if the class we've popped is a top-level class,
1409/// false otherwise.
1410void Parser::PopParsingClass() {
1411  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
1412
1413  ParsingClass *Victim = ClassStack.top();
1414  ClassStack.pop();
1415  if (Victim->TopLevelClass) {
1416    // Deallocate all of the nested classes of this class,
1417    // recursively: we don't need to keep any of this information.
1418    DeallocateParsedClasses(Victim);
1419    return;
1420  }
1421  assert(!ClassStack.empty() && "Missing top-level class?");
1422
1423  if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() &&
1424      Victim->NestedClasses.empty()) {
1425    // The victim is a nested class, but we will not need to perform
1426    // any processing after the definition of this class since it has
1427    // no members whose handling was delayed. Therefore, we can just
1428    // remove this nested class.
1429    delete Victim;
1430    return;
1431  }
1432
1433  // This nested class has some members that will need to be processed
1434  // after the top-level class is completely defined. Therefore, add
1435  // it to the list of nested classes within its parent.
1436  assert(CurScope->isClassScope() && "Nested class outside of class scope?");
1437  ClassStack.top()->NestedClasses.push_back(Victim);
1438  Victim->TemplateScope = CurScope->getParent()->isTemplateParamScope();
1439}
1440