ParseDeclCXX.cpp revision 453091cc2082e207ea2c2dda645a9bc01b37fb0c
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 "clang/Parse/Template.h"
20#include "RAIIObjectsForParser.h"
21using namespace clang;
22
23/// ParseNamespace - We know that the current token is a namespace keyword. This
24/// may either be a top level namespace or a block-level namespace alias.
25///
26///       namespace-definition: [C++ 7.3: basic.namespace]
27///         named-namespace-definition
28///         unnamed-namespace-definition
29///
30///       unnamed-namespace-definition:
31///         'namespace' attributes[opt] '{' namespace-body '}'
32///
33///       named-namespace-definition:
34///         original-namespace-definition
35///         extension-namespace-definition
36///
37///       original-namespace-definition:
38///         'namespace' identifier attributes[opt] '{' namespace-body '}'
39///
40///       extension-namespace-definition:
41///         'namespace' original-namespace-name '{' namespace-body '}'
42///
43///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
44///         'namespace' identifier '=' qualified-namespace-specifier ';'
45///
46Parser::DeclPtrTy Parser::ParseNamespace(unsigned Context,
47                                         SourceLocation &DeclEnd) {
48  assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
49  SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
50
51  if (Tok.is(tok::code_completion)) {
52    Actions.CodeCompleteNamespaceDecl(CurScope);
53    ConsumeToken();
54  }
55
56  SourceLocation IdentLoc;
57  IdentifierInfo *Ident = 0;
58
59  Token attrTok;
60
61  if (Tok.is(tok::identifier)) {
62    Ident = Tok.getIdentifierInfo();
63    IdentLoc = ConsumeToken();  // eat the identifier.
64  }
65
66  // Read label attributes, if present.
67  llvm::OwningPtr<AttributeList> AttrList;
68  if (Tok.is(tok::kw___attribute)) {
69    attrTok = Tok;
70
71    // FIXME: save these somewhere.
72    AttrList.reset(ParseGNUAttributes());
73  }
74
75  if (Tok.is(tok::equal)) {
76    if (AttrList)
77      Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
78
79    return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
80  }
81
82  if (Tok.isNot(tok::l_brace)) {
83    Diag(Tok, Ident ? diag::err_expected_lbrace :
84         diag::err_expected_ident_lbrace);
85    return DeclPtrTy();
86  }
87
88  SourceLocation LBrace = ConsumeBrace();
89
90  // Enter a scope for the namespace.
91  ParseScope NamespaceScope(this, Scope::DeclScope);
92
93  DeclPtrTy NamespcDecl =
94    Actions.ActOnStartNamespaceDef(CurScope, IdentLoc, Ident, LBrace,
95                                   AttrList.get());
96
97  PrettyStackTraceActionsDecl CrashInfo(NamespcDecl, NamespaceLoc, Actions,
98                                        PP.getSourceManager(),
99                                        "parsing namespace");
100
101  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
102    CXX0XAttributeList Attr;
103    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
104      Attr = ParseCXX0XAttributes();
105    ParseExternalDeclaration(Attr);
106  }
107
108  // Leave the namespace scope.
109  NamespaceScope.Exit();
110
111  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBrace);
112  Actions.ActOnFinishNamespaceDef(NamespcDecl, RBraceLoc);
113
114  DeclEnd = RBraceLoc;
115  return NamespcDecl;
116}
117
118/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
119/// alias definition.
120///
121Parser::DeclPtrTy Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
122                                              SourceLocation AliasLoc,
123                                              IdentifierInfo *Alias,
124                                              SourceLocation &DeclEnd) {
125  assert(Tok.is(tok::equal) && "Not equal token");
126
127  ConsumeToken(); // eat the '='.
128
129  if (Tok.is(tok::code_completion)) {
130    Actions.CodeCompleteNamespaceAliasDecl(CurScope);
131    ConsumeToken();
132  }
133
134  CXXScopeSpec SS;
135  // Parse (optional) nested-name-specifier.
136  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
137
138  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
139    Diag(Tok, diag::err_expected_namespace_name);
140    // Skip to end of the definition and eat the ';'.
141    SkipUntil(tok::semi);
142    return DeclPtrTy();
143  }
144
145  // Parse identifier.
146  IdentifierInfo *Ident = Tok.getIdentifierInfo();
147  SourceLocation IdentLoc = ConsumeToken();
148
149  // Eat the ';'.
150  DeclEnd = Tok.getLocation();
151  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
152                   "", tok::semi);
153
154  return Actions.ActOnNamespaceAliasDef(CurScope, NamespaceLoc, AliasLoc, Alias,
155                                        SS, IdentLoc, Ident);
156}
157
158/// ParseLinkage - We know that the current token is a string_literal
159/// and just before that, that extern was seen.
160///
161///       linkage-specification: [C++ 7.5p2: dcl.link]
162///         'extern' string-literal '{' declaration-seq[opt] '}'
163///         'extern' string-literal declaration
164///
165Parser::DeclPtrTy Parser::ParseLinkage(ParsingDeclSpec &DS,
166                                       unsigned Context) {
167  assert(Tok.is(tok::string_literal) && "Not a string literal!");
168  llvm::SmallString<8> LangBuffer;
169  // LangBuffer is guaranteed to be big enough.
170  bool Invalid = false;
171  llvm::StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid);
172  if (Invalid)
173    return DeclPtrTy();
174
175  SourceLocation Loc = ConsumeStringToken();
176
177  ParseScope LinkageScope(this, Scope::DeclScope);
178  DeclPtrTy LinkageSpec
179    = Actions.ActOnStartLinkageSpecification(CurScope,
180                                             /*FIXME: */SourceLocation(),
181                                             Loc, Lang.data(), Lang.size(),
182                                       Tok.is(tok::l_brace)? Tok.getLocation()
183                                                           : SourceLocation());
184
185  CXX0XAttributeList Attr;
186  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
187    Attr = ParseCXX0XAttributes();
188  }
189
190  if (Tok.isNot(tok::l_brace)) {
191    ParseDeclarationOrFunctionDefinition(DS, Attr.AttrList);
192    return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec,
193                                                   SourceLocation());
194  }
195
196  DS.abort();
197
198  if (Attr.HasAttr)
199    Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
200      << Attr.Range;
201
202  SourceLocation LBrace = ConsumeBrace();
203  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
204    CXX0XAttributeList Attr;
205    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
206      Attr = ParseCXX0XAttributes();
207    ParseExternalDeclaration(Attr);
208  }
209
210  SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
211  return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec, RBrace);
212}
213
214/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
215/// using-directive. Assumes that current token is 'using'.
216Parser::DeclPtrTy Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
217                                                     SourceLocation &DeclEnd,
218                                                     CXX0XAttributeList Attr) {
219  assert(Tok.is(tok::kw_using) && "Not using token");
220
221  // Eat 'using'.
222  SourceLocation UsingLoc = ConsumeToken();
223
224  if (Tok.is(tok::code_completion)) {
225    Actions.CodeCompleteUsing(CurScope);
226    ConsumeToken();
227  }
228
229  if (Tok.is(tok::kw_namespace))
230    // Next token after 'using' is 'namespace' so it must be using-directive
231    return ParseUsingDirective(Context, UsingLoc, DeclEnd, Attr.AttrList);
232
233  if (Attr.HasAttr)
234    Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
235      << Attr.Range;
236
237  // Otherwise, it must be using-declaration.
238  // Ignore illegal attributes (the caller should already have issued an error.
239  return ParseUsingDeclaration(Context, UsingLoc, DeclEnd);
240}
241
242/// ParseUsingDirective - Parse C++ using-directive, assumes
243/// that current token is 'namespace' and 'using' was already parsed.
244///
245///       using-directive: [C++ 7.3.p4: namespace.udir]
246///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
247///                 namespace-name ;
248/// [GNU] using-directive:
249///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
250///                 namespace-name attributes[opt] ;
251///
252Parser::DeclPtrTy Parser::ParseUsingDirective(unsigned Context,
253                                              SourceLocation UsingLoc,
254                                              SourceLocation &DeclEnd,
255                                              AttributeList *Attr) {
256  assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
257
258  // Eat 'namespace'.
259  SourceLocation NamespcLoc = ConsumeToken();
260
261  if (Tok.is(tok::code_completion)) {
262    Actions.CodeCompleteUsingDirective(CurScope);
263    ConsumeToken();
264  }
265
266  CXXScopeSpec SS;
267  // Parse (optional) nested-name-specifier.
268  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
269
270  IdentifierInfo *NamespcName = 0;
271  SourceLocation IdentLoc = SourceLocation();
272
273  // Parse namespace-name.
274  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
275    Diag(Tok, diag::err_expected_namespace_name);
276    // If there was invalid namespace name, skip to end of decl, and eat ';'.
277    SkipUntil(tok::semi);
278    // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
279    return DeclPtrTy();
280  }
281
282  // Parse identifier.
283  NamespcName = Tok.getIdentifierInfo();
284  IdentLoc = ConsumeToken();
285
286  // Parse (optional) attributes (most likely GNU strong-using extension).
287  bool GNUAttr = false;
288  if (Tok.is(tok::kw___attribute)) {
289    GNUAttr = true;
290    Attr = addAttributeLists(Attr, ParseGNUAttributes());
291  }
292
293  // Eat ';'.
294  DeclEnd = Tok.getLocation();
295  ExpectAndConsume(tok::semi,
296                   GNUAttr ? diag::err_expected_semi_after_attribute_list :
297                   diag::err_expected_semi_after_namespace_name, "", tok::semi);
298
299  return Actions.ActOnUsingDirective(CurScope, UsingLoc, NamespcLoc, SS,
300                                      IdentLoc, NamespcName, Attr);
301}
302
303/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that
304/// 'using' was already seen.
305///
306///     using-declaration: [C++ 7.3.p3: namespace.udecl]
307///       'using' 'typename'[opt] ::[opt] nested-name-specifier
308///               unqualified-id
309///       'using' :: unqualified-id
310///
311Parser::DeclPtrTy Parser::ParseUsingDeclaration(unsigned Context,
312                                                SourceLocation UsingLoc,
313                                                SourceLocation &DeclEnd,
314                                                AccessSpecifier AS) {
315  CXXScopeSpec SS;
316  SourceLocation TypenameLoc;
317  bool IsTypeName;
318
319  // Ignore optional 'typename'.
320  // FIXME: This is wrong; we should parse this as a typename-specifier.
321  if (Tok.is(tok::kw_typename)) {
322    TypenameLoc = Tok.getLocation();
323    ConsumeToken();
324    IsTypeName = true;
325  }
326  else
327    IsTypeName = false;
328
329  // Parse nested-name-specifier.
330  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
331
332  // Check nested-name specifier.
333  if (SS.isInvalid()) {
334    SkipUntil(tok::semi);
335    return DeclPtrTy();
336  }
337
338  // Parse the unqualified-id. We allow parsing of both constructor and
339  // destructor names and allow the action module to diagnose any semantic
340  // errors.
341  UnqualifiedId Name;
342  if (ParseUnqualifiedId(SS,
343                         /*EnteringContext=*/false,
344                         /*AllowDestructorName=*/true,
345                         /*AllowConstructorName=*/true,
346                         /*ObjectType=*/0,
347                         Name)) {
348    SkipUntil(tok::semi);
349    return DeclPtrTy();
350  }
351
352  // Parse (optional) attributes (most likely GNU strong-using extension).
353  llvm::OwningPtr<AttributeList> AttrList;
354  if (Tok.is(tok::kw___attribute))
355    AttrList.reset(ParseGNUAttributes());
356
357  // Eat ';'.
358  DeclEnd = Tok.getLocation();
359  ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
360                   AttrList ? "attributes list" : "using declaration",
361                   tok::semi);
362
363  return Actions.ActOnUsingDeclaration(CurScope, AS, true, UsingLoc, SS, Name,
364                                       AttrList.get(), IsTypeName, TypenameLoc);
365}
366
367/// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion.
368///
369///      static_assert-declaration:
370///        static_assert ( constant-expression  ,  string-literal  ) ;
371///
372Parser::DeclPtrTy Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
373  assert(Tok.is(tok::kw_static_assert) && "Not a static_assert declaration");
374  SourceLocation StaticAssertLoc = ConsumeToken();
375
376  if (Tok.isNot(tok::l_paren)) {
377    Diag(Tok, diag::err_expected_lparen);
378    return DeclPtrTy();
379  }
380
381  SourceLocation LParenLoc = ConsumeParen();
382
383  OwningExprResult AssertExpr(ParseConstantExpression());
384  if (AssertExpr.isInvalid()) {
385    SkipUntil(tok::semi);
386    return DeclPtrTy();
387  }
388
389  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
390    return DeclPtrTy();
391
392  if (Tok.isNot(tok::string_literal)) {
393    Diag(Tok, diag::err_expected_string_literal);
394    SkipUntil(tok::semi);
395    return DeclPtrTy();
396  }
397
398  OwningExprResult AssertMessage(ParseStringLiteralExpression());
399  if (AssertMessage.isInvalid())
400    return DeclPtrTy();
401
402  MatchRHSPunctuation(tok::r_paren, LParenLoc);
403
404  DeclEnd = Tok.getLocation();
405  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_static_assert);
406
407  return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, move(AssertExpr),
408                                              move(AssertMessage));
409}
410
411/// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
412///
413/// 'decltype' ( expression )
414///
415void Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
416  assert(Tok.is(tok::kw_decltype) && "Not a decltype specifier");
417
418  SourceLocation StartLoc = ConsumeToken();
419  SourceLocation LParenLoc = Tok.getLocation();
420
421  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
422                       "decltype")) {
423    SkipUntil(tok::r_paren);
424    return;
425  }
426
427  // Parse the expression
428
429  // C++0x [dcl.type.simple]p4:
430  //   The operand of the decltype specifier is an unevaluated operand.
431  EnterExpressionEvaluationContext Unevaluated(Actions,
432                                               Action::Unevaluated);
433  OwningExprResult Result = ParseExpression();
434  if (Result.isInvalid()) {
435    SkipUntil(tok::r_paren);
436    return;
437  }
438
439  // Match the ')'
440  SourceLocation RParenLoc;
441  if (Tok.is(tok::r_paren))
442    RParenLoc = ConsumeParen();
443  else
444    MatchRHSPunctuation(tok::r_paren, LParenLoc);
445
446  if (RParenLoc.isInvalid())
447    return;
448
449  const char *PrevSpec = 0;
450  unsigned DiagID;
451  // Check for duplicate type specifiers (e.g. "int decltype(a)").
452  if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
453                         DiagID, Result.release()))
454    Diag(StartLoc, DiagID) << PrevSpec;
455}
456
457/// ParseClassName - Parse a C++ class-name, which names a class. Note
458/// that we only check that the result names a type; semantic analysis
459/// will need to verify that the type names a class. The result is
460/// either a type or NULL, depending on whether a type name was
461/// found.
462///
463///       class-name: [C++ 9.1]
464///         identifier
465///         simple-template-id
466///
467Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation,
468                                          const CXXScopeSpec *SS) {
469  // Check whether we have a template-id that names a type.
470  if (Tok.is(tok::annot_template_id)) {
471    TemplateIdAnnotation *TemplateId
472      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
473    if (TemplateId->Kind == TNK_Type_template ||
474        TemplateId->Kind == TNK_Dependent_template_name) {
475      AnnotateTemplateIdTokenAsType(SS);
476
477      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
478      TypeTy *Type = Tok.getAnnotationValue();
479      EndLocation = Tok.getAnnotationEndLoc();
480      ConsumeToken();
481
482      if (Type)
483        return Type;
484      return true;
485    }
486
487    // Fall through to produce an error below.
488  }
489
490  if (Tok.isNot(tok::identifier)) {
491    Diag(Tok, diag::err_expected_class_name);
492    return true;
493  }
494
495  IdentifierInfo *Id = Tok.getIdentifierInfo();
496  SourceLocation IdLoc = ConsumeToken();
497
498  if (Tok.is(tok::less)) {
499    // It looks the user intended to write a template-id here, but the
500    // template-name was wrong. Try to fix that.
501    TemplateNameKind TNK = TNK_Type_template;
502    TemplateTy Template;
503    if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, CurScope,
504                                             SS, Template, TNK)) {
505      Diag(IdLoc, diag::err_unknown_template_name)
506        << Id;
507    }
508
509    if (!Template)
510      return true;
511
512    // Form the template name
513    UnqualifiedId TemplateName;
514    TemplateName.setIdentifier(Id, IdLoc);
515
516    // Parse the full template-id, then turn it into a type.
517    if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
518                                SourceLocation(), true))
519      return true;
520    if (TNK == TNK_Dependent_template_name)
521      AnnotateTemplateIdTokenAsType(SS);
522
523    // If we didn't end up with a typename token, there's nothing more we
524    // can do.
525    if (Tok.isNot(tok::annot_typename))
526      return true;
527
528    // Retrieve the type from the annotation token, consume that token, and
529    // return.
530    EndLocation = Tok.getAnnotationEndLoc();
531    TypeTy *Type = Tok.getAnnotationValue();
532    ConsumeToken();
533    return Type;
534  }
535
536  // We have an identifier; check whether it is actually a type.
537  TypeTy *Type = Actions.getTypeName(*Id, IdLoc, CurScope, SS, true);
538  if (!Type) {
539    Diag(IdLoc, diag::err_expected_class_name);
540    return true;
541  }
542
543  // Consume the identifier.
544  EndLocation = IdLoc;
545  return Type;
546}
547
548/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
549/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
550/// until we reach the start of a definition or see a token that
551/// cannot start a definition. If SuppressDeclarations is true, we do know.
552///
553///       class-specifier: [C++ class]
554///         class-head '{' member-specification[opt] '}'
555///         class-head '{' member-specification[opt] '}' attributes[opt]
556///       class-head:
557///         class-key identifier[opt] base-clause[opt]
558///         class-key nested-name-specifier identifier base-clause[opt]
559///         class-key nested-name-specifier[opt] simple-template-id
560///                          base-clause[opt]
561/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
562/// [GNU]   class-key attributes[opt] nested-name-specifier
563///                          identifier base-clause[opt]
564/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
565///                          simple-template-id base-clause[opt]
566///       class-key:
567///         'class'
568///         'struct'
569///         'union'
570///
571///       elaborated-type-specifier: [C++ dcl.type.elab]
572///         class-key ::[opt] nested-name-specifier[opt] identifier
573///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
574///                          simple-template-id
575///
576///  Note that the C++ class-specifier and elaborated-type-specifier,
577///  together, subsume the C99 struct-or-union-specifier:
578///
579///       struct-or-union-specifier: [C99 6.7.2.1]
580///         struct-or-union identifier[opt] '{' struct-contents '}'
581///         struct-or-union identifier
582/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
583///                                                         '}' attributes[opt]
584/// [GNU]   struct-or-union attributes[opt] identifier
585///       struct-or-union:
586///         'struct'
587///         'union'
588void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
589                                 SourceLocation StartLoc, DeclSpec &DS,
590                                 const ParsedTemplateInfo &TemplateInfo,
591                                 AccessSpecifier AS, bool SuppressDeclarations){
592  DeclSpec::TST TagType;
593  if (TagTokKind == tok::kw_struct)
594    TagType = DeclSpec::TST_struct;
595  else if (TagTokKind == tok::kw_class)
596    TagType = DeclSpec::TST_class;
597  else {
598    assert(TagTokKind == tok::kw_union && "Not a class specifier");
599    TagType = DeclSpec::TST_union;
600  }
601
602  if (Tok.is(tok::code_completion)) {
603    // Code completion for a struct, class, or union name.
604    Actions.CodeCompleteTag(CurScope, TagType);
605    ConsumeToken();
606  }
607
608  AttributeList *AttrList = 0;
609  // If attributes exist after tag, parse them.
610  if (Tok.is(tok::kw___attribute))
611    AttrList = ParseGNUAttributes();
612
613  // If declspecs exist after tag, parse them.
614  if (Tok.is(tok::kw___declspec))
615    AttrList = ParseMicrosoftDeclSpec(AttrList);
616
617  // If C++0x attributes exist here, parse them.
618  // FIXME: Are we consistent with the ordering of parsing of different
619  // styles of attributes?
620  if (isCXX0XAttributeSpecifier())
621    AttrList = addAttributeLists(AttrList, ParseCXX0XAttributes().AttrList);
622
623  if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_pod)) {
624    // GNU libstdc++ 4.2 uses __is_pod as the name of a struct template, but
625    // __is_pod is a keyword in GCC >= 4.3. Therefore, when we see the
626    // token sequence "struct __is_pod", make __is_pod into a normal
627    // identifier rather than a keyword, to allow libstdc++ 4.2 to work
628    // properly.
629    Tok.getIdentifierInfo()->setTokenID(tok::identifier);
630    Tok.setKind(tok::identifier);
631  }
632
633  if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_empty)) {
634    // GNU libstdc++ 4.2 uses __is_empty as the name of a struct template, but
635    // __is_empty is a keyword in GCC >= 4.3. Therefore, when we see the
636    // token sequence "struct __is_empty", make __is_empty into a normal
637    // identifier rather than a keyword, to allow libstdc++ 4.2 to work
638    // properly.
639    Tok.getIdentifierInfo()->setTokenID(tok::identifier);
640    Tok.setKind(tok::identifier);
641  }
642
643  // Parse the (optional) nested-name-specifier.
644  CXXScopeSpec &SS = DS.getTypeSpecScope();
645  if (getLang().CPlusPlus) {
646    // "FOO : BAR" is not a potential typo for "FOO::BAR".
647    ColonProtectionRAIIObject X(*this);
648
649    ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true);
650    if (SS.isSet())
651      if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
652        Diag(Tok, diag::err_expected_ident);
653  }
654
655  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
656
657  // Parse the (optional) class name or simple-template-id.
658  IdentifierInfo *Name = 0;
659  SourceLocation NameLoc;
660  TemplateIdAnnotation *TemplateId = 0;
661  if (Tok.is(tok::identifier)) {
662    Name = Tok.getIdentifierInfo();
663    NameLoc = ConsumeToken();
664
665    if (Tok.is(tok::less)) {
666      // The name was supposed to refer to a template, but didn't.
667      // Eat the template argument list and try to continue parsing this as
668      // a class (or template thereof).
669      TemplateArgList TemplateArgs;
670      SourceLocation LAngleLoc, RAngleLoc;
671      if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, &SS,
672                                           true, LAngleLoc,
673                                           TemplateArgs, RAngleLoc)) {
674        // We couldn't parse the template argument list at all, so don't
675        // try to give any location information for the list.
676        LAngleLoc = RAngleLoc = SourceLocation();
677      }
678
679      Diag(NameLoc, diag::err_explicit_spec_non_template)
680        << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
681        << (TagType == DeclSpec::TST_class? 0
682            : TagType == DeclSpec::TST_struct? 1
683            : 2)
684        << Name
685        << SourceRange(LAngleLoc, RAngleLoc);
686
687      // Strip off the last template parameter list if it was empty, since
688      // we've removed its template argument list.
689      if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
690        if (TemplateParams && TemplateParams->size() > 1) {
691          TemplateParams->pop_back();
692        } else {
693          TemplateParams = 0;
694          const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
695            = ParsedTemplateInfo::NonTemplate;
696        }
697      } else if (TemplateInfo.Kind
698                                == ParsedTemplateInfo::ExplicitInstantiation) {
699        // Pretend this is just a forward declaration.
700        TemplateParams = 0;
701        const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
702          = ParsedTemplateInfo::NonTemplate;
703        const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
704          = SourceLocation();
705        const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
706          = SourceLocation();
707      }
708
709
710    }
711  } else if (Tok.is(tok::annot_template_id)) {
712    TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
713    NameLoc = ConsumeToken();
714
715    if (TemplateId->Kind != TNK_Type_template) {
716      // The template-name in the simple-template-id refers to
717      // something other than a class template. Give an appropriate
718      // error message and skip to the ';'.
719      SourceRange Range(NameLoc);
720      if (SS.isNotEmpty())
721        Range.setBegin(SS.getBeginLoc());
722
723      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
724        << Name << static_cast<int>(TemplateId->Kind) << Range;
725
726      DS.SetTypeSpecError();
727      SkipUntil(tok::semi, false, true);
728      TemplateId->Destroy();
729      return;
730    }
731  }
732
733  // There are four options here.  If we have 'struct foo;', then this
734  // is either a forward declaration or a friend declaration, which
735  // have to be treated differently.  If we have 'struct foo {...' or
736  // 'struct foo :...' then this is a definition. Otherwise we have
737  // something like 'struct foo xyz', a reference.
738  // However, in some contexts, things look like declarations but are just
739  // references, e.g.
740  // new struct s;
741  // or
742  // &T::operator struct s;
743  // For these, SuppressDeclarations is true.
744  Action::TagUseKind TUK;
745  if (SuppressDeclarations)
746    TUK = Action::TUK_Reference;
747  else if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon))){
748    if (DS.isFriendSpecified()) {
749      // C++ [class.friend]p2:
750      //   A class shall not be defined in a friend declaration.
751      Diag(Tok.getLocation(), diag::err_friend_decl_defines_class)
752        << SourceRange(DS.getFriendSpecLoc());
753
754      // Skip everything up to the semicolon, so that this looks like a proper
755      // friend class (or template thereof) declaration.
756      SkipUntil(tok::semi, true, true);
757      TUK = Action::TUK_Friend;
758    } else {
759      // Okay, this is a class definition.
760      TUK = Action::TUK_Definition;
761    }
762  } else if (Tok.is(tok::semi))
763    TUK = DS.isFriendSpecified() ? Action::TUK_Friend : Action::TUK_Declaration;
764  else
765    TUK = Action::TUK_Reference;
766
767  if (!Name && !TemplateId && TUK != Action::TUK_Definition) {
768    // We have a declaration or reference to an anonymous class.
769    Diag(StartLoc, diag::err_anon_type_definition)
770      << DeclSpec::getSpecifierName(TagType);
771
772    SkipUntil(tok::comma, true);
773
774    if (TemplateId)
775      TemplateId->Destroy();
776    return;
777  }
778
779  // Create the tag portion of the class or class template.
780  Action::DeclResult TagOrTempResult = true; // invalid
781  Action::TypeResult TypeResult = true; // invalid
782
783  // FIXME: When TUK == TUK_Reference and we have a template-id, we need
784  // to turn that template-id into a type.
785
786  bool Owned = false;
787  if (TemplateId) {
788    // Explicit specialization, class template partial specialization,
789    // or explicit instantiation.
790    ASTTemplateArgsPtr TemplateArgsPtr(Actions,
791                                       TemplateId->getTemplateArgs(),
792                                       TemplateId->NumArgs);
793    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
794        TUK == Action::TUK_Declaration) {
795      // This is an explicit instantiation of a class template.
796      TagOrTempResult
797        = Actions.ActOnExplicitInstantiation(CurScope,
798                                             TemplateInfo.ExternLoc,
799                                             TemplateInfo.TemplateLoc,
800                                             TagType,
801                                             StartLoc,
802                                             SS,
803                                     TemplateTy::make(TemplateId->Template),
804                                             TemplateId->TemplateNameLoc,
805                                             TemplateId->LAngleLoc,
806                                             TemplateArgsPtr,
807                                             TemplateId->RAngleLoc,
808                                             AttrList);
809    } else if (TUK == Action::TUK_Reference) {
810      TypeResult
811        = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
812                                      TemplateId->TemplateNameLoc,
813                                      TemplateId->LAngleLoc,
814                                      TemplateArgsPtr,
815                                      TemplateId->RAngleLoc);
816
817      TypeResult = Actions.ActOnTagTemplateIdType(TypeResult, TUK,
818                                                  TagType, StartLoc);
819    } else {
820      // This is an explicit specialization or a class template
821      // partial specialization.
822      TemplateParameterLists FakedParamLists;
823
824      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
825        // This looks like an explicit instantiation, because we have
826        // something like
827        //
828        //   template class Foo<X>
829        //
830        // but it actually has a definition. Most likely, this was
831        // meant to be an explicit specialization, but the user forgot
832        // the '<>' after 'template'.
833        assert(TUK == Action::TUK_Definition && "Expected a definition here");
834
835        SourceLocation LAngleLoc
836          = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
837        Diag(TemplateId->TemplateNameLoc,
838             diag::err_explicit_instantiation_with_definition)
839          << SourceRange(TemplateInfo.TemplateLoc)
840          << CodeModificationHint::CreateInsertion(LAngleLoc, "<>");
841
842        // Create a fake template parameter list that contains only
843        // "template<>", so that we treat this construct as a class
844        // template specialization.
845        FakedParamLists.push_back(
846          Actions.ActOnTemplateParameterList(0, SourceLocation(),
847                                             TemplateInfo.TemplateLoc,
848                                             LAngleLoc,
849                                             0, 0,
850                                             LAngleLoc));
851        TemplateParams = &FakedParamLists;
852      }
853
854      // Build the class template specialization.
855      TagOrTempResult
856        = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TUK,
857                       StartLoc, SS,
858                       TemplateTy::make(TemplateId->Template),
859                       TemplateId->TemplateNameLoc,
860                       TemplateId->LAngleLoc,
861                       TemplateArgsPtr,
862                       TemplateId->RAngleLoc,
863                       AttrList,
864                       Action::MultiTemplateParamsArg(Actions,
865                                    TemplateParams? &(*TemplateParams)[0] : 0,
866                                 TemplateParams? TemplateParams->size() : 0));
867    }
868    TemplateId->Destroy();
869  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
870             TUK == Action::TUK_Declaration) {
871    // Explicit instantiation of a member of a class template
872    // specialization, e.g.,
873    //
874    //   template struct Outer<int>::Inner;
875    //
876    TagOrTempResult
877      = Actions.ActOnExplicitInstantiation(CurScope,
878                                           TemplateInfo.ExternLoc,
879                                           TemplateInfo.TemplateLoc,
880                                           TagType, StartLoc, SS, Name,
881                                           NameLoc, AttrList);
882  } else {
883    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
884        TUK == Action::TUK_Definition) {
885      // FIXME: Diagnose this particular error.
886    }
887
888    bool IsDependent = false;
889
890    // Declaration or definition of a class type
891    TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TUK, StartLoc, SS,
892                                       Name, NameLoc, AttrList, AS,
893                                  Action::MultiTemplateParamsArg(Actions,
894                                    TemplateParams? &(*TemplateParams)[0] : 0,
895                                    TemplateParams? TemplateParams->size() : 0),
896                                       Owned, IsDependent);
897
898    // If ActOnTag said the type was dependent, try again with the
899    // less common call.
900    if (IsDependent)
901      TypeResult = Actions.ActOnDependentTag(CurScope, TagType, TUK,
902                                             SS, Name, StartLoc, NameLoc);
903  }
904
905  // If there is a body, parse it and inform the actions module.
906  if (TUK == Action::TUK_Definition) {
907    assert(Tok.is(tok::l_brace) ||
908           (getLang().CPlusPlus && Tok.is(tok::colon)));
909    if (getLang().CPlusPlus)
910      ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
911    else
912      ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
913  }
914
915  void *Result;
916  if (!TypeResult.isInvalid()) {
917    TagType = DeclSpec::TST_typename;
918    Result = TypeResult.get();
919    Owned = false;
920  } else if (!TagOrTempResult.isInvalid()) {
921    Result = TagOrTempResult.get().getAs<void>();
922  } else {
923    DS.SetTypeSpecError();
924    return;
925  }
926
927  const char *PrevSpec = 0;
928  unsigned DiagID;
929
930  // FIXME: The DeclSpec should keep the locations of both the keyword and the
931  // name (if there is one).
932  SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc;
933
934  if (DS.SetTypeSpecType(TagType, TSTLoc, PrevSpec, DiagID,
935                         Result, Owned))
936    Diag(StartLoc, DiagID) << PrevSpec;
937
938  // At this point, we've successfully parsed a class-specifier in 'definition'
939  // form (e.g. "struct foo { int x; }".  While we could just return here, we're
940  // going to look at what comes after it to improve error recovery.  If an
941  // impossible token occurs next, we assume that the programmer forgot a ; at
942  // the end of the declaration and recover that way.
943  //
944  // This switch enumerates the valid "follow" set for definition.
945  if (TUK == Action::TUK_Definition) {
946    bool ExpectedSemi = true;
947    switch (Tok.getKind()) {
948    default: break;
949    case tok::semi:               // struct foo {...} ;
950    case tok::star:               // struct foo {...} *         P;
951    case tok::amp:                // struct foo {...} &         R = ...
952    case tok::identifier:         // struct foo {...} V         ;
953    case tok::r_paren:            //(struct foo {...} )         {4}
954    case tok::annot_cxxscope:     // struct foo {...} a::       b;
955    case tok::annot_typename:     // struct foo {...} a         ::b;
956    case tok::annot_template_id:  // struct foo {...} a<int>    ::b;
957    case tok::l_paren:            // struct foo {...} (         x);
958    case tok::comma:              // __builtin_offsetof(struct foo{...} ,
959      ExpectedSemi = false;
960      break;
961    // Type qualifiers
962    case tok::kw_const:           // struct foo {...} const     x;
963    case tok::kw_volatile:        // struct foo {...} volatile  x;
964    case tok::kw_restrict:        // struct foo {...} restrict  x;
965    case tok::kw_inline:          // struct foo {...} inline    foo() {};
966    // Storage-class specifiers
967    case tok::kw_static:          // struct foo {...} static    x;
968    case tok::kw_extern:          // struct foo {...} extern    x;
969    case tok::kw_typedef:         // struct foo {...} typedef   x;
970    case tok::kw_register:        // struct foo {...} register  x;
971    case tok::kw_auto:            // struct foo {...} auto      x;
972      // As shown above, type qualifiers and storage class specifiers absolutely
973      // can occur after class specifiers according to the grammar.  However,
974      // almost noone actually writes code like this.  If we see one of these,
975      // it is much more likely that someone missed a semi colon and the
976      // type/storage class specifier we're seeing is part of the *next*
977      // intended declaration, as in:
978      //
979      //   struct foo { ... }
980      //   typedef int X;
981      //
982      // We'd really like to emit a missing semicolon error instead of emitting
983      // an error on the 'int' saying that you can't have two type specifiers in
984      // the same declaration of X.  Because of this, we look ahead past this
985      // token to see if it's a type specifier.  If so, we know the code is
986      // otherwise invalid, so we can produce the expected semi error.
987      if (!isKnownToBeTypeSpecifier(NextToken()))
988        ExpectedSemi = false;
989      break;
990
991    case tok::r_brace:  // struct bar { struct foo {...} }
992      // Missing ';' at end of struct is accepted as an extension in C mode.
993      if (!getLang().CPlusPlus)
994        ExpectedSemi = false;
995      break;
996    }
997
998    if (ExpectedSemi) {
999      ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1000                       TagType == DeclSpec::TST_class ? "class"
1001                       : TagType == DeclSpec::TST_struct? "struct" : "union");
1002      // Push this token back into the preprocessor and change our current token
1003      // to ';' so that the rest of the code recovers as though there were an
1004      // ';' after the definition.
1005      PP.EnterToken(Tok);
1006      Tok.setKind(tok::semi);
1007    }
1008  }
1009}
1010
1011/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1012///
1013///       base-clause : [C++ class.derived]
1014///         ':' base-specifier-list
1015///       base-specifier-list:
1016///         base-specifier '...'[opt]
1017///         base-specifier-list ',' base-specifier '...'[opt]
1018void Parser::ParseBaseClause(DeclPtrTy ClassDecl) {
1019  assert(Tok.is(tok::colon) && "Not a base clause");
1020  ConsumeToken();
1021
1022  // Build up an array of parsed base specifiers.
1023  llvm::SmallVector<BaseTy *, 8> BaseInfo;
1024
1025  while (true) {
1026    // Parse a base-specifier.
1027    BaseResult Result = ParseBaseSpecifier(ClassDecl);
1028    if (Result.isInvalid()) {
1029      // Skip the rest of this base specifier, up until the comma or
1030      // opening brace.
1031      SkipUntil(tok::comma, tok::l_brace, true, true);
1032    } else {
1033      // Add this to our array of base specifiers.
1034      BaseInfo.push_back(Result.get());
1035    }
1036
1037    // If the next token is a comma, consume it and keep reading
1038    // base-specifiers.
1039    if (Tok.isNot(tok::comma)) break;
1040
1041    // Consume the comma.
1042    ConsumeToken();
1043  }
1044
1045  // Attach the base specifiers
1046  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1047}
1048
1049/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1050/// one entry in the base class list of a class specifier, for example:
1051///    class foo : public bar, virtual private baz {
1052/// 'public bar' and 'virtual private baz' are each base-specifiers.
1053///
1054///       base-specifier: [C++ class.derived]
1055///         ::[opt] nested-name-specifier[opt] class-name
1056///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
1057///                        class-name
1058///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
1059///                        class-name
1060Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) {
1061  bool IsVirtual = false;
1062  SourceLocation StartLoc = Tok.getLocation();
1063
1064  // Parse the 'virtual' keyword.
1065  if (Tok.is(tok::kw_virtual))  {
1066    ConsumeToken();
1067    IsVirtual = true;
1068  }
1069
1070  // Parse an (optional) access specifier.
1071  AccessSpecifier Access = getAccessSpecifierIfPresent();
1072  if (Access != AS_none)
1073    ConsumeToken();
1074
1075  // Parse the 'virtual' keyword (again!), in case it came after the
1076  // access specifier.
1077  if (Tok.is(tok::kw_virtual))  {
1078    SourceLocation VirtualLoc = ConsumeToken();
1079    if (IsVirtual) {
1080      // Complain about duplicate 'virtual'
1081      Diag(VirtualLoc, diag::err_dup_virtual)
1082        << CodeModificationHint::CreateRemoval(VirtualLoc);
1083    }
1084
1085    IsVirtual = true;
1086  }
1087
1088  // Parse optional '::' and optional nested-name-specifier.
1089  CXXScopeSpec SS;
1090  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0,
1091                                 /*EnteringContext=*/false);
1092
1093  // The location of the base class itself.
1094  SourceLocation BaseLoc = Tok.getLocation();
1095
1096  // Parse the class-name.
1097  SourceLocation EndLocation;
1098  TypeResult BaseType = ParseClassName(EndLocation, &SS);
1099  if (BaseType.isInvalid())
1100    return true;
1101
1102  // Find the complete source range for the base-specifier.
1103  SourceRange Range(StartLoc, EndLocation);
1104
1105  // Notify semantic analysis that we have parsed a complete
1106  // base-specifier.
1107  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
1108                                    BaseType.get(), BaseLoc);
1109}
1110
1111/// getAccessSpecifierIfPresent - Determine whether the next token is
1112/// a C++ access-specifier.
1113///
1114///       access-specifier: [C++ class.derived]
1115///         'private'
1116///         'protected'
1117///         'public'
1118AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1119  switch (Tok.getKind()) {
1120  default: return AS_none;
1121  case tok::kw_private: return AS_private;
1122  case tok::kw_protected: return AS_protected;
1123  case tok::kw_public: return AS_public;
1124  }
1125}
1126
1127void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo,
1128                                             DeclPtrTy ThisDecl) {
1129  // We just declared a member function. If this member function
1130  // has any default arguments, we'll need to parse them later.
1131  LateParsedMethodDeclaration *LateMethod = 0;
1132  DeclaratorChunk::FunctionTypeInfo &FTI
1133    = DeclaratorInfo.getTypeObject(0).Fun;
1134  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1135    if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1136      if (!LateMethod) {
1137        // Push this method onto the stack of late-parsed method
1138        // declarations.
1139        getCurrentClass().MethodDecls.push_back(
1140                                LateParsedMethodDeclaration(ThisDecl));
1141        LateMethod = &getCurrentClass().MethodDecls.back();
1142        LateMethod->TemplateScope = CurScope->isTemplateParamScope();
1143
1144        // Add all of the parameters prior to this one (they don't
1145        // have default arguments).
1146        LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1147        for (unsigned I = 0; I < ParamIdx; ++I)
1148          LateMethod->DefaultArgs.push_back(
1149                             LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
1150      }
1151
1152      // Add this parameter to the list of parameters (it or may
1153      // not have a default argument).
1154      LateMethod->DefaultArgs.push_back(
1155        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1156                                  FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1157    }
1158  }
1159}
1160
1161/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1162///
1163///       member-declaration:
1164///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
1165///         function-definition ';'[opt]
1166///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1167///         using-declaration                                            [TODO]
1168/// [C++0x] static_assert-declaration
1169///         template-declaration
1170/// [GNU]   '__extension__' member-declaration
1171///
1172///       member-declarator-list:
1173///         member-declarator
1174///         member-declarator-list ',' member-declarator
1175///
1176///       member-declarator:
1177///         declarator pure-specifier[opt]
1178///         declarator constant-initializer[opt]
1179///         identifier[opt] ':' constant-expression
1180///
1181///       pure-specifier:
1182///         '= 0'
1183///
1184///       constant-initializer:
1185///         '=' constant-expression
1186///
1187void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1188                                       const ParsedTemplateInfo &TemplateInfo) {
1189  // Access declarations.
1190  if (!TemplateInfo.Kind &&
1191      (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
1192      !TryAnnotateCXXScopeToken() &&
1193      Tok.is(tok::annot_cxxscope)) {
1194    bool isAccessDecl = false;
1195    if (NextToken().is(tok::identifier))
1196      isAccessDecl = GetLookAheadToken(2).is(tok::semi);
1197    else
1198      isAccessDecl = NextToken().is(tok::kw_operator);
1199
1200    if (isAccessDecl) {
1201      // Collect the scope specifier token we annotated earlier.
1202      CXXScopeSpec SS;
1203      ParseOptionalCXXScopeSpecifier(SS, /*ObjectType*/ 0, false);
1204
1205      // Try to parse an unqualified-id.
1206      UnqualifiedId Name;
1207      if (ParseUnqualifiedId(SS, false, true, true, /*ObjectType*/ 0, Name)) {
1208        SkipUntil(tok::semi);
1209        return;
1210      }
1211
1212      // TODO: recover from mistakenly-qualified operator declarations.
1213      if (ExpectAndConsume(tok::semi,
1214                           diag::err_expected_semi_after,
1215                           "access declaration",
1216                           tok::semi))
1217        return;
1218
1219      Actions.ActOnUsingDeclaration(CurScope, AS,
1220                                    false, SourceLocation(),
1221                                    SS, Name,
1222                                    /* AttrList */ 0,
1223                                    /* IsTypeName */ false,
1224                                    SourceLocation());
1225      return;
1226    }
1227  }
1228
1229  // static_assert-declaration
1230  if (Tok.is(tok::kw_static_assert)) {
1231    // FIXME: Check for templates
1232    SourceLocation DeclEnd;
1233    ParseStaticAssertDeclaration(DeclEnd);
1234    return;
1235  }
1236
1237  if (Tok.is(tok::kw_template)) {
1238    assert(!TemplateInfo.TemplateParams &&
1239           "Nested template improperly parsed?");
1240    SourceLocation DeclEnd;
1241    ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
1242                                         AS);
1243    return;
1244  }
1245
1246  // Handle:  member-declaration ::= '__extension__' member-declaration
1247  if (Tok.is(tok::kw___extension__)) {
1248    // __extension__ silences extension warnings in the subexpression.
1249    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1250    ConsumeToken();
1251    return ParseCXXClassMemberDeclaration(AS, TemplateInfo);
1252  }
1253
1254  // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1255  // is a bitfield.
1256  ColonProtectionRAIIObject X(*this);
1257
1258  CXX0XAttributeList AttrList;
1259  // Optional C++0x attribute-specifier
1260  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
1261    AttrList = ParseCXX0XAttributes();
1262
1263  if (Tok.is(tok::kw_using)) {
1264    // FIXME: Check for template aliases
1265
1266    if (AttrList.HasAttr)
1267      Diag(AttrList.Range.getBegin(), diag::err_attributes_not_allowed)
1268        << AttrList.Range;
1269
1270    // Eat 'using'.
1271    SourceLocation UsingLoc = ConsumeToken();
1272
1273    if (Tok.is(tok::kw_namespace)) {
1274      Diag(UsingLoc, diag::err_using_namespace_in_class);
1275      SkipUntil(tok::semi, true, true);
1276    } else {
1277      SourceLocation DeclEnd;
1278      // Otherwise, it must be using-declaration.
1279      ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd, AS);
1280    }
1281    return;
1282  }
1283
1284  SourceLocation DSStart = Tok.getLocation();
1285  // decl-specifier-seq:
1286  // Parse the common declaration-specifiers piece.
1287  ParsingDeclSpec DS(*this);
1288  DS.AddAttributes(AttrList.AttrList);
1289  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class);
1290
1291  Action::MultiTemplateParamsArg TemplateParams(Actions,
1292      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
1293      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
1294
1295  if (Tok.is(tok::semi)) {
1296    ConsumeToken();
1297    Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1298    return;
1299  }
1300
1301  ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
1302
1303  if (Tok.isNot(tok::colon)) {
1304    // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1305    ColonProtectionRAIIObject X(*this);
1306
1307    // Parse the first declarator.
1308    ParseDeclarator(DeclaratorInfo);
1309    // Error parsing the declarator?
1310    if (!DeclaratorInfo.hasName()) {
1311      // If so, skip until the semi-colon or a }.
1312      SkipUntil(tok::r_brace, true);
1313      if (Tok.is(tok::semi))
1314        ConsumeToken();
1315      return;
1316    }
1317
1318    // If attributes exist after the declarator, but before an '{', parse them.
1319    if (Tok.is(tok::kw___attribute)) {
1320      SourceLocation Loc;
1321      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1322      DeclaratorInfo.AddAttributes(AttrList, Loc);
1323    }
1324
1325    // function-definition:
1326    if (Tok.is(tok::l_brace)
1327        || (DeclaratorInfo.isFunctionDeclarator() &&
1328            (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) {
1329      if (!DeclaratorInfo.isFunctionDeclarator()) {
1330        Diag(Tok, diag::err_func_def_no_params);
1331        ConsumeBrace();
1332        SkipUntil(tok::r_brace, true);
1333        return;
1334      }
1335
1336      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1337        Diag(Tok, diag::err_function_declared_typedef);
1338        // This recovery skips the entire function body. It would be nice
1339        // to simply call ParseCXXInlineMethodDef() below, however Sema
1340        // assumes the declarator represents a function, not a typedef.
1341        ConsumeBrace();
1342        SkipUntil(tok::r_brace, true);
1343        return;
1344      }
1345
1346      ParseCXXInlineMethodDef(AS, DeclaratorInfo, TemplateInfo);
1347      return;
1348    }
1349  }
1350
1351  // member-declarator-list:
1352  //   member-declarator
1353  //   member-declarator-list ',' member-declarator
1354
1355  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
1356  OwningExprResult BitfieldSize(Actions);
1357  OwningExprResult Init(Actions);
1358  bool Deleted = false;
1359
1360  while (1) {
1361    // member-declarator:
1362    //   declarator pure-specifier[opt]
1363    //   declarator constant-initializer[opt]
1364    //   identifier[opt] ':' constant-expression
1365
1366    if (Tok.is(tok::colon)) {
1367      ConsumeToken();
1368      BitfieldSize = ParseConstantExpression();
1369      if (BitfieldSize.isInvalid())
1370        SkipUntil(tok::comma, true, true);
1371    }
1372
1373    // pure-specifier:
1374    //   '= 0'
1375    //
1376    // constant-initializer:
1377    //   '=' constant-expression
1378    //
1379    // defaulted/deleted function-definition:
1380    //   '=' 'default'                          [TODO]
1381    //   '=' 'delete'
1382
1383    if (Tok.is(tok::equal)) {
1384      ConsumeToken();
1385      if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
1386        ConsumeToken();
1387        Deleted = true;
1388      } else {
1389        Init = ParseInitializer();
1390        if (Init.isInvalid())
1391          SkipUntil(tok::comma, true, true);
1392      }
1393    }
1394
1395    // If attributes exist after the declarator, parse them.
1396    if (Tok.is(tok::kw___attribute)) {
1397      SourceLocation Loc;
1398      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1399      DeclaratorInfo.AddAttributes(AttrList, Loc);
1400    }
1401
1402    // NOTE: If Sema is the Action module and declarator is an instance field,
1403    // this call will *not* return the created decl; It will return null.
1404    // See Sema::ActOnCXXMemberDeclarator for details.
1405
1406    DeclPtrTy ThisDecl;
1407    if (DS.isFriendSpecified()) {
1408      // TODO: handle initializers, bitfields, 'delete'
1409      ThisDecl = Actions.ActOnFriendFunctionDecl(CurScope, DeclaratorInfo,
1410                                                 /*IsDefinition*/ false,
1411                                                 move(TemplateParams));
1412    } else {
1413      ThisDecl = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
1414                                                  DeclaratorInfo,
1415                                                  move(TemplateParams),
1416                                                  BitfieldSize.release(),
1417                                                  Init.release(),
1418                                                  /*IsDefinition*/Deleted,
1419                                                  Deleted);
1420    }
1421    if (ThisDecl)
1422      DeclsInGroup.push_back(ThisDecl);
1423
1424    if (DeclaratorInfo.isFunctionDeclarator() &&
1425        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
1426          != DeclSpec::SCS_typedef) {
1427      HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl);
1428    }
1429
1430    DeclaratorInfo.complete(ThisDecl);
1431
1432    // If we don't have a comma, it is either the end of the list (a ';')
1433    // or an error, bail out.
1434    if (Tok.isNot(tok::comma))
1435      break;
1436
1437    // Consume the comma.
1438    ConsumeToken();
1439
1440    // Parse the next declarator.
1441    DeclaratorInfo.clear();
1442    BitfieldSize = 0;
1443    Init = 0;
1444    Deleted = false;
1445
1446    // Attributes are only allowed on the second declarator.
1447    if (Tok.is(tok::kw___attribute)) {
1448      SourceLocation Loc;
1449      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1450      DeclaratorInfo.AddAttributes(AttrList, Loc);
1451    }
1452
1453    if (Tok.isNot(tok::colon))
1454      ParseDeclarator(DeclaratorInfo);
1455  }
1456
1457  if (ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
1458    // Skip to end of block or statement.
1459    SkipUntil(tok::r_brace, true, true);
1460    // If we stopped at a ';', eat it.
1461    if (Tok.is(tok::semi)) ConsumeToken();
1462    return;
1463  }
1464
1465  Actions.FinalizeDeclaratorGroup(CurScope, DS, DeclsInGroup.data(),
1466                                  DeclsInGroup.size());
1467}
1468
1469/// ParseCXXMemberSpecification - Parse the class definition.
1470///
1471///       member-specification:
1472///         member-declaration member-specification[opt]
1473///         access-specifier ':' member-specification[opt]
1474///
1475void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
1476                                         unsigned TagType, DeclPtrTy TagDecl) {
1477  assert((TagType == DeclSpec::TST_struct ||
1478         TagType == DeclSpec::TST_union  ||
1479         TagType == DeclSpec::TST_class) && "Invalid TagType!");
1480
1481  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1482                                        PP.getSourceManager(),
1483                                        "parsing struct/union/class body");
1484
1485  // Determine whether this is a non-nested class. Note that local
1486  // classes are *not* considered to be nested classes.
1487  bool NonNestedClass = true;
1488  if (!ClassStack.empty()) {
1489    for (const Scope *S = CurScope; S; S = S->getParent()) {
1490      if (S->isClassScope()) {
1491        // We're inside a class scope, so this is a nested class.
1492        NonNestedClass = false;
1493        break;
1494      }
1495
1496      if ((S->getFlags() & Scope::FnScope)) {
1497        // If we're in a function or function template declared in the
1498        // body of a class, then this is a local class rather than a
1499        // nested class.
1500        const Scope *Parent = S->getParent();
1501        if (Parent->isTemplateParamScope())
1502          Parent = Parent->getParent();
1503        if (Parent->isClassScope())
1504          break;
1505      }
1506    }
1507  }
1508
1509  // Enter a scope for the class.
1510  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
1511
1512  // Note that we are parsing a new (potentially-nested) class definition.
1513  ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass);
1514
1515  if (TagDecl)
1516    Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1517
1518  if (Tok.is(tok::colon)) {
1519    ParseBaseClause(TagDecl);
1520
1521    if (!Tok.is(tok::l_brace)) {
1522      Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
1523      return;
1524    }
1525  }
1526
1527  assert(Tok.is(tok::l_brace));
1528
1529  SourceLocation LBraceLoc = ConsumeBrace();
1530
1531  if (!TagDecl) {
1532    SkipUntil(tok::r_brace, false, false);
1533    return;
1534  }
1535
1536  Actions.ActOnStartCXXMemberDeclarations(CurScope, TagDecl, LBraceLoc);
1537
1538  // C++ 11p3: Members of a class defined with the keyword class are private
1539  // by default. Members of a class defined with the keywords struct or union
1540  // are public by default.
1541  AccessSpecifier CurAS;
1542  if (TagType == DeclSpec::TST_class)
1543    CurAS = AS_private;
1544  else
1545    CurAS = AS_public;
1546
1547  // While we still have something to read, read the member-declarations.
1548  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1549    // Each iteration of this loop reads one member-declaration.
1550
1551    // Check for extraneous top-level semicolon.
1552    if (Tok.is(tok::semi)) {
1553      Diag(Tok, diag::ext_extra_struct_semi)
1554        << CodeModificationHint::CreateRemoval(Tok.getLocation());
1555      ConsumeToken();
1556      continue;
1557    }
1558
1559    AccessSpecifier AS = getAccessSpecifierIfPresent();
1560    if (AS != AS_none) {
1561      // Current token is a C++ access specifier.
1562      CurAS = AS;
1563      ConsumeToken();
1564      ExpectAndConsume(tok::colon, diag::err_expected_colon);
1565      continue;
1566    }
1567
1568    // FIXME: Make sure we don't have a template here.
1569
1570    // Parse all the comma separated declarators.
1571    ParseCXXClassMemberDeclaration(CurAS);
1572  }
1573
1574  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1575
1576  // If attributes exist after class contents, parse them.
1577  llvm::OwningPtr<AttributeList> AttrList;
1578  if (Tok.is(tok::kw___attribute))
1579    AttrList.reset(ParseGNUAttributes()); // FIXME: where should I put them?
1580
1581  Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
1582                                            LBraceLoc, RBraceLoc);
1583
1584  // C++ 9.2p2: Within the class member-specification, the class is regarded as
1585  // complete within function bodies, default arguments,
1586  // exception-specifications, and constructor ctor-initializers (including
1587  // such things in nested classes).
1588  //
1589  // FIXME: Only function bodies and constructor ctor-initializers are
1590  // parsed correctly, fix the rest.
1591  if (NonNestedClass) {
1592    // We are not inside a nested class. This class and its nested classes
1593    // are complete and we can parse the delayed portions of method
1594    // declarations and the lexed inline method definitions.
1595    ParseLexedMethodDeclarations(getCurrentClass());
1596    ParseLexedMethodDefs(getCurrentClass());
1597  }
1598
1599  // Leave the class scope.
1600  ParsingDef.Pop();
1601  ClassScope.Exit();
1602
1603  Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1604}
1605
1606/// ParseConstructorInitializer - Parse a C++ constructor initializer,
1607/// which explicitly initializes the members or base classes of a
1608/// class (C++ [class.base.init]). For example, the three initializers
1609/// after the ':' in the Derived constructor below:
1610///
1611/// @code
1612/// class Base { };
1613/// class Derived : Base {
1614///   int x;
1615///   float f;
1616/// public:
1617///   Derived(float f) : Base(), x(17), f(f) { }
1618/// };
1619/// @endcode
1620///
1621/// [C++]  ctor-initializer:
1622///          ':' mem-initializer-list
1623///
1624/// [C++]  mem-initializer-list:
1625///          mem-initializer
1626///          mem-initializer , mem-initializer-list
1627void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) {
1628  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
1629
1630  SourceLocation ColonLoc = ConsumeToken();
1631
1632  llvm::SmallVector<MemInitTy*, 4> MemInitializers;
1633  bool AnyErrors = false;
1634
1635  do {
1636    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
1637    if (!MemInit.isInvalid())
1638      MemInitializers.push_back(MemInit.get());
1639    else
1640      AnyErrors = true;
1641
1642    if (Tok.is(tok::comma))
1643      ConsumeToken();
1644    else if (Tok.is(tok::l_brace))
1645      break;
1646    else {
1647      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1648      Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
1649      SkipUntil(tok::l_brace, true, true);
1650      break;
1651    }
1652  } while (true);
1653
1654  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
1655                               MemInitializers.data(), MemInitializers.size(),
1656                               AnyErrors);
1657}
1658
1659/// ParseMemInitializer - Parse a C++ member initializer, which is
1660/// part of a constructor initializer that explicitly initializes one
1661/// member or base class (C++ [class.base.init]). See
1662/// ParseConstructorInitializer for an example.
1663///
1664/// [C++] mem-initializer:
1665///         mem-initializer-id '(' expression-list[opt] ')'
1666///
1667/// [C++] mem-initializer-id:
1668///         '::'[opt] nested-name-specifier[opt] class-name
1669///         identifier
1670Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) {
1671  // parse '::'[opt] nested-name-specifier[opt]
1672  CXXScopeSpec SS;
1673  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
1674  TypeTy *TemplateTypeTy = 0;
1675  if (Tok.is(tok::annot_template_id)) {
1676    TemplateIdAnnotation *TemplateId
1677      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1678    if (TemplateId->Kind == TNK_Type_template ||
1679        TemplateId->Kind == TNK_Dependent_template_name) {
1680      AnnotateTemplateIdTokenAsType(&SS);
1681      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1682      TemplateTypeTy = Tok.getAnnotationValue();
1683    }
1684  }
1685  if (!TemplateTypeTy && Tok.isNot(tok::identifier)) {
1686    Diag(Tok, diag::err_expected_member_or_base_name);
1687    return true;
1688  }
1689
1690  // Get the identifier. This may be a member name or a class name,
1691  // but we'll let the semantic analysis determine which it is.
1692  IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0;
1693  SourceLocation IdLoc = ConsumeToken();
1694
1695  // Parse the '('.
1696  if (Tok.isNot(tok::l_paren)) {
1697    Diag(Tok, diag::err_expected_lparen);
1698    return true;
1699  }
1700  SourceLocation LParenLoc = ConsumeParen();
1701
1702  // Parse the optional expression-list.
1703  ExprVector ArgExprs(Actions);
1704  CommaLocsTy CommaLocs;
1705  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
1706    SkipUntil(tok::r_paren);
1707    return true;
1708  }
1709
1710  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1711
1712  return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, SS, II,
1713                                     TemplateTypeTy, IdLoc,
1714                                     LParenLoc, ArgExprs.take(),
1715                                     ArgExprs.size(), CommaLocs.data(),
1716                                     RParenLoc);
1717}
1718
1719/// ParseExceptionSpecification - Parse a C++ exception-specification
1720/// (C++ [except.spec]).
1721///
1722///       exception-specification:
1723///         'throw' '(' type-id-list [opt] ')'
1724/// [MS]    'throw' '(' '...' ')'
1725///
1726///       type-id-list:
1727///         type-id
1728///         type-id-list ',' type-id
1729///
1730bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc,
1731                                         llvm::SmallVector<TypeTy*, 2>
1732                                             &Exceptions,
1733                                         llvm::SmallVector<SourceRange, 2>
1734                                             &Ranges,
1735                                         bool &hasAnyExceptionSpec) {
1736  assert(Tok.is(tok::kw_throw) && "expected throw");
1737
1738  SourceLocation ThrowLoc = ConsumeToken();
1739
1740  if (!Tok.is(tok::l_paren)) {
1741    return Diag(Tok, diag::err_expected_lparen_after) << "throw";
1742  }
1743  SourceLocation LParenLoc = ConsumeParen();
1744
1745  // Parse throw(...), a Microsoft extension that means "this function
1746  // can throw anything".
1747  if (Tok.is(tok::ellipsis)) {
1748    hasAnyExceptionSpec = true;
1749    SourceLocation EllipsisLoc = ConsumeToken();
1750    if (!getLang().Microsoft)
1751      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
1752    EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1753    return false;
1754  }
1755
1756  // Parse the sequence of type-ids.
1757  SourceRange Range;
1758  while (Tok.isNot(tok::r_paren)) {
1759    TypeResult Res(ParseTypeName(&Range));
1760    if (!Res.isInvalid()) {
1761      Exceptions.push_back(Res.get());
1762      Ranges.push_back(Range);
1763    }
1764    if (Tok.is(tok::comma))
1765      ConsumeToken();
1766    else
1767      break;
1768  }
1769
1770  EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1771  return false;
1772}
1773
1774/// \brief We have just started parsing the definition of a new class,
1775/// so push that class onto our stack of classes that is currently
1776/// being parsed.
1777void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool NonNestedClass) {
1778  assert((NonNestedClass || !ClassStack.empty()) &&
1779         "Nested class without outer class");
1780  ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass));
1781}
1782
1783/// \brief Deallocate the given parsed class and all of its nested
1784/// classes.
1785void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
1786  for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I)
1787    DeallocateParsedClasses(Class->NestedClasses[I]);
1788  delete Class;
1789}
1790
1791/// \brief Pop the top class of the stack of classes that are
1792/// currently being parsed.
1793///
1794/// This routine should be called when we have finished parsing the
1795/// definition of a class, but have not yet popped the Scope
1796/// associated with the class's definition.
1797///
1798/// \returns true if the class we've popped is a top-level class,
1799/// false otherwise.
1800void Parser::PopParsingClass() {
1801  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
1802
1803  ParsingClass *Victim = ClassStack.top();
1804  ClassStack.pop();
1805  if (Victim->TopLevelClass) {
1806    // Deallocate all of the nested classes of this class,
1807    // recursively: we don't need to keep any of this information.
1808    DeallocateParsedClasses(Victim);
1809    return;
1810  }
1811  assert(!ClassStack.empty() && "Missing top-level class?");
1812
1813  if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() &&
1814      Victim->NestedClasses.empty()) {
1815    // The victim is a nested class, but we will not need to perform
1816    // any processing after the definition of this class since it has
1817    // no members whose handling was delayed. Therefore, we can just
1818    // remove this nested class.
1819    delete Victim;
1820    return;
1821  }
1822
1823  // This nested class has some members that will need to be processed
1824  // after the top-level class is completely defined. Therefore, add
1825  // it to the list of nested classes within its parent.
1826  assert(CurScope->isClassScope() && "Nested class outside of class scope?");
1827  ClassStack.top()->NestedClasses.push_back(Victim);
1828  Victim->TemplateScope = CurScope->getParent()->isTemplateParamScope();
1829}
1830
1831/// ParseCXX0XAttributes - Parse a C++0x attribute-specifier. Currently only
1832/// parses standard attributes.
1833///
1834/// [C++0x] attribute-specifier:
1835///         '[' '[' attribute-list ']' ']'
1836///
1837/// [C++0x] attribute-list:
1838///         attribute[opt]
1839///         attribute-list ',' attribute[opt]
1840///
1841/// [C++0x] attribute:
1842///         attribute-token attribute-argument-clause[opt]
1843///
1844/// [C++0x] attribute-token:
1845///         identifier
1846///         attribute-scoped-token
1847///
1848/// [C++0x] attribute-scoped-token:
1849///         attribute-namespace '::' identifier
1850///
1851/// [C++0x] attribute-namespace:
1852///         identifier
1853///
1854/// [C++0x] attribute-argument-clause:
1855///         '(' balanced-token-seq ')'
1856///
1857/// [C++0x] balanced-token-seq:
1858///         balanced-token
1859///         balanced-token-seq balanced-token
1860///
1861/// [C++0x] balanced-token:
1862///         '(' balanced-token-seq ')'
1863///         '[' balanced-token-seq ']'
1864///         '{' balanced-token-seq '}'
1865///         any token but '(', ')', '[', ']', '{', or '}'
1866CXX0XAttributeList Parser::ParseCXX0XAttributes(SourceLocation *EndLoc) {
1867  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
1868      && "Not a C++0x attribute list");
1869
1870  SourceLocation StartLoc = Tok.getLocation(), Loc;
1871  AttributeList *CurrAttr = 0;
1872
1873  ConsumeBracket();
1874  ConsumeBracket();
1875
1876  if (Tok.is(tok::comma)) {
1877    Diag(Tok.getLocation(), diag::err_expected_ident);
1878    ConsumeToken();
1879  }
1880
1881  while (Tok.is(tok::identifier) || Tok.is(tok::comma)) {
1882    // attribute not present
1883    if (Tok.is(tok::comma)) {
1884      ConsumeToken();
1885      continue;
1886    }
1887
1888    IdentifierInfo *ScopeName = 0, *AttrName = Tok.getIdentifierInfo();
1889    SourceLocation ScopeLoc, AttrLoc = ConsumeToken();
1890
1891    // scoped attribute
1892    if (Tok.is(tok::coloncolon)) {
1893      ConsumeToken();
1894
1895      if (!Tok.is(tok::identifier)) {
1896        Diag(Tok.getLocation(), diag::err_expected_ident);
1897        SkipUntil(tok::r_square, tok::comma, true, true);
1898        continue;
1899      }
1900
1901      ScopeName = AttrName;
1902      ScopeLoc = AttrLoc;
1903
1904      AttrName = Tok.getIdentifierInfo();
1905      AttrLoc = ConsumeToken();
1906    }
1907
1908    bool AttrParsed = false;
1909    // No scoped names are supported; ideally we could put all non-standard
1910    // attributes into namespaces.
1911    if (!ScopeName) {
1912      switch(AttributeList::getKind(AttrName))
1913      {
1914      // No arguments
1915      case AttributeList::AT_base_check:
1916      case AttributeList::AT_carries_dependency:
1917      case AttributeList::AT_final:
1918      case AttributeList::AT_hiding:
1919      case AttributeList::AT_noreturn:
1920      case AttributeList::AT_override: {
1921        if (Tok.is(tok::l_paren)) {
1922          Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_arguments)
1923            << AttrName->getName();
1924          break;
1925        }
1926
1927        CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc, 0,
1928                                     SourceLocation(), 0, 0, CurrAttr, false,
1929                                     true);
1930        AttrParsed = true;
1931        break;
1932      }
1933
1934      // One argument; must be a type-id or assignment-expression
1935      case AttributeList::AT_aligned: {
1936        if (Tok.isNot(tok::l_paren)) {
1937          Diag(Tok.getLocation(), diag::err_cxx0x_attribute_requires_arguments)
1938            << AttrName->getName();
1939          break;
1940        }
1941        SourceLocation ParamLoc = ConsumeParen();
1942
1943        OwningExprResult ArgExpr = ParseCXX0XAlignArgument(ParamLoc);
1944
1945        MatchRHSPunctuation(tok::r_paren, ParamLoc);
1946
1947        ExprVector ArgExprs(Actions);
1948        ArgExprs.push_back(ArgExpr.release());
1949        CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc,
1950                                     0, ParamLoc, ArgExprs.take(), 1, CurrAttr,
1951                                     false, true);
1952
1953        AttrParsed = true;
1954        break;
1955      }
1956
1957      // Silence warnings
1958      default: break;
1959      }
1960    }
1961
1962    // Skip the entire parameter clause, if any
1963    if (!AttrParsed && Tok.is(tok::l_paren)) {
1964      ConsumeParen();
1965      // SkipUntil maintains the balancedness of tokens.
1966      SkipUntil(tok::r_paren, false);
1967    }
1968  }
1969
1970  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
1971    SkipUntil(tok::r_square, false);
1972  Loc = Tok.getLocation();
1973  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
1974    SkipUntil(tok::r_square, false);
1975
1976  CXX0XAttributeList Attr (CurrAttr, SourceRange(StartLoc, Loc), true);
1977  return Attr;
1978}
1979
1980/// ParseCXX0XAlignArgument - Parse the argument to C++0x's [[align]]
1981/// attribute.
1982///
1983/// FIXME: Simply returns an alignof() expression if the argument is a
1984/// type. Ideally, the type should be propagated directly into Sema.
1985///
1986/// [C++0x] 'align' '(' type-id ')'
1987/// [C++0x] 'align' '(' assignment-expression ')'
1988Parser::OwningExprResult Parser::ParseCXX0XAlignArgument(SourceLocation Start) {
1989  if (isTypeIdInParens()) {
1990    EnterExpressionEvaluationContext Unevaluated(Actions,
1991                                                  Action::Unevaluated);
1992    SourceLocation TypeLoc = Tok.getLocation();
1993    TypeTy *Ty = ParseTypeName().get();
1994    SourceRange TypeRange(Start, Tok.getLocation());
1995    return Actions.ActOnSizeOfAlignOfExpr(TypeLoc, false, true, Ty,
1996                                              TypeRange);
1997  } else
1998    return ParseConstantExpression();
1999}
2000