ParseDeclCXX.cpp revision 72b505b7904b3c9320a1312998800ba76e4f5841
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/Parse/Parser.h"
15#include "clang/Basic/Diagnostic.h"
16#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
18#include "AstGuard.h"
19using namespace clang;
20
21/// ParseNamespace - We know that the current token is a namespace keyword. This
22/// may either be a top level namespace or a block-level namespace alias.
23///
24///       namespace-definition: [C++ 7.3: basic.namespace]
25///         named-namespace-definition
26///         unnamed-namespace-definition
27///
28///       unnamed-namespace-definition:
29///         'namespace' attributes[opt] '{' namespace-body '}'
30///
31///       named-namespace-definition:
32///         original-namespace-definition
33///         extension-namespace-definition
34///
35///       original-namespace-definition:
36///         'namespace' identifier attributes[opt] '{' namespace-body '}'
37///
38///       extension-namespace-definition:
39///         'namespace' original-namespace-name '{' namespace-body '}'
40///
41///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
42///         'namespace' identifier '=' qualified-namespace-specifier ';'
43///
44Parser::DeclTy *Parser::ParseNamespace(unsigned Context) {
45  assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
46  SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
47
48  SourceLocation IdentLoc;
49  IdentifierInfo *Ident = 0;
50
51  if (Tok.is(tok::identifier)) {
52    Ident = Tok.getIdentifierInfo();
53    IdentLoc = ConsumeToken();  // eat the identifier.
54  }
55
56  // Read label attributes, if present.
57  DeclTy *AttrList = 0;
58  if (Tok.is(tok::kw___attribute))
59    // FIXME: save these somewhere.
60    AttrList = ParseAttributes();
61
62  if (Tok.is(tok::equal)) {
63    // FIXME: Verify no attributes were present.
64    // FIXME: parse this.
65  } else if (Tok.is(tok::l_brace)) {
66
67    SourceLocation LBrace = ConsumeBrace();
68
69    // Enter a scope for the namespace.
70    ParseScope NamespaceScope(this, Scope::DeclScope);
71
72    DeclTy *NamespcDecl =
73      Actions.ActOnStartNamespaceDef(CurScope, IdentLoc, Ident, LBrace);
74
75    while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof))
76      ParseExternalDeclaration();
77
78    // Leave the namespace scope.
79    NamespaceScope.Exit();
80
81    SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
82    Actions.ActOnFinishNamespaceDef(NamespcDecl, RBrace);
83
84    return NamespcDecl;
85
86  } else {
87    Diag(Tok, Ident ? diag::err_expected_lbrace :
88                      diag::err_expected_ident_lbrace);
89  }
90
91  return 0;
92}
93
94/// ParseLinkage - We know that the current token is a string_literal
95/// and just before that, that extern was seen.
96///
97///       linkage-specification: [C++ 7.5p2: dcl.link]
98///         'extern' string-literal '{' declaration-seq[opt] '}'
99///         'extern' string-literal declaration
100///
101Parser::DeclTy *Parser::ParseLinkage(unsigned Context) {
102  assert(Tok.is(tok::string_literal) && "Not a string literal!");
103  llvm::SmallVector<char, 8> LangBuffer;
104  // LangBuffer is guaranteed to be big enough.
105  LangBuffer.resize(Tok.getLength());
106  const char *LangBufPtr = &LangBuffer[0];
107  unsigned StrSize = PP.getSpelling(Tok, LangBufPtr);
108
109  SourceLocation Loc = ConsumeStringToken();
110  DeclTy *D = 0;
111  SourceLocation LBrace, RBrace;
112
113  if (Tok.isNot(tok::l_brace)) {
114    D = ParseDeclarationOrFunctionDefinition();
115  } else {
116    LBrace = ConsumeBrace();
117    while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
118      // FIXME capture the decls.
119      D = ParseExternalDeclaration();
120    }
121
122    RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
123  }
124
125  if (!D)
126    return 0;
127
128  return Actions.ActOnLinkageSpec(Loc, LBrace, RBrace, LangBufPtr, StrSize, D);
129}
130
131/// ParseClassName - Parse a C++ class-name, which names a class. Note
132/// that we only check that the result names a type; semantic analysis
133/// will need to verify that the type names a class. The result is
134/// either a type or NULL, dependending on whether a type name was
135/// found.
136///
137///       class-name: [C++ 9.1]
138///         identifier
139///         template-id   [TODO]
140///
141Parser::TypeTy *Parser::ParseClassName(const CXXScopeSpec *SS) {
142  // Parse the class-name.
143  // FIXME: Alternatively, parse a simple-template-id.
144  if (Tok.isNot(tok::identifier)) {
145    Diag(Tok, diag::err_expected_class_name);
146    return 0;
147  }
148
149  // We have an identifier; check whether it is actually a type.
150  TypeTy *Type = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope, SS);
151  if (!Type) {
152    Diag(Tok, diag::err_expected_class_name);
153    return 0;
154  }
155
156  // Consume the identifier.
157  ConsumeToken();
158
159  return Type;
160}
161
162/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
163/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
164/// until we reach the start of a definition or see a token that
165/// cannot start a definition.
166///
167///       class-specifier: [C++ class]
168///         class-head '{' member-specification[opt] '}'
169///         class-head '{' member-specification[opt] '}' attributes[opt]
170///       class-head:
171///         class-key identifier[opt] base-clause[opt]
172///         class-key nested-name-specifier identifier base-clause[opt]
173///         class-key nested-name-specifier[opt] simple-template-id
174///                          base-clause[opt]
175/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
176/// [GNU]   class-key attributes[opt] nested-name-specifier
177///                          identifier base-clause[opt]
178/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
179///                          simple-template-id base-clause[opt]
180///       class-key:
181///         'class'
182///         'struct'
183///         'union'
184///
185///       elaborated-type-specifier: [C++ dcl.type.elab]
186///         class-key ::[opt] nested-name-specifier[opt] identifier
187///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
188///                          simple-template-id
189///
190///  Note that the C++ class-specifier and elaborated-type-specifier,
191///  together, subsume the C99 struct-or-union-specifier:
192///
193///       struct-or-union-specifier: [C99 6.7.2.1]
194///         struct-or-union identifier[opt] '{' struct-contents '}'
195///         struct-or-union identifier
196/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
197///                                                         '}' attributes[opt]
198/// [GNU]   struct-or-union attributes[opt] identifier
199///       struct-or-union:
200///         'struct'
201///         'union'
202void Parser::ParseClassSpecifier(DeclSpec &DS) {
203  assert((Tok.is(tok::kw_class) ||
204          Tok.is(tok::kw_struct) ||
205          Tok.is(tok::kw_union)) &&
206         "Not a class specifier");
207  DeclSpec::TST TagType =
208    Tok.is(tok::kw_class) ? DeclSpec::TST_class :
209    Tok.is(tok::kw_struct) ? DeclSpec::TST_struct :
210    DeclSpec::TST_union;
211
212  SourceLocation StartLoc = ConsumeToken();
213
214  AttributeList *Attr = 0;
215  // If attributes exist after tag, parse them.
216  if (Tok.is(tok::kw___attribute))
217    Attr = ParseAttributes();
218
219  // Parse the (optional) nested-name-specifier.
220  CXXScopeSpec SS;
221  if (getLang().CPlusPlus && MaybeParseCXXScopeSpecifier(SS)) {
222    if (Tok.isNot(tok::identifier))
223      Diag(Tok, diag::err_expected_ident);
224  }
225
226  // Parse the (optional) class name.
227  // FIXME: Alternatively, parse a simple-template-id.
228  IdentifierInfo *Name = 0;
229  SourceLocation NameLoc;
230  if (Tok.is(tok::identifier)) {
231    Name = Tok.getIdentifierInfo();
232    NameLoc = ConsumeToken();
233  }
234
235  // There are three options here.  If we have 'struct foo;', then
236  // this is a forward declaration.  If we have 'struct foo {...' or
237  // 'struct fo :...' then this is a definition. Otherwise we have
238  // something like 'struct foo xyz', a reference.
239  Action::TagKind TK;
240  if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon)))
241    TK = Action::TK_Definition;
242  else if (Tok.is(tok::semi))
243    TK = Action::TK_Declaration;
244  else
245    TK = Action::TK_Reference;
246
247  if (!Name && TK != Action::TK_Definition) {
248    // We have a declaration or reference to an anonymous class.
249    Diag(StartLoc, diag::err_anon_type_definition)
250      << DeclSpec::getSpecifierName(TagType);
251
252    // Skip the rest of this declarator, up until the comma or semicolon.
253    SkipUntil(tok::comma, true);
254    return;
255  }
256
257  // Parse the tag portion of this.
258  DeclTy *TagDecl = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, SS, Name,
259                                     NameLoc, Attr);
260
261  // Parse the optional base clause (C++ only).
262  if (getLang().CPlusPlus && Tok.is(tok::colon)) {
263    ParseBaseClause(TagDecl);
264  }
265
266  // If there is a body, parse it and inform the actions module.
267  if (Tok.is(tok::l_brace))
268    if (getLang().CPlusPlus)
269      ParseCXXMemberSpecification(StartLoc, TagType, TagDecl);
270    else
271      ParseStructUnionBody(StartLoc, TagType, TagDecl);
272  else if (TK == Action::TK_Definition) {
273    // FIXME: Complain that we have a base-specifier list but no
274    // definition.
275    Diag(Tok, diag::err_expected_lbrace);
276  }
277
278  const char *PrevSpec = 0;
279  if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagDecl))
280    Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
281}
282
283/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
284///
285///       base-clause : [C++ class.derived]
286///         ':' base-specifier-list
287///       base-specifier-list:
288///         base-specifier '...'[opt]
289///         base-specifier-list ',' base-specifier '...'[opt]
290void Parser::ParseBaseClause(DeclTy *ClassDecl)
291{
292  assert(Tok.is(tok::colon) && "Not a base clause");
293  ConsumeToken();
294
295  // Build up an array of parsed base specifiers.
296  llvm::SmallVector<BaseTy *, 8> BaseInfo;
297
298  while (true) {
299    // Parse a base-specifier.
300    BaseResult Result = ParseBaseSpecifier(ClassDecl);
301    if (Result.isInvalid) {
302      // Skip the rest of this base specifier, up until the comma or
303      // opening brace.
304      SkipUntil(tok::comma, tok::l_brace, true, true);
305    } else {
306      // Add this to our array of base specifiers.
307      BaseInfo.push_back(Result.Val);
308    }
309
310    // If the next token is a comma, consume it and keep reading
311    // base-specifiers.
312    if (Tok.isNot(tok::comma)) break;
313
314    // Consume the comma.
315    ConsumeToken();
316  }
317
318  // Attach the base specifiers
319  Actions.ActOnBaseSpecifiers(ClassDecl, &BaseInfo[0], BaseInfo.size());
320}
321
322/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
323/// one entry in the base class list of a class specifier, for example:
324///    class foo : public bar, virtual private baz {
325/// 'public bar' and 'virtual private baz' are each base-specifiers.
326///
327///       base-specifier: [C++ class.derived]
328///         ::[opt] nested-name-specifier[opt] class-name
329///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
330///                        class-name
331///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
332///                        class-name
333Parser::BaseResult Parser::ParseBaseSpecifier(DeclTy *ClassDecl)
334{
335  bool IsVirtual = false;
336  SourceLocation StartLoc = Tok.getLocation();
337
338  // Parse the 'virtual' keyword.
339  if (Tok.is(tok::kw_virtual))  {
340    ConsumeToken();
341    IsVirtual = true;
342  }
343
344  // Parse an (optional) access specifier.
345  AccessSpecifier Access = getAccessSpecifierIfPresent();
346  if (Access)
347    ConsumeToken();
348
349  // Parse the 'virtual' keyword (again!), in case it came after the
350  // access specifier.
351  if (Tok.is(tok::kw_virtual))  {
352    SourceLocation VirtualLoc = ConsumeToken();
353    if (IsVirtual) {
354      // Complain about duplicate 'virtual'
355      Diag(VirtualLoc, diag::err_dup_virtual)
356        << SourceRange(VirtualLoc, VirtualLoc);
357    }
358
359    IsVirtual = true;
360  }
361
362  // Parse optional '::' and optional nested-name-specifier.
363  CXXScopeSpec SS;
364  MaybeParseCXXScopeSpecifier(SS);
365
366  // The location of the base class itself.
367  SourceLocation BaseLoc = Tok.getLocation();
368
369  // Parse the class-name.
370  TypeTy *BaseType = ParseClassName(&SS);
371  if (!BaseType)
372    return true;
373
374  // Find the complete source range for the base-specifier.
375  SourceRange Range(StartLoc, BaseLoc);
376
377  // Notify semantic analysis that we have parsed a complete
378  // base-specifier.
379  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
380                                    BaseType, BaseLoc);
381}
382
383/// getAccessSpecifierIfPresent - Determine whether the next token is
384/// a C++ access-specifier.
385///
386///       access-specifier: [C++ class.derived]
387///         'private'
388///         'protected'
389///         'public'
390AccessSpecifier Parser::getAccessSpecifierIfPresent() const
391{
392  switch (Tok.getKind()) {
393  default: return AS_none;
394  case tok::kw_private: return AS_private;
395  case tok::kw_protected: return AS_protected;
396  case tok::kw_public: return AS_public;
397  }
398}
399
400/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
401///
402///       member-declaration:
403///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
404///         function-definition ';'[opt]
405///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
406///         using-declaration                                            [TODO]
407/// [C++0x] static_assert-declaration                                    [TODO]
408///         template-declaration                                         [TODO]
409///
410///       member-declarator-list:
411///         member-declarator
412///         member-declarator-list ',' member-declarator
413///
414///       member-declarator:
415///         declarator pure-specifier[opt]
416///         declarator constant-initializer[opt]
417///         identifier[opt] ':' constant-expression
418///
419///       pure-specifier:   [TODO]
420///         '= 0'
421///
422///       constant-initializer:
423///         '=' constant-expression
424///
425Parser::DeclTy *Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) {
426  SourceLocation DSStart = Tok.getLocation();
427  // decl-specifier-seq:
428  // Parse the common declaration-specifiers piece.
429  DeclSpec DS;
430  ParseDeclarationSpecifiers(DS);
431
432  if (Tok.is(tok::semi)) {
433    ConsumeToken();
434    // C++ 9.2p7: The member-declarator-list can be omitted only after a
435    // class-specifier or an enum-specifier or in a friend declaration.
436    // FIXME: Friend declarations.
437    switch (DS.getTypeSpecType()) {
438      case DeclSpec::TST_struct:
439      case DeclSpec::TST_union:
440      case DeclSpec::TST_class:
441      case DeclSpec::TST_enum:
442        return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
443      default:
444        Diag(DSStart, diag::err_no_declarators);
445        return 0;
446    }
447  }
448
449  Declarator DeclaratorInfo(DS, Declarator::MemberContext);
450
451  if (Tok.isNot(tok::colon)) {
452    // Parse the first declarator.
453    ParseDeclarator(DeclaratorInfo);
454    // Error parsing the declarator?
455    if (!DeclaratorInfo.hasName()) {
456      // If so, skip until the semi-colon or a }.
457      SkipUntil(tok::r_brace, true);
458      if (Tok.is(tok::semi))
459        ConsumeToken();
460      return 0;
461    }
462
463    // function-definition:
464    if (Tok.is(tok::l_brace)
465        || (DeclaratorInfo.isFunctionDeclarator() && Tok.is(tok::colon))) {
466      if (!DeclaratorInfo.isFunctionDeclarator()) {
467        Diag(Tok, diag::err_func_def_no_params);
468        ConsumeBrace();
469        SkipUntil(tok::r_brace, true);
470        return 0;
471      }
472
473      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
474        Diag(Tok, diag::err_function_declared_typedef);
475        // This recovery skips the entire function body. It would be nice
476        // to simply call ParseCXXInlineMethodDef() below, however Sema
477        // assumes the declarator represents a function, not a typedef.
478        ConsumeBrace();
479        SkipUntil(tok::r_brace, true);
480        return 0;
481      }
482
483      return ParseCXXInlineMethodDef(AS, DeclaratorInfo);
484    }
485  }
486
487  // member-declarator-list:
488  //   member-declarator
489  //   member-declarator-list ',' member-declarator
490
491  DeclTy *LastDeclInGroup = 0;
492  OwningExprResult BitfieldSize(Actions);
493  OwningExprResult Init(Actions);
494
495  while (1) {
496
497    // member-declarator:
498    //   declarator pure-specifier[opt]
499    //   declarator constant-initializer[opt]
500    //   identifier[opt] ':' constant-expression
501
502    if (Tok.is(tok::colon)) {
503      ConsumeToken();
504      BitfieldSize = ParseConstantExpression();
505      if (BitfieldSize.isInvalid())
506        SkipUntil(tok::comma, true, true);
507    }
508
509    // pure-specifier:
510    //   '= 0'
511    //
512    // constant-initializer:
513    //   '=' constant-expression
514
515    if (Tok.is(tok::equal)) {
516      ConsumeToken();
517      Init = ParseInitializer();
518      if (Init.isInvalid())
519        SkipUntil(tok::comma, true, true);
520    }
521
522    // If attributes exist after the declarator, parse them.
523    if (Tok.is(tok::kw___attribute))
524      DeclaratorInfo.AddAttributes(ParseAttributes());
525
526    // NOTE: If Sema is the Action module and declarator is an instance field,
527    // this call will *not* return the created decl; LastDeclInGroup will be
528    // returned instead.
529    // See Sema::ActOnCXXMemberDeclarator for details.
530    LastDeclInGroup = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
531                                                       DeclaratorInfo,
532                                                       BitfieldSize.release(),
533                                                       Init.release(),
534                                                       LastDeclInGroup);
535
536    if (DeclaratorInfo.isFunctionDeclarator() &&
537        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
538          != DeclSpec::SCS_typedef) {
539      // We just declared a member function. If this member function
540      // has any default arguments, we'll need to parse them later.
541      LateParsedMethodDeclaration *LateMethod = 0;
542      DeclaratorChunk::FunctionTypeInfo &FTI
543        = DeclaratorInfo.getTypeObject(0).Fun;
544      for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
545        if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
546          if (!LateMethod) {
547            // Push this method onto the stack of late-parsed method
548            // declarations.
549            getCurTopClassStack().MethodDecls.push_back(
550                                   LateParsedMethodDeclaration(LastDeclInGroup));
551            LateMethod = &getCurTopClassStack().MethodDecls.back();
552
553            // Add all of the parameters prior to this one (they don't
554            // have default arguments).
555            LateMethod->DefaultArgs.reserve(FTI.NumArgs);
556            for (unsigned I = 0; I < ParamIdx; ++I)
557              LateMethod->DefaultArgs.push_back(
558                        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param));
559          }
560
561          // Add this parameter to the list of parameters (it or may
562          // not have a default argument).
563          LateMethod->DefaultArgs.push_back(
564            LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
565                                      FTI.ArgInfo[ParamIdx].DefaultArgTokens));
566        }
567      }
568    }
569
570    // If we don't have a comma, it is either the end of the list (a ';')
571    // or an error, bail out.
572    if (Tok.isNot(tok::comma))
573      break;
574
575    // Consume the comma.
576    ConsumeToken();
577
578    // Parse the next declarator.
579    DeclaratorInfo.clear();
580    BitfieldSize = 0;
581    Init = 0;
582
583    // Attributes are only allowed on the second declarator.
584    if (Tok.is(tok::kw___attribute))
585      DeclaratorInfo.AddAttributes(ParseAttributes());
586
587    if (Tok.isNot(tok::colon))
588      ParseDeclarator(DeclaratorInfo);
589  }
590
591  if (Tok.is(tok::semi)) {
592    ConsumeToken();
593    // Reverse the chain list.
594    return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
595  }
596
597  Diag(Tok, diag::err_expected_semi_decl_list);
598  // Skip to end of block or statement
599  SkipUntil(tok::r_brace, true, true);
600  if (Tok.is(tok::semi))
601    ConsumeToken();
602  return 0;
603}
604
605/// ParseCXXMemberSpecification - Parse the class definition.
606///
607///       member-specification:
608///         member-declaration member-specification[opt]
609///         access-specifier ':' member-specification[opt]
610///
611void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
612                                         unsigned TagType, DeclTy *TagDecl) {
613  assert((TagType == DeclSpec::TST_struct ||
614         TagType == DeclSpec::TST_union  ||
615         TagType == DeclSpec::TST_class) && "Invalid TagType!");
616
617  SourceLocation LBraceLoc = ConsumeBrace();
618
619  if (!CurScope->isCXXClassScope() && // Not about to define a nested class.
620      CurScope->isInCXXInlineMethodScope()) {
621    // We will define a local class of an inline method.
622    // Push a new LexedMethodsForTopClass for its inline methods.
623    PushTopClassStack();
624  }
625
626  // Enter a scope for the class.
627  ParseScope ClassScope(this, Scope::CXXClassScope|Scope::DeclScope);
628
629  Actions.ActOnStartCXXClassDef(CurScope, TagDecl, LBraceLoc);
630
631  // C++ 11p3: Members of a class defined with the keyword class are private
632  // by default. Members of a class defined with the keywords struct or union
633  // are public by default.
634  AccessSpecifier CurAS;
635  if (TagType == DeclSpec::TST_class)
636    CurAS = AS_private;
637  else
638    CurAS = AS_public;
639
640  // While we still have something to read, read the member-declarations.
641  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
642    // Each iteration of this loop reads one member-declaration.
643
644    // Check for extraneous top-level semicolon.
645    if (Tok.is(tok::semi)) {
646      Diag(Tok, diag::ext_extra_struct_semi);
647      ConsumeToken();
648      continue;
649    }
650
651    AccessSpecifier AS = getAccessSpecifierIfPresent();
652    if (AS != AS_none) {
653      // Current token is a C++ access specifier.
654      CurAS = AS;
655      ConsumeToken();
656      ExpectAndConsume(tok::colon, diag::err_expected_colon);
657      continue;
658    }
659
660    // Parse all the comma separated declarators.
661    ParseCXXClassMemberDeclaration(CurAS);
662  }
663
664  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
665
666  AttributeList *AttrList = 0;
667  // If attributes exist after class contents, parse them.
668  if (Tok.is(tok::kw___attribute))
669    AttrList = ParseAttributes(); // FIXME: where should I put them?
670
671  Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
672                                            LBraceLoc, RBraceLoc);
673
674  // C++ 9.2p2: Within the class member-specification, the class is regarded as
675  // complete within function bodies, default arguments,
676  // exception-specifications, and constructor ctor-initializers (including
677  // such things in nested classes).
678  //
679  // FIXME: Only function bodies and constructor ctor-initializers are
680  // parsed correctly, fix the rest.
681  if (!CurScope->getParent()->isCXXClassScope()) {
682    // We are not inside a nested class. This class and its nested classes
683    // are complete and we can parse the delayed portions of method
684    // declarations and the lexed inline method definitions.
685    ParseLexedMethodDeclarations();
686    ParseLexedMethodDefs();
687
688    // For a local class of inline method, pop the LexedMethodsForTopClass that
689    // was previously pushed.
690
691    assert((CurScope->isInCXXInlineMethodScope() ||
692           TopClassStacks.size() == 1) &&
693           "MethodLexers not getting popped properly!");
694    if (CurScope->isInCXXInlineMethodScope())
695      PopTopClassStack();
696  }
697
698  // Leave the class scope.
699  ClassScope.Exit();
700
701  Actions.ActOnFinishCXXClassDef(TagDecl);
702}
703
704/// ParseConstructorInitializer - Parse a C++ constructor initializer,
705/// which explicitly initializes the members or base classes of a
706/// class (C++ [class.base.init]). For example, the three initializers
707/// after the ':' in the Derived constructor below:
708///
709/// @code
710/// class Base { };
711/// class Derived : Base {
712///   int x;
713///   float f;
714/// public:
715///   Derived(float f) : Base(), x(17), f(f) { }
716/// };
717/// @endcode
718///
719/// [C++]  ctor-initializer:
720///          ':' mem-initializer-list
721///
722/// [C++]  mem-initializer-list:
723///          mem-initializer
724///          mem-initializer , mem-initializer-list
725void Parser::ParseConstructorInitializer(DeclTy *ConstructorDecl) {
726  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
727
728  SourceLocation ColonLoc = ConsumeToken();
729
730  llvm::SmallVector<MemInitTy*, 4> MemInitializers;
731
732  do {
733    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
734    if (!MemInit.isInvalid)
735      MemInitializers.push_back(MemInit.Val);
736
737    if (Tok.is(tok::comma))
738      ConsumeToken();
739    else if (Tok.is(tok::l_brace))
740      break;
741    else {
742      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
743      SkipUntil(tok::l_brace, true, true);
744      break;
745    }
746  } while (true);
747
748  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
749                               &MemInitializers[0], MemInitializers.size());
750}
751
752/// ParseMemInitializer - Parse a C++ member initializer, which is
753/// part of a constructor initializer that explicitly initializes one
754/// member or base class (C++ [class.base.init]). See
755/// ParseConstructorInitializer for an example.
756///
757/// [C++] mem-initializer:
758///         mem-initializer-id '(' expression-list[opt] ')'
759///
760/// [C++] mem-initializer-id:
761///         '::'[opt] nested-name-specifier[opt] class-name
762///         identifier
763Parser::MemInitResult Parser::ParseMemInitializer(DeclTy *ConstructorDecl) {
764  // FIXME: parse '::'[opt] nested-name-specifier[opt]
765
766  if (Tok.isNot(tok::identifier)) {
767    Diag(Tok, diag::err_expected_member_or_base_name);
768    return true;
769  }
770
771  // Get the identifier. This may be a member name or a class name,
772  // but we'll let the semantic analysis determine which it is.
773  IdentifierInfo *II = Tok.getIdentifierInfo();
774  SourceLocation IdLoc = ConsumeToken();
775
776  // Parse the '('.
777  if (Tok.isNot(tok::l_paren)) {
778    Diag(Tok, diag::err_expected_lparen);
779    return true;
780  }
781  SourceLocation LParenLoc = ConsumeParen();
782
783  // Parse the optional expression-list.
784  ExprVector ArgExprs(Actions);
785  CommaLocsTy CommaLocs;
786  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
787    SkipUntil(tok::r_paren);
788    return true;
789  }
790
791  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
792
793  return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, II, IdLoc,
794                                     LParenLoc, ArgExprs.take(),
795                                     ArgExprs.size(), &CommaLocs[0], RParenLoc);
796}
797
798/// ParseExceptionSpecification - Parse a C++ exception-specification
799/// (C++ [except.spec]).
800///
801///       exception-specification:
802///         'throw' '(' type-id-list [opt] ')'
803/// [MS]    'throw' '(' '...' ')'
804///
805///       type-id-list:
806///         type-id
807///         type-id-list ',' type-id
808///
809bool Parser::ParseExceptionSpecification() {
810  assert(Tok.is(tok::kw_throw) && "expected throw");
811
812  SourceLocation ThrowLoc = ConsumeToken();
813
814  if (!Tok.is(tok::l_paren)) {
815    return Diag(Tok, diag::err_expected_lparen_after) << "throw";
816  }
817  SourceLocation LParenLoc = ConsumeParen();
818
819  // Parse throw(...), a Microsoft extension that means "this function
820  // can throw anything".
821  if (Tok.is(tok::ellipsis)) {
822    SourceLocation EllipsisLoc = ConsumeToken();
823    if (!getLang().Microsoft)
824      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
825    SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
826    return false;
827  }
828
829  // Parse the sequence of type-ids.
830  while (Tok.isNot(tok::r_paren)) {
831    ParseTypeName();
832    if (Tok.is(tok::comma))
833      ConsumeToken();
834    else
835      break;
836  }
837
838  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
839  return false;
840}
841