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