ParseDeclCXX.cpp revision 74256f5ea6950c9fd34595aa124eb4740372f15c
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                                          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  bool Owned = false;
784  if (TemplateId) {
785    // Explicit specialization, class template partial specialization,
786    // or explicit instantiation.
787    ASTTemplateArgsPtr TemplateArgsPtr(Actions,
788                                       TemplateId->getTemplateArgs(),
789                                       TemplateId->NumArgs);
790    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
791        TUK == Action::TUK_Declaration) {
792      // This is an explicit instantiation of a class template.
793      TagOrTempResult
794        = Actions.ActOnExplicitInstantiation(CurScope,
795                                             TemplateInfo.ExternLoc,
796                                             TemplateInfo.TemplateLoc,
797                                             TagType,
798                                             StartLoc,
799                                             SS,
800                                     TemplateTy::make(TemplateId->Template),
801                                             TemplateId->TemplateNameLoc,
802                                             TemplateId->LAngleLoc,
803                                             TemplateArgsPtr,
804                                             TemplateId->RAngleLoc,
805                                             AttrList);
806
807    // Friend template-ids are treated as references unless
808    // they have template headers, in which case they're ill-formed
809    // (FIXME: "template <class T> friend class A<T>::B<int>;").
810    // We diagnose this error in ActOnClassTemplateSpecialization.
811    } else if (TUK == Action::TUK_Reference ||
812               (TUK == Action::TUK_Friend &&
813                TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
814      TypeResult
815        = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
816                                      TemplateId->TemplateNameLoc,
817                                      TemplateId->LAngleLoc,
818                                      TemplateArgsPtr,
819                                      TemplateId->RAngleLoc);
820
821      TypeResult = Actions.ActOnTagTemplateIdType(TypeResult, TUK,
822                                                  TagType, StartLoc);
823    } else {
824      // This is an explicit specialization or a class template
825      // partial specialization.
826      TemplateParameterLists FakedParamLists;
827
828      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
829        // This looks like an explicit instantiation, because we have
830        // something like
831        //
832        //   template class Foo<X>
833        //
834        // but it actually has a definition. Most likely, this was
835        // meant to be an explicit specialization, but the user forgot
836        // the '<>' after 'template'.
837        assert(TUK == Action::TUK_Definition && "Expected a definition here");
838
839        SourceLocation LAngleLoc
840          = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
841        Diag(TemplateId->TemplateNameLoc,
842             diag::err_explicit_instantiation_with_definition)
843          << SourceRange(TemplateInfo.TemplateLoc)
844          << FixItHint::CreateInsertion(LAngleLoc, "<>");
845
846        // Create a fake template parameter list that contains only
847        // "template<>", so that we treat this construct as a class
848        // template specialization.
849        FakedParamLists.push_back(
850          Actions.ActOnTemplateParameterList(0, SourceLocation(),
851                                             TemplateInfo.TemplateLoc,
852                                             LAngleLoc,
853                                             0, 0,
854                                             LAngleLoc));
855        TemplateParams = &FakedParamLists;
856      }
857
858      // Build the class template specialization.
859      TagOrTempResult
860        = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TUK,
861                       StartLoc, SS,
862                       TemplateTy::make(TemplateId->Template),
863                       TemplateId->TemplateNameLoc,
864                       TemplateId->LAngleLoc,
865                       TemplateArgsPtr,
866                       TemplateId->RAngleLoc,
867                       AttrList,
868                       Action::MultiTemplateParamsArg(Actions,
869                                    TemplateParams? &(*TemplateParams)[0] : 0,
870                                 TemplateParams? TemplateParams->size() : 0));
871    }
872    TemplateId->Destroy();
873  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
874             TUK == Action::TUK_Declaration) {
875    // Explicit instantiation of a member of a class template
876    // specialization, e.g.,
877    //
878    //   template struct Outer<int>::Inner;
879    //
880    TagOrTempResult
881      = Actions.ActOnExplicitInstantiation(CurScope,
882                                           TemplateInfo.ExternLoc,
883                                           TemplateInfo.TemplateLoc,
884                                           TagType, StartLoc, SS, Name,
885                                           NameLoc, AttrList);
886  } else {
887    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
888        TUK == Action::TUK_Definition) {
889      // FIXME: Diagnose this particular error.
890    }
891
892    bool IsDependent = false;
893
894    // Declaration or definition of a class type
895    TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TUK, StartLoc, SS,
896                                       Name, NameLoc, AttrList, AS,
897                                  Action::MultiTemplateParamsArg(Actions,
898                                    TemplateParams? &(*TemplateParams)[0] : 0,
899                                    TemplateParams? TemplateParams->size() : 0),
900                                       Owned, IsDependent);
901
902    // If ActOnTag said the type was dependent, try again with the
903    // less common call.
904    if (IsDependent)
905      TypeResult = Actions.ActOnDependentTag(CurScope, TagType, TUK,
906                                             SS, Name, StartLoc, NameLoc);
907  }
908
909  // If there is a body, parse it and inform the actions module.
910  if (TUK == Action::TUK_Definition) {
911    assert(Tok.is(tok::l_brace) ||
912           (getLang().CPlusPlus && Tok.is(tok::colon)));
913    if (getLang().CPlusPlus)
914      ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
915    else
916      ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
917  }
918
919  void *Result;
920  if (!TypeResult.isInvalid()) {
921    TagType = DeclSpec::TST_typename;
922    Result = TypeResult.get();
923    Owned = false;
924  } else if (!TagOrTempResult.isInvalid()) {
925    Result = TagOrTempResult.get().getAs<void>();
926  } else {
927    DS.SetTypeSpecError();
928    return;
929  }
930
931  const char *PrevSpec = 0;
932  unsigned DiagID;
933
934  // FIXME: The DeclSpec should keep the locations of both the keyword and the
935  // name (if there is one).
936  SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc;
937
938  if (DS.SetTypeSpecType(TagType, TSTLoc, PrevSpec, DiagID,
939                         Result, Owned))
940    Diag(StartLoc, DiagID) << PrevSpec;
941
942  // At this point, we've successfully parsed a class-specifier in 'definition'
943  // form (e.g. "struct foo { int x; }".  While we could just return here, we're
944  // going to look at what comes after it to improve error recovery.  If an
945  // impossible token occurs next, we assume that the programmer forgot a ; at
946  // the end of the declaration and recover that way.
947  //
948  // This switch enumerates the valid "follow" set for definition.
949  if (TUK == Action::TUK_Definition) {
950    bool ExpectedSemi = true;
951    switch (Tok.getKind()) {
952    default: break;
953    case tok::semi:               // struct foo {...} ;
954    case tok::star:               // struct foo {...} *         P;
955    case tok::amp:                // struct foo {...} &         R = ...
956    case tok::identifier:         // struct foo {...} V         ;
957    case tok::r_paren:            //(struct foo {...} )         {4}
958    case tok::annot_cxxscope:     // struct foo {...} a::       b;
959    case tok::annot_typename:     // struct foo {...} a         ::b;
960    case tok::annot_template_id:  // struct foo {...} a<int>    ::b;
961    case tok::l_paren:            // struct foo {...} (         x);
962    case tok::comma:              // __builtin_offsetof(struct foo{...} ,
963      ExpectedSemi = false;
964      break;
965    // Type qualifiers
966    case tok::kw_const:           // struct foo {...} const     x;
967    case tok::kw_volatile:        // struct foo {...} volatile  x;
968    case tok::kw_restrict:        // struct foo {...} restrict  x;
969    case tok::kw_inline:          // struct foo {...} inline    foo() {};
970    // Storage-class specifiers
971    case tok::kw_static:          // struct foo {...} static    x;
972    case tok::kw_extern:          // struct foo {...} extern    x;
973    case tok::kw_typedef:         // struct foo {...} typedef   x;
974    case tok::kw_register:        // struct foo {...} register  x;
975    case tok::kw_auto:            // struct foo {...} auto      x;
976      // As shown above, type qualifiers and storage class specifiers absolutely
977      // can occur after class specifiers according to the grammar.  However,
978      // almost noone actually writes code like this.  If we see one of these,
979      // it is much more likely that someone missed a semi colon and the
980      // type/storage class specifier we're seeing is part of the *next*
981      // intended declaration, as in:
982      //
983      //   struct foo { ... }
984      //   typedef int X;
985      //
986      // We'd really like to emit a missing semicolon error instead of emitting
987      // an error on the 'int' saying that you can't have two type specifiers in
988      // the same declaration of X.  Because of this, we look ahead past this
989      // token to see if it's a type specifier.  If so, we know the code is
990      // otherwise invalid, so we can produce the expected semi error.
991      if (!isKnownToBeTypeSpecifier(NextToken()))
992        ExpectedSemi = false;
993      break;
994
995    case tok::r_brace:  // struct bar { struct foo {...} }
996      // Missing ';' at end of struct is accepted as an extension in C mode.
997      if (!getLang().CPlusPlus)
998        ExpectedSemi = false;
999      break;
1000    }
1001
1002    if (ExpectedSemi) {
1003      ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1004                       TagType == DeclSpec::TST_class ? "class"
1005                       : TagType == DeclSpec::TST_struct? "struct" : "union");
1006      // Push this token back into the preprocessor and change our current token
1007      // to ';' so that the rest of the code recovers as though there were an
1008      // ';' after the definition.
1009      PP.EnterToken(Tok);
1010      Tok.setKind(tok::semi);
1011    }
1012  }
1013}
1014
1015/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1016///
1017///       base-clause : [C++ class.derived]
1018///         ':' base-specifier-list
1019///       base-specifier-list:
1020///         base-specifier '...'[opt]
1021///         base-specifier-list ',' base-specifier '...'[opt]
1022void Parser::ParseBaseClause(DeclPtrTy ClassDecl) {
1023  assert(Tok.is(tok::colon) && "Not a base clause");
1024  ConsumeToken();
1025
1026  // Build up an array of parsed base specifiers.
1027  llvm::SmallVector<BaseTy *, 8> BaseInfo;
1028
1029  while (true) {
1030    // Parse a base-specifier.
1031    BaseResult Result = ParseBaseSpecifier(ClassDecl);
1032    if (Result.isInvalid()) {
1033      // Skip the rest of this base specifier, up until the comma or
1034      // opening brace.
1035      SkipUntil(tok::comma, tok::l_brace, true, true);
1036    } else {
1037      // Add this to our array of base specifiers.
1038      BaseInfo.push_back(Result.get());
1039    }
1040
1041    // If the next token is a comma, consume it and keep reading
1042    // base-specifiers.
1043    if (Tok.isNot(tok::comma)) break;
1044
1045    // Consume the comma.
1046    ConsumeToken();
1047  }
1048
1049  // Attach the base specifiers
1050  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1051}
1052
1053/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1054/// one entry in the base class list of a class specifier, for example:
1055///    class foo : public bar, virtual private baz {
1056/// 'public bar' and 'virtual private baz' are each base-specifiers.
1057///
1058///       base-specifier: [C++ class.derived]
1059///         ::[opt] nested-name-specifier[opt] class-name
1060///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
1061///                        class-name
1062///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
1063///                        class-name
1064Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) {
1065  bool IsVirtual = false;
1066  SourceLocation StartLoc = Tok.getLocation();
1067
1068  // Parse the 'virtual' keyword.
1069  if (Tok.is(tok::kw_virtual))  {
1070    ConsumeToken();
1071    IsVirtual = true;
1072  }
1073
1074  // Parse an (optional) access specifier.
1075  AccessSpecifier Access = getAccessSpecifierIfPresent();
1076  if (Access != AS_none)
1077    ConsumeToken();
1078
1079  // Parse the 'virtual' keyword (again!), in case it came after the
1080  // access specifier.
1081  if (Tok.is(tok::kw_virtual))  {
1082    SourceLocation VirtualLoc = ConsumeToken();
1083    if (IsVirtual) {
1084      // Complain about duplicate 'virtual'
1085      Diag(VirtualLoc, diag::err_dup_virtual)
1086        << FixItHint::CreateRemoval(VirtualLoc);
1087    }
1088
1089    IsVirtual = true;
1090  }
1091
1092  // Parse optional '::' and optional nested-name-specifier.
1093  CXXScopeSpec SS;
1094  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0,
1095                                 /*EnteringContext=*/false);
1096
1097  // The location of the base class itself.
1098  SourceLocation BaseLoc = Tok.getLocation();
1099
1100  // Parse the class-name.
1101  SourceLocation EndLocation;
1102  TypeResult BaseType = ParseClassName(EndLocation, &SS);
1103  if (BaseType.isInvalid())
1104    return true;
1105
1106  // Find the complete source range for the base-specifier.
1107  SourceRange Range(StartLoc, EndLocation);
1108
1109  // Notify semantic analysis that we have parsed a complete
1110  // base-specifier.
1111  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
1112                                    BaseType.get(), BaseLoc);
1113}
1114
1115/// getAccessSpecifierIfPresent - Determine whether the next token is
1116/// a C++ access-specifier.
1117///
1118///       access-specifier: [C++ class.derived]
1119///         'private'
1120///         'protected'
1121///         'public'
1122AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1123  switch (Tok.getKind()) {
1124  default: return AS_none;
1125  case tok::kw_private: return AS_private;
1126  case tok::kw_protected: return AS_protected;
1127  case tok::kw_public: return AS_public;
1128  }
1129}
1130
1131void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo,
1132                                             DeclPtrTy ThisDecl) {
1133  // We just declared a member function. If this member function
1134  // has any default arguments, we'll need to parse them later.
1135  LateParsedMethodDeclaration *LateMethod = 0;
1136  DeclaratorChunk::FunctionTypeInfo &FTI
1137    = DeclaratorInfo.getTypeObject(0).Fun;
1138  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1139    if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1140      if (!LateMethod) {
1141        // Push this method onto the stack of late-parsed method
1142        // declarations.
1143        getCurrentClass().MethodDecls.push_back(
1144                                LateParsedMethodDeclaration(ThisDecl));
1145        LateMethod = &getCurrentClass().MethodDecls.back();
1146        LateMethod->TemplateScope = CurScope->isTemplateParamScope();
1147
1148        // Add all of the parameters prior to this one (they don't
1149        // have default arguments).
1150        LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1151        for (unsigned I = 0; I < ParamIdx; ++I)
1152          LateMethod->DefaultArgs.push_back(
1153                             LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
1154      }
1155
1156      // Add this parameter to the list of parameters (it or may
1157      // not have a default argument).
1158      LateMethod->DefaultArgs.push_back(
1159        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1160                                  FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1161    }
1162  }
1163}
1164
1165/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1166///
1167///       member-declaration:
1168///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
1169///         function-definition ';'[opt]
1170///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1171///         using-declaration                                            [TODO]
1172/// [C++0x] static_assert-declaration
1173///         template-declaration
1174/// [GNU]   '__extension__' member-declaration
1175///
1176///       member-declarator-list:
1177///         member-declarator
1178///         member-declarator-list ',' member-declarator
1179///
1180///       member-declarator:
1181///         declarator pure-specifier[opt]
1182///         declarator constant-initializer[opt]
1183///         identifier[opt] ':' constant-expression
1184///
1185///       pure-specifier:
1186///         '= 0'
1187///
1188///       constant-initializer:
1189///         '=' constant-expression
1190///
1191void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1192                                       const ParsedTemplateInfo &TemplateInfo) {
1193  // Access declarations.
1194  if (!TemplateInfo.Kind &&
1195      (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
1196      !TryAnnotateCXXScopeToken() &&
1197      Tok.is(tok::annot_cxxscope)) {
1198    bool isAccessDecl = false;
1199    if (NextToken().is(tok::identifier))
1200      isAccessDecl = GetLookAheadToken(2).is(tok::semi);
1201    else
1202      isAccessDecl = NextToken().is(tok::kw_operator);
1203
1204    if (isAccessDecl) {
1205      // Collect the scope specifier token we annotated earlier.
1206      CXXScopeSpec SS;
1207      ParseOptionalCXXScopeSpecifier(SS, /*ObjectType*/ 0, false);
1208
1209      // Try to parse an unqualified-id.
1210      UnqualifiedId Name;
1211      if (ParseUnqualifiedId(SS, false, true, true, /*ObjectType*/ 0, Name)) {
1212        SkipUntil(tok::semi);
1213        return;
1214      }
1215
1216      // TODO: recover from mistakenly-qualified operator declarations.
1217      if (ExpectAndConsume(tok::semi,
1218                           diag::err_expected_semi_after,
1219                           "access declaration",
1220                           tok::semi))
1221        return;
1222
1223      Actions.ActOnUsingDeclaration(CurScope, AS,
1224                                    false, SourceLocation(),
1225                                    SS, Name,
1226                                    /* AttrList */ 0,
1227                                    /* IsTypeName */ false,
1228                                    SourceLocation());
1229      return;
1230    }
1231  }
1232
1233  // static_assert-declaration
1234  if (Tok.is(tok::kw_static_assert)) {
1235    // FIXME: Check for templates
1236    SourceLocation DeclEnd;
1237    ParseStaticAssertDeclaration(DeclEnd);
1238    return;
1239  }
1240
1241  if (Tok.is(tok::kw_template)) {
1242    assert(!TemplateInfo.TemplateParams &&
1243           "Nested template improperly parsed?");
1244    SourceLocation DeclEnd;
1245    ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
1246                                         AS);
1247    return;
1248  }
1249
1250  // Handle:  member-declaration ::= '__extension__' member-declaration
1251  if (Tok.is(tok::kw___extension__)) {
1252    // __extension__ silences extension warnings in the subexpression.
1253    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1254    ConsumeToken();
1255    return ParseCXXClassMemberDeclaration(AS, TemplateInfo);
1256  }
1257
1258  // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1259  // is a bitfield.
1260  ColonProtectionRAIIObject X(*this);
1261
1262  CXX0XAttributeList AttrList;
1263  // Optional C++0x attribute-specifier
1264  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
1265    AttrList = ParseCXX0XAttributes();
1266
1267  if (Tok.is(tok::kw_using)) {
1268    // FIXME: Check for template aliases
1269
1270    if (AttrList.HasAttr)
1271      Diag(AttrList.Range.getBegin(), diag::err_attributes_not_allowed)
1272        << AttrList.Range;
1273
1274    // Eat 'using'.
1275    SourceLocation UsingLoc = ConsumeToken();
1276
1277    if (Tok.is(tok::kw_namespace)) {
1278      Diag(UsingLoc, diag::err_using_namespace_in_class);
1279      SkipUntil(tok::semi, true, true);
1280    } else {
1281      SourceLocation DeclEnd;
1282      // Otherwise, it must be using-declaration.
1283      ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd, AS);
1284    }
1285    return;
1286  }
1287
1288  SourceLocation DSStart = Tok.getLocation();
1289  // decl-specifier-seq:
1290  // Parse the common declaration-specifiers piece.
1291  ParsingDeclSpec DS(*this);
1292  DS.AddAttributes(AttrList.AttrList);
1293  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class);
1294
1295  Action::MultiTemplateParamsArg TemplateParams(Actions,
1296      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
1297      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
1298
1299  if (Tok.is(tok::semi)) {
1300    ConsumeToken();
1301    Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1302    return;
1303  }
1304
1305  ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
1306
1307  if (Tok.isNot(tok::colon)) {
1308    // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1309    ColonProtectionRAIIObject X(*this);
1310
1311    // Parse the first declarator.
1312    ParseDeclarator(DeclaratorInfo);
1313    // Error parsing the declarator?
1314    if (!DeclaratorInfo.hasName()) {
1315      // If so, skip until the semi-colon or a }.
1316      SkipUntil(tok::r_brace, true);
1317      if (Tok.is(tok::semi))
1318        ConsumeToken();
1319      return;
1320    }
1321
1322    // If attributes exist after the declarator, but before an '{', parse them.
1323    if (Tok.is(tok::kw___attribute)) {
1324      SourceLocation Loc;
1325      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1326      DeclaratorInfo.AddAttributes(AttrList, Loc);
1327    }
1328
1329    // function-definition:
1330    if (Tok.is(tok::l_brace)
1331        || (DeclaratorInfo.isFunctionDeclarator() &&
1332            (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) {
1333      if (!DeclaratorInfo.isFunctionDeclarator()) {
1334        Diag(Tok, diag::err_func_def_no_params);
1335        ConsumeBrace();
1336        SkipUntil(tok::r_brace, true);
1337        return;
1338      }
1339
1340      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1341        Diag(Tok, diag::err_function_declared_typedef);
1342        // This recovery skips the entire function body. It would be nice
1343        // to simply call ParseCXXInlineMethodDef() below, however Sema
1344        // assumes the declarator represents a function, not a typedef.
1345        ConsumeBrace();
1346        SkipUntil(tok::r_brace, true);
1347        return;
1348      }
1349
1350      ParseCXXInlineMethodDef(AS, DeclaratorInfo, TemplateInfo);
1351      return;
1352    }
1353  }
1354
1355  // member-declarator-list:
1356  //   member-declarator
1357  //   member-declarator-list ',' member-declarator
1358
1359  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
1360  OwningExprResult BitfieldSize(Actions);
1361  OwningExprResult Init(Actions);
1362  bool Deleted = false;
1363
1364  while (1) {
1365    // member-declarator:
1366    //   declarator pure-specifier[opt]
1367    //   declarator constant-initializer[opt]
1368    //   identifier[opt] ':' constant-expression
1369
1370    if (Tok.is(tok::colon)) {
1371      ConsumeToken();
1372      BitfieldSize = ParseConstantExpression();
1373      if (BitfieldSize.isInvalid())
1374        SkipUntil(tok::comma, true, true);
1375    }
1376
1377    // pure-specifier:
1378    //   '= 0'
1379    //
1380    // constant-initializer:
1381    //   '=' constant-expression
1382    //
1383    // defaulted/deleted function-definition:
1384    //   '=' 'default'                          [TODO]
1385    //   '=' 'delete'
1386
1387    if (Tok.is(tok::equal)) {
1388      ConsumeToken();
1389      if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
1390        ConsumeToken();
1391        Deleted = true;
1392      } else {
1393        Init = ParseInitializer();
1394        if (Init.isInvalid())
1395          SkipUntil(tok::comma, true, true);
1396      }
1397    }
1398
1399    // If attributes exist after the declarator, parse them.
1400    if (Tok.is(tok::kw___attribute)) {
1401      SourceLocation Loc;
1402      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1403      DeclaratorInfo.AddAttributes(AttrList, Loc);
1404    }
1405
1406    // NOTE: If Sema is the Action module and declarator is an instance field,
1407    // this call will *not* return the created decl; It will return null.
1408    // See Sema::ActOnCXXMemberDeclarator for details.
1409
1410    DeclPtrTy ThisDecl;
1411    if (DS.isFriendSpecified()) {
1412      // TODO: handle initializers, bitfields, 'delete'
1413      ThisDecl = Actions.ActOnFriendFunctionDecl(CurScope, DeclaratorInfo,
1414                                                 /*IsDefinition*/ false,
1415                                                 move(TemplateParams));
1416    } else {
1417      ThisDecl = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
1418                                                  DeclaratorInfo,
1419                                                  move(TemplateParams),
1420                                                  BitfieldSize.release(),
1421                                                  Init.release(),
1422                                                  /*IsDefinition*/Deleted,
1423                                                  Deleted);
1424    }
1425    if (ThisDecl)
1426      DeclsInGroup.push_back(ThisDecl);
1427
1428    if (DeclaratorInfo.isFunctionDeclarator() &&
1429        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
1430          != DeclSpec::SCS_typedef) {
1431      HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl);
1432    }
1433
1434    DeclaratorInfo.complete(ThisDecl);
1435
1436    // If we don't have a comma, it is either the end of the list (a ';')
1437    // or an error, bail out.
1438    if (Tok.isNot(tok::comma))
1439      break;
1440
1441    // Consume the comma.
1442    ConsumeToken();
1443
1444    // Parse the next declarator.
1445    DeclaratorInfo.clear();
1446    BitfieldSize = 0;
1447    Init = 0;
1448    Deleted = false;
1449
1450    // Attributes are only allowed on the second declarator.
1451    if (Tok.is(tok::kw___attribute)) {
1452      SourceLocation Loc;
1453      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1454      DeclaratorInfo.AddAttributes(AttrList, Loc);
1455    }
1456
1457    if (Tok.isNot(tok::colon))
1458      ParseDeclarator(DeclaratorInfo);
1459  }
1460
1461  if (ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
1462    // Skip to end of block or statement.
1463    SkipUntil(tok::r_brace, true, true);
1464    // If we stopped at a ';', eat it.
1465    if (Tok.is(tok::semi)) ConsumeToken();
1466    return;
1467  }
1468
1469  Actions.FinalizeDeclaratorGroup(CurScope, DS, DeclsInGroup.data(),
1470                                  DeclsInGroup.size());
1471}
1472
1473/// ParseCXXMemberSpecification - Parse the class definition.
1474///
1475///       member-specification:
1476///         member-declaration member-specification[opt]
1477///         access-specifier ':' member-specification[opt]
1478///
1479void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
1480                                         unsigned TagType, DeclPtrTy TagDecl) {
1481  assert((TagType == DeclSpec::TST_struct ||
1482         TagType == DeclSpec::TST_union  ||
1483         TagType == DeclSpec::TST_class) && "Invalid TagType!");
1484
1485  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1486                                        PP.getSourceManager(),
1487                                        "parsing struct/union/class body");
1488
1489  // Determine whether this is a non-nested class. Note that local
1490  // classes are *not* considered to be nested classes.
1491  bool NonNestedClass = true;
1492  if (!ClassStack.empty()) {
1493    for (const Scope *S = CurScope; S; S = S->getParent()) {
1494      if (S->isClassScope()) {
1495        // We're inside a class scope, so this is a nested class.
1496        NonNestedClass = false;
1497        break;
1498      }
1499
1500      if ((S->getFlags() & Scope::FnScope)) {
1501        // If we're in a function or function template declared in the
1502        // body of a class, then this is a local class rather than a
1503        // nested class.
1504        const Scope *Parent = S->getParent();
1505        if (Parent->isTemplateParamScope())
1506          Parent = Parent->getParent();
1507        if (Parent->isClassScope())
1508          break;
1509      }
1510    }
1511  }
1512
1513  // Enter a scope for the class.
1514  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
1515
1516  // Note that we are parsing a new (potentially-nested) class definition.
1517  ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass);
1518
1519  if (TagDecl)
1520    Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1521
1522  if (Tok.is(tok::colon)) {
1523    ParseBaseClause(TagDecl);
1524
1525    if (!Tok.is(tok::l_brace)) {
1526      Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
1527
1528      if (TagDecl)
1529        Actions.ActOnTagDefinitionError(CurScope, TagDecl);
1530      return;
1531    }
1532  }
1533
1534  assert(Tok.is(tok::l_brace));
1535
1536  SourceLocation LBraceLoc = ConsumeBrace();
1537
1538  if (!TagDecl) {
1539    SkipUntil(tok::r_brace, false, false);
1540    return;
1541  }
1542
1543  Actions.ActOnStartCXXMemberDeclarations(CurScope, TagDecl, LBraceLoc);
1544
1545  // C++ 11p3: Members of a class defined with the keyword class are private
1546  // by default. Members of a class defined with the keywords struct or union
1547  // are public by default.
1548  AccessSpecifier CurAS;
1549  if (TagType == DeclSpec::TST_class)
1550    CurAS = AS_private;
1551  else
1552    CurAS = AS_public;
1553
1554  // While we still have something to read, read the member-declarations.
1555  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1556    // Each iteration of this loop reads one member-declaration.
1557
1558    // Check for extraneous top-level semicolon.
1559    if (Tok.is(tok::semi)) {
1560      Diag(Tok, diag::ext_extra_struct_semi)
1561        << FixItHint::CreateRemoval(Tok.getLocation());
1562      ConsumeToken();
1563      continue;
1564    }
1565
1566    AccessSpecifier AS = getAccessSpecifierIfPresent();
1567    if (AS != AS_none) {
1568      // Current token is a C++ access specifier.
1569      CurAS = AS;
1570      ConsumeToken();
1571      ExpectAndConsume(tok::colon, diag::err_expected_colon);
1572      continue;
1573    }
1574
1575    // FIXME: Make sure we don't have a template here.
1576
1577    // Parse all the comma separated declarators.
1578    ParseCXXClassMemberDeclaration(CurAS);
1579  }
1580
1581  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1582
1583  // If attributes exist after class contents, parse them.
1584  llvm::OwningPtr<AttributeList> AttrList;
1585  if (Tok.is(tok::kw___attribute))
1586    AttrList.reset(ParseGNUAttributes());
1587
1588  Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
1589                                            LBraceLoc, RBraceLoc,
1590                                            AttrList.get());
1591
1592  // C++ 9.2p2: Within the class member-specification, the class is regarded as
1593  // complete within function bodies, default arguments,
1594  // exception-specifications, and constructor ctor-initializers (including
1595  // such things in nested classes).
1596  //
1597  // FIXME: Only function bodies and constructor ctor-initializers are
1598  // parsed correctly, fix the rest.
1599  if (NonNestedClass) {
1600    // We are not inside a nested class. This class and its nested classes
1601    // are complete and we can parse the delayed portions of method
1602    // declarations and the lexed inline method definitions.
1603    ParseLexedMethodDeclarations(getCurrentClass());
1604    ParseLexedMethodDefs(getCurrentClass());
1605  }
1606
1607  Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1608
1609  // Leave the class scope.
1610  ParsingDef.Pop();
1611  ClassScope.Exit();
1612}
1613
1614/// ParseConstructorInitializer - Parse a C++ constructor initializer,
1615/// which explicitly initializes the members or base classes of a
1616/// class (C++ [class.base.init]). For example, the three initializers
1617/// after the ':' in the Derived constructor below:
1618///
1619/// @code
1620/// class Base { };
1621/// class Derived : Base {
1622///   int x;
1623///   float f;
1624/// public:
1625///   Derived(float f) : Base(), x(17), f(f) { }
1626/// };
1627/// @endcode
1628///
1629/// [C++]  ctor-initializer:
1630///          ':' mem-initializer-list
1631///
1632/// [C++]  mem-initializer-list:
1633///          mem-initializer
1634///          mem-initializer , mem-initializer-list
1635void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) {
1636  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
1637
1638  SourceLocation ColonLoc = ConsumeToken();
1639
1640  llvm::SmallVector<MemInitTy*, 4> MemInitializers;
1641  bool AnyErrors = false;
1642
1643  do {
1644    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
1645    if (!MemInit.isInvalid())
1646      MemInitializers.push_back(MemInit.get());
1647    else
1648      AnyErrors = true;
1649
1650    if (Tok.is(tok::comma))
1651      ConsumeToken();
1652    else if (Tok.is(tok::l_brace))
1653      break;
1654    else {
1655      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1656      Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
1657      SkipUntil(tok::l_brace, true, true);
1658      break;
1659    }
1660  } while (true);
1661
1662  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
1663                               MemInitializers.data(), MemInitializers.size(),
1664                               AnyErrors);
1665}
1666
1667/// ParseMemInitializer - Parse a C++ member initializer, which is
1668/// part of a constructor initializer that explicitly initializes one
1669/// member or base class (C++ [class.base.init]). See
1670/// ParseConstructorInitializer for an example.
1671///
1672/// [C++] mem-initializer:
1673///         mem-initializer-id '(' expression-list[opt] ')'
1674///
1675/// [C++] mem-initializer-id:
1676///         '::'[opt] nested-name-specifier[opt] class-name
1677///         identifier
1678Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) {
1679  // parse '::'[opt] nested-name-specifier[opt]
1680  CXXScopeSpec SS;
1681  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
1682  TypeTy *TemplateTypeTy = 0;
1683  if (Tok.is(tok::annot_template_id)) {
1684    TemplateIdAnnotation *TemplateId
1685      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1686    if (TemplateId->Kind == TNK_Type_template ||
1687        TemplateId->Kind == TNK_Dependent_template_name) {
1688      AnnotateTemplateIdTokenAsType(&SS);
1689      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1690      TemplateTypeTy = Tok.getAnnotationValue();
1691    }
1692  }
1693  if (!TemplateTypeTy && Tok.isNot(tok::identifier)) {
1694    Diag(Tok, diag::err_expected_member_or_base_name);
1695    return true;
1696  }
1697
1698  // Get the identifier. This may be a member name or a class name,
1699  // but we'll let the semantic analysis determine which it is.
1700  IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0;
1701  SourceLocation IdLoc = ConsumeToken();
1702
1703  // Parse the '('.
1704  if (Tok.isNot(tok::l_paren)) {
1705    Diag(Tok, diag::err_expected_lparen);
1706    return true;
1707  }
1708  SourceLocation LParenLoc = ConsumeParen();
1709
1710  // Parse the optional expression-list.
1711  ExprVector ArgExprs(Actions);
1712  CommaLocsTy CommaLocs;
1713  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
1714    SkipUntil(tok::r_paren);
1715    return true;
1716  }
1717
1718  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1719
1720  return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, SS, II,
1721                                     TemplateTypeTy, IdLoc,
1722                                     LParenLoc, ArgExprs.take(),
1723                                     ArgExprs.size(), CommaLocs.data(),
1724                                     RParenLoc);
1725}
1726
1727/// ParseExceptionSpecification - Parse a C++ exception-specification
1728/// (C++ [except.spec]).
1729///
1730///       exception-specification:
1731///         'throw' '(' type-id-list [opt] ')'
1732/// [MS]    'throw' '(' '...' ')'
1733///
1734///       type-id-list:
1735///         type-id
1736///         type-id-list ',' type-id
1737///
1738bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc,
1739                                         llvm::SmallVector<TypeTy*, 2>
1740                                             &Exceptions,
1741                                         llvm::SmallVector<SourceRange, 2>
1742                                             &Ranges,
1743                                         bool &hasAnyExceptionSpec) {
1744  assert(Tok.is(tok::kw_throw) && "expected throw");
1745
1746  SourceLocation ThrowLoc = ConsumeToken();
1747
1748  if (!Tok.is(tok::l_paren)) {
1749    return Diag(Tok, diag::err_expected_lparen_after) << "throw";
1750  }
1751  SourceLocation LParenLoc = ConsumeParen();
1752
1753  // Parse throw(...), a Microsoft extension that means "this function
1754  // can throw anything".
1755  if (Tok.is(tok::ellipsis)) {
1756    hasAnyExceptionSpec = true;
1757    SourceLocation EllipsisLoc = ConsumeToken();
1758    if (!getLang().Microsoft)
1759      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
1760    EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1761    return false;
1762  }
1763
1764  // Parse the sequence of type-ids.
1765  SourceRange Range;
1766  while (Tok.isNot(tok::r_paren)) {
1767    TypeResult Res(ParseTypeName(&Range));
1768    if (!Res.isInvalid()) {
1769      Exceptions.push_back(Res.get());
1770      Ranges.push_back(Range);
1771    }
1772    if (Tok.is(tok::comma))
1773      ConsumeToken();
1774    else
1775      break;
1776  }
1777
1778  EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1779  return false;
1780}
1781
1782/// \brief We have just started parsing the definition of a new class,
1783/// so push that class onto our stack of classes that is currently
1784/// being parsed.
1785void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool NonNestedClass) {
1786  assert((NonNestedClass || !ClassStack.empty()) &&
1787         "Nested class without outer class");
1788  ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass));
1789}
1790
1791/// \brief Deallocate the given parsed class and all of its nested
1792/// classes.
1793void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
1794  for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I)
1795    DeallocateParsedClasses(Class->NestedClasses[I]);
1796  delete Class;
1797}
1798
1799/// \brief Pop the top class of the stack of classes that are
1800/// currently being parsed.
1801///
1802/// This routine should be called when we have finished parsing the
1803/// definition of a class, but have not yet popped the Scope
1804/// associated with the class's definition.
1805///
1806/// \returns true if the class we've popped is a top-level class,
1807/// false otherwise.
1808void Parser::PopParsingClass() {
1809  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
1810
1811  ParsingClass *Victim = ClassStack.top();
1812  ClassStack.pop();
1813  if (Victim->TopLevelClass) {
1814    // Deallocate all of the nested classes of this class,
1815    // recursively: we don't need to keep any of this information.
1816    DeallocateParsedClasses(Victim);
1817    return;
1818  }
1819  assert(!ClassStack.empty() && "Missing top-level class?");
1820
1821  if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() &&
1822      Victim->NestedClasses.empty()) {
1823    // The victim is a nested class, but we will not need to perform
1824    // any processing after the definition of this class since it has
1825    // no members whose handling was delayed. Therefore, we can just
1826    // remove this nested class.
1827    delete Victim;
1828    return;
1829  }
1830
1831  // This nested class has some members that will need to be processed
1832  // after the top-level class is completely defined. Therefore, add
1833  // it to the list of nested classes within its parent.
1834  assert(CurScope->isClassScope() && "Nested class outside of class scope?");
1835  ClassStack.top()->NestedClasses.push_back(Victim);
1836  Victim->TemplateScope = CurScope->getParent()->isTemplateParamScope();
1837}
1838
1839/// ParseCXX0XAttributes - Parse a C++0x attribute-specifier. Currently only
1840/// parses standard attributes.
1841///
1842/// [C++0x] attribute-specifier:
1843///         '[' '[' attribute-list ']' ']'
1844///
1845/// [C++0x] attribute-list:
1846///         attribute[opt]
1847///         attribute-list ',' attribute[opt]
1848///
1849/// [C++0x] attribute:
1850///         attribute-token attribute-argument-clause[opt]
1851///
1852/// [C++0x] attribute-token:
1853///         identifier
1854///         attribute-scoped-token
1855///
1856/// [C++0x] attribute-scoped-token:
1857///         attribute-namespace '::' identifier
1858///
1859/// [C++0x] attribute-namespace:
1860///         identifier
1861///
1862/// [C++0x] attribute-argument-clause:
1863///         '(' balanced-token-seq ')'
1864///
1865/// [C++0x] balanced-token-seq:
1866///         balanced-token
1867///         balanced-token-seq balanced-token
1868///
1869/// [C++0x] balanced-token:
1870///         '(' balanced-token-seq ')'
1871///         '[' balanced-token-seq ']'
1872///         '{' balanced-token-seq '}'
1873///         any token but '(', ')', '[', ']', '{', or '}'
1874CXX0XAttributeList Parser::ParseCXX0XAttributes(SourceLocation *EndLoc) {
1875  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
1876      && "Not a C++0x attribute list");
1877
1878  SourceLocation StartLoc = Tok.getLocation(), Loc;
1879  AttributeList *CurrAttr = 0;
1880
1881  ConsumeBracket();
1882  ConsumeBracket();
1883
1884  if (Tok.is(tok::comma)) {
1885    Diag(Tok.getLocation(), diag::err_expected_ident);
1886    ConsumeToken();
1887  }
1888
1889  while (Tok.is(tok::identifier) || Tok.is(tok::comma)) {
1890    // attribute not present
1891    if (Tok.is(tok::comma)) {
1892      ConsumeToken();
1893      continue;
1894    }
1895
1896    IdentifierInfo *ScopeName = 0, *AttrName = Tok.getIdentifierInfo();
1897    SourceLocation ScopeLoc, AttrLoc = ConsumeToken();
1898
1899    // scoped attribute
1900    if (Tok.is(tok::coloncolon)) {
1901      ConsumeToken();
1902
1903      if (!Tok.is(tok::identifier)) {
1904        Diag(Tok.getLocation(), diag::err_expected_ident);
1905        SkipUntil(tok::r_square, tok::comma, true, true);
1906        continue;
1907      }
1908
1909      ScopeName = AttrName;
1910      ScopeLoc = AttrLoc;
1911
1912      AttrName = Tok.getIdentifierInfo();
1913      AttrLoc = ConsumeToken();
1914    }
1915
1916    bool AttrParsed = false;
1917    // No scoped names are supported; ideally we could put all non-standard
1918    // attributes into namespaces.
1919    if (!ScopeName) {
1920      switch(AttributeList::getKind(AttrName))
1921      {
1922      // No arguments
1923      case AttributeList::AT_base_check:
1924      case AttributeList::AT_carries_dependency:
1925      case AttributeList::AT_final:
1926      case AttributeList::AT_hiding:
1927      case AttributeList::AT_noreturn:
1928      case AttributeList::AT_override: {
1929        if (Tok.is(tok::l_paren)) {
1930          Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_arguments)
1931            << AttrName->getName();
1932          break;
1933        }
1934
1935        CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc, 0,
1936                                     SourceLocation(), 0, 0, CurrAttr, false,
1937                                     true);
1938        AttrParsed = true;
1939        break;
1940      }
1941
1942      // One argument; must be a type-id or assignment-expression
1943      case AttributeList::AT_aligned: {
1944        if (Tok.isNot(tok::l_paren)) {
1945          Diag(Tok.getLocation(), diag::err_cxx0x_attribute_requires_arguments)
1946            << AttrName->getName();
1947          break;
1948        }
1949        SourceLocation ParamLoc = ConsumeParen();
1950
1951        OwningExprResult ArgExpr = ParseCXX0XAlignArgument(ParamLoc);
1952
1953        MatchRHSPunctuation(tok::r_paren, ParamLoc);
1954
1955        ExprVector ArgExprs(Actions);
1956        ArgExprs.push_back(ArgExpr.release());
1957        CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc,
1958                                     0, ParamLoc, ArgExprs.take(), 1, CurrAttr,
1959                                     false, true);
1960
1961        AttrParsed = true;
1962        break;
1963      }
1964
1965      // Silence warnings
1966      default: break;
1967      }
1968    }
1969
1970    // Skip the entire parameter clause, if any
1971    if (!AttrParsed && Tok.is(tok::l_paren)) {
1972      ConsumeParen();
1973      // SkipUntil maintains the balancedness of tokens.
1974      SkipUntil(tok::r_paren, false);
1975    }
1976  }
1977
1978  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
1979    SkipUntil(tok::r_square, false);
1980  Loc = Tok.getLocation();
1981  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
1982    SkipUntil(tok::r_square, false);
1983
1984  CXX0XAttributeList Attr (CurrAttr, SourceRange(StartLoc, Loc), true);
1985  return Attr;
1986}
1987
1988/// ParseCXX0XAlignArgument - Parse the argument to C++0x's [[align]]
1989/// attribute.
1990///
1991/// FIXME: Simply returns an alignof() expression if the argument is a
1992/// type. Ideally, the type should be propagated directly into Sema.
1993///
1994/// [C++0x] 'align' '(' type-id ')'
1995/// [C++0x] 'align' '(' assignment-expression ')'
1996Parser::OwningExprResult Parser::ParseCXX0XAlignArgument(SourceLocation Start) {
1997  if (isTypeIdInParens()) {
1998    EnterExpressionEvaluationContext Unevaluated(Actions,
1999                                                  Action::Unevaluated);
2000    SourceLocation TypeLoc = Tok.getLocation();
2001    TypeTy *Ty = ParseTypeName().get();
2002    SourceRange TypeRange(Start, Tok.getLocation());
2003    return Actions.ActOnSizeOfAlignOfExpr(TypeLoc, false, true, Ty,
2004                                              TypeRange);
2005  } else
2006    return ParseConstantExpression();
2007}
2008