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