ParseDeclCXX.cpp revision 7f43d6764797ab21216421aeb00f4ec314d503d1
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/Parse/ParseDiagnostic.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.isNot(tok::identifier)) {
178    Diag(Tok, diag::err_expected_namespace_name);
179    // If there was invalid namespace name, skip to end of decl, and eat ';'.
180    SkipUntil(tok::semi);
181    // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
182    return 0;
183  }
184
185  // Parse identifier.
186  NamespcName = Tok.getIdentifierInfo();
187  IdentLoc = ConsumeToken();
188
189  // Parse (optional) attributes (most likely GNU strong-using extension).
190  if (Tok.is(tok::kw___attribute))
191    AttrList = ParseAttributes();
192
193  // Eat ';'.
194  ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
195                   AttrList ? "attributes list" : "namespace name", tok::semi);
196
197  return Actions.ActOnUsingDirective(CurScope, UsingLoc, NamespcLoc, SS,
198                                      IdentLoc, NamespcName, AttrList);
199}
200
201/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that
202/// 'using' was already seen.
203///
204///     using-declaration: [C++ 7.3.p3: namespace.udecl]
205///       'using' 'typename'[opt] ::[opt] nested-name-specifier
206///               unqualified-id [TODO]
207///       'using' :: unqualified-id [TODO]
208///
209Parser::DeclTy *Parser::ParseUsingDeclaration(unsigned Context,
210                                              SourceLocation UsingLoc) {
211  assert(false && "Not implemented");
212  // FIXME: Implement parsing.
213  return 0;
214}
215
216/// ParseClassName - Parse a C++ class-name, which names a class. Note
217/// that we only check that the result names a type; semantic analysis
218/// will need to verify that the type names a class. The result is
219/// either a type or NULL, depending on whether a type name was
220/// found.
221///
222///       class-name: [C++ 9.1]
223///         identifier
224///         simple-template-id
225///
226Parser::TypeTy *Parser::ParseClassName(SourceLocation &EndLocation,
227                                       const CXXScopeSpec *SS) {
228  // Check whether we have a template-id that names a type.
229  if (Tok.is(tok::annot_template_id)) {
230    TemplateIdAnnotation *TemplateId
231      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
232    if (TemplateId->Kind == TNK_Class_template) {
233      if (AnnotateTemplateIdTokenAsType(SS))
234        return 0;
235
236      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
237      TypeTy *Type = Tok.getAnnotationValue();
238      EndLocation = Tok.getAnnotationEndLoc();
239      ConsumeToken();
240      return Type;
241    }
242
243    // Fall through to produce an error below.
244  }
245
246  if (Tok.isNot(tok::identifier)) {
247    Diag(Tok, diag::err_expected_class_name);
248    return 0;
249  }
250
251  // We have an identifier; check whether it is actually a type.
252  TypeTy *Type = Actions.getTypeName(*Tok.getIdentifierInfo(),
253                                     Tok.getLocation(), CurScope, SS);
254  if (!Type) {
255    Diag(Tok, diag::err_expected_class_name);
256    return 0;
257  }
258
259  // Consume the identifier.
260  EndLocation = ConsumeToken();
261  return Type;
262}
263
264/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
265/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
266/// until we reach the start of a definition or see a token that
267/// cannot start a definition.
268///
269///       class-specifier: [C++ class]
270///         class-head '{' member-specification[opt] '}'
271///         class-head '{' member-specification[opt] '}' attributes[opt]
272///       class-head:
273///         class-key identifier[opt] base-clause[opt]
274///         class-key nested-name-specifier identifier base-clause[opt]
275///         class-key nested-name-specifier[opt] simple-template-id
276///                          base-clause[opt]
277/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
278/// [GNU]   class-key attributes[opt] nested-name-specifier
279///                          identifier base-clause[opt]
280/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
281///                          simple-template-id base-clause[opt]
282///       class-key:
283///         'class'
284///         'struct'
285///         'union'
286///
287///       elaborated-type-specifier: [C++ dcl.type.elab]
288///         class-key ::[opt] nested-name-specifier[opt] identifier
289///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
290///                          simple-template-id
291///
292///  Note that the C++ class-specifier and elaborated-type-specifier,
293///  together, subsume the C99 struct-or-union-specifier:
294///
295///       struct-or-union-specifier: [C99 6.7.2.1]
296///         struct-or-union identifier[opt] '{' struct-contents '}'
297///         struct-or-union identifier
298/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
299///                                                         '}' attributes[opt]
300/// [GNU]   struct-or-union attributes[opt] identifier
301///       struct-or-union:
302///         'struct'
303///         'union'
304void Parser::ParseClassSpecifier(DeclSpec &DS,
305                                 TemplateParameterLists *TemplateParams) {
306  assert((Tok.is(tok::kw_class) ||
307          Tok.is(tok::kw_struct) ||
308          Tok.is(tok::kw_union)) &&
309         "Not a class specifier");
310  DeclSpec::TST TagType =
311    Tok.is(tok::kw_class) ? DeclSpec::TST_class :
312    Tok.is(tok::kw_struct) ? DeclSpec::TST_struct :
313    DeclSpec::TST_union;
314
315  SourceLocation StartLoc = ConsumeToken();
316
317  AttributeList *Attr = 0;
318  // If attributes exist after tag, parse them.
319  if (Tok.is(tok::kw___attribute))
320    Attr = ParseAttributes();
321
322  // If declspecs exist after tag, parse them.
323  if (Tok.is(tok::kw___declspec) && PP.getLangOptions().Microsoft)
324    FuzzyParseMicrosoftDeclSpec();
325
326  // Parse the (optional) nested-name-specifier.
327  CXXScopeSpec SS;
328  if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS))
329    if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
330      Diag(Tok, diag::err_expected_ident);
331
332  // Parse the (optional) class name or simple-template-id.
333  IdentifierInfo *Name = 0;
334  SourceLocation NameLoc;
335  TemplateIdAnnotation *TemplateId = 0;
336  if (Tok.is(tok::identifier)) {
337    Name = Tok.getIdentifierInfo();
338    NameLoc = ConsumeToken();
339  } else if (Tok.is(tok::annot_template_id)) {
340    TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
341    NameLoc = ConsumeToken();
342
343    if (TemplateId->Kind != TNK_Class_template) {
344      // The template-name in the simple-template-id refers to
345      // something other than a class template. Give an appropriate
346      // error message and skip to the ';'.
347      SourceRange Range(NameLoc);
348      if (SS.isNotEmpty())
349        Range.setBegin(SS.getBeginLoc());
350
351      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
352        << Name << static_cast<int>(TemplateId->Kind) << Range;
353
354      DS.SetTypeSpecError();
355      SkipUntil(tok::semi, false, true);
356      TemplateId->Destroy();
357      return;
358    }
359  }
360
361  // There are three options here.  If we have 'struct foo;', then
362  // this is a forward declaration.  If we have 'struct foo {...' or
363  // 'struct foo :...' then this is a definition. Otherwise we have
364  // something like 'struct foo xyz', a reference.
365  Action::TagKind TK;
366  if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon)))
367    TK = Action::TK_Definition;
368  else if (Tok.is(tok::semi))
369    TK = Action::TK_Declaration;
370  else
371    TK = Action::TK_Reference;
372
373  if (!Name && !TemplateId && TK != Action::TK_Definition) {
374    // We have a declaration or reference to an anonymous class.
375    Diag(StartLoc, diag::err_anon_type_definition)
376      << DeclSpec::getSpecifierName(TagType);
377
378    // Skip the rest of this declarator, up until the comma or semicolon.
379    SkipUntil(tok::comma, true);
380
381    if (TemplateId)
382      TemplateId->Destroy();
383    return;
384  }
385
386  // Create the tag portion of the class or class template.
387  DeclTy *TagOrTempDecl;
388  if (TemplateId && TK != Action::TK_Reference) {
389    // Explicit specialization or class template partial
390    // specialization. Let semantic analysis decide.
391    ASTTemplateArgsPtr TemplateArgsPtr(Actions,
392                                       TemplateId->getTemplateArgs(),
393                                       TemplateId->getTemplateArgIsType(),
394                                       TemplateId->NumArgs);
395    TagOrTempDecl
396      = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TK,
397                       StartLoc, SS,
398                       TemplateId->Template,
399                       TemplateId->TemplateNameLoc,
400                       TemplateId->LAngleLoc,
401                       TemplateArgsPtr,
402                       TemplateId->getTemplateArgLocations(),
403                       TemplateId->RAngleLoc,
404                       Attr,
405                       Action::MultiTemplateParamsArg(Actions,
406                                    TemplateParams? &(*TemplateParams)[0] : 0,
407                                 TemplateParams? TemplateParams->size() : 0));
408    TemplateId->Destroy();
409  } else if (TemplateParams && TK != Action::TK_Reference)
410    TagOrTempDecl = Actions.ActOnClassTemplate(CurScope, TagType, TK, StartLoc,
411                                               SS, Name, NameLoc, Attr,
412                       Action::MultiTemplateParamsArg(Actions,
413                                                      &(*TemplateParams)[0],
414                                                      TemplateParams->size()));
415  else
416    TagOrTempDecl = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, SS, Name,
417                                     NameLoc, Attr);
418
419  // Parse the optional base clause (C++ only).
420  if (getLang().CPlusPlus && Tok.is(tok::colon))
421    ParseBaseClause(TagOrTempDecl);
422
423  // If there is a body, parse it and inform the actions module.
424  if (Tok.is(tok::l_brace))
425    if (getLang().CPlusPlus)
426      ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempDecl);
427    else
428      ParseStructUnionBody(StartLoc, TagType, TagOrTempDecl);
429  else if (TK == Action::TK_Definition) {
430    // FIXME: Complain that we have a base-specifier list but no
431    // definition.
432    Diag(Tok, diag::err_expected_lbrace);
433  }
434
435  const char *PrevSpec = 0;
436  if (!TagOrTempDecl)
437    DS.SetTypeSpecError();
438  else if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagOrTempDecl))
439    Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec;
440}
441
442/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
443///
444///       base-clause : [C++ class.derived]
445///         ':' base-specifier-list
446///       base-specifier-list:
447///         base-specifier '...'[opt]
448///         base-specifier-list ',' base-specifier '...'[opt]
449void Parser::ParseBaseClause(DeclTy *ClassDecl)
450{
451  assert(Tok.is(tok::colon) && "Not a base clause");
452  ConsumeToken();
453
454  // Build up an array of parsed base specifiers.
455  llvm::SmallVector<BaseTy *, 8> BaseInfo;
456
457  while (true) {
458    // Parse a base-specifier.
459    BaseResult Result = ParseBaseSpecifier(ClassDecl);
460    if (Result.isInvalid()) {
461      // Skip the rest of this base specifier, up until the comma or
462      // opening brace.
463      SkipUntil(tok::comma, tok::l_brace, true, true);
464    } else {
465      // Add this to our array of base specifiers.
466      BaseInfo.push_back(Result.get());
467    }
468
469    // If the next token is a comma, consume it and keep reading
470    // base-specifiers.
471    if (Tok.isNot(tok::comma)) break;
472
473    // Consume the comma.
474    ConsumeToken();
475  }
476
477  // Attach the base specifiers
478  Actions.ActOnBaseSpecifiers(ClassDecl, &BaseInfo[0], BaseInfo.size());
479}
480
481/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
482/// one entry in the base class list of a class specifier, for example:
483///    class foo : public bar, virtual private baz {
484/// 'public bar' and 'virtual private baz' are each base-specifiers.
485///
486///       base-specifier: [C++ class.derived]
487///         ::[opt] nested-name-specifier[opt] class-name
488///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
489///                        class-name
490///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
491///                        class-name
492Parser::BaseResult Parser::ParseBaseSpecifier(DeclTy *ClassDecl)
493{
494  bool IsVirtual = false;
495  SourceLocation StartLoc = Tok.getLocation();
496
497  // Parse the 'virtual' keyword.
498  if (Tok.is(tok::kw_virtual))  {
499    ConsumeToken();
500    IsVirtual = true;
501  }
502
503  // Parse an (optional) access specifier.
504  AccessSpecifier Access = getAccessSpecifierIfPresent();
505  if (Access)
506    ConsumeToken();
507
508  // Parse the 'virtual' keyword (again!), in case it came after the
509  // access specifier.
510  if (Tok.is(tok::kw_virtual))  {
511    SourceLocation VirtualLoc = ConsumeToken();
512    if (IsVirtual) {
513      // Complain about duplicate 'virtual'
514      Diag(VirtualLoc, diag::err_dup_virtual)
515        << SourceRange(VirtualLoc, VirtualLoc);
516    }
517
518    IsVirtual = true;
519  }
520
521  // Parse optional '::' and optional nested-name-specifier.
522  CXXScopeSpec SS;
523  ParseOptionalCXXScopeSpecifier(SS);
524
525  // The location of the base class itself.
526  SourceLocation BaseLoc = Tok.getLocation();
527
528  // Parse the class-name.
529  SourceLocation EndLocation;
530  TypeTy *BaseType = ParseClassName(EndLocation, &SS);
531  if (!BaseType)
532    return true;
533
534  // Find the complete source range for the base-specifier.
535  SourceRange Range(StartLoc, EndLocation);
536
537  // Notify semantic analysis that we have parsed a complete
538  // base-specifier.
539  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
540                                    BaseType, BaseLoc);
541}
542
543/// getAccessSpecifierIfPresent - Determine whether the next token is
544/// a C++ access-specifier.
545///
546///       access-specifier: [C++ class.derived]
547///         'private'
548///         'protected'
549///         'public'
550AccessSpecifier Parser::getAccessSpecifierIfPresent() const
551{
552  switch (Tok.getKind()) {
553  default: return AS_none;
554  case tok::kw_private: return AS_private;
555  case tok::kw_protected: return AS_protected;
556  case tok::kw_public: return AS_public;
557  }
558}
559
560/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
561///
562///       member-declaration:
563///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
564///         function-definition ';'[opt]
565///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
566///         using-declaration                                            [TODO]
567/// [C++0x] static_assert-declaration                                    [TODO]
568///         template-declaration                                         [TODO]
569/// [GNU]   '__extension__' member-declaration
570///
571///       member-declarator-list:
572///         member-declarator
573///         member-declarator-list ',' member-declarator
574///
575///       member-declarator:
576///         declarator pure-specifier[opt]
577///         declarator constant-initializer[opt]
578///         identifier[opt] ':' constant-expression
579///
580///       pure-specifier:   [TODO]
581///         '= 0'
582///
583///       constant-initializer:
584///         '=' constant-expression
585///
586Parser::DeclTy *Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) {
587  // Handle:  member-declaration ::= '__extension__' member-declaration
588  if (Tok.is(tok::kw___extension__)) {
589    // __extension__ silences extension warnings in the subexpression.
590    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
591    ConsumeToken();
592    return ParseCXXClassMemberDeclaration(AS);
593  }
594
595  SourceLocation DSStart = Tok.getLocation();
596  // decl-specifier-seq:
597  // Parse the common declaration-specifiers piece.
598  DeclSpec DS;
599  ParseDeclarationSpecifiers(DS);
600
601  if (Tok.is(tok::semi)) {
602    ConsumeToken();
603    // C++ 9.2p7: The member-declarator-list can be omitted only after a
604    // class-specifier or an enum-specifier or in a friend declaration.
605    // FIXME: Friend declarations.
606    switch (DS.getTypeSpecType()) {
607      case DeclSpec::TST_struct:
608      case DeclSpec::TST_union:
609      case DeclSpec::TST_class:
610      case DeclSpec::TST_enum:
611        return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
612      default:
613        Diag(DSStart, diag::err_no_declarators);
614        return 0;
615    }
616  }
617
618  Declarator DeclaratorInfo(DS, Declarator::MemberContext);
619
620  if (Tok.isNot(tok::colon)) {
621    // Parse the first declarator.
622    ParseDeclarator(DeclaratorInfo);
623    // Error parsing the declarator?
624    if (!DeclaratorInfo.hasName()) {
625      // If so, skip until the semi-colon or a }.
626      SkipUntil(tok::r_brace, true);
627      if (Tok.is(tok::semi))
628        ConsumeToken();
629      return 0;
630    }
631
632    // function-definition:
633    if (Tok.is(tok::l_brace)
634        || (DeclaratorInfo.isFunctionDeclarator() && Tok.is(tok::colon))) {
635      if (!DeclaratorInfo.isFunctionDeclarator()) {
636        Diag(Tok, diag::err_func_def_no_params);
637        ConsumeBrace();
638        SkipUntil(tok::r_brace, true);
639        return 0;
640      }
641
642      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
643        Diag(Tok, diag::err_function_declared_typedef);
644        // This recovery skips the entire function body. It would be nice
645        // to simply call ParseCXXInlineMethodDef() below, however Sema
646        // assumes the declarator represents a function, not a typedef.
647        ConsumeBrace();
648        SkipUntil(tok::r_brace, true);
649        return 0;
650      }
651
652      return ParseCXXInlineMethodDef(AS, DeclaratorInfo);
653    }
654  }
655
656  // member-declarator-list:
657  //   member-declarator
658  //   member-declarator-list ',' member-declarator
659
660  DeclTy *LastDeclInGroup = 0;
661  OwningExprResult BitfieldSize(Actions);
662  OwningExprResult Init(Actions);
663
664  while (1) {
665
666    // member-declarator:
667    //   declarator pure-specifier[opt]
668    //   declarator constant-initializer[opt]
669    //   identifier[opt] ':' constant-expression
670
671    if (Tok.is(tok::colon)) {
672      ConsumeToken();
673      BitfieldSize = ParseConstantExpression();
674      if (BitfieldSize.isInvalid())
675        SkipUntil(tok::comma, true, true);
676    }
677
678    // pure-specifier:
679    //   '= 0'
680    //
681    // constant-initializer:
682    //   '=' constant-expression
683
684    if (Tok.is(tok::equal)) {
685      ConsumeToken();
686      Init = ParseInitializer();
687      if (Init.isInvalid())
688        SkipUntil(tok::comma, true, true);
689    }
690
691    // If attributes exist after the declarator, parse them.
692    if (Tok.is(tok::kw___attribute)) {
693      SourceLocation Loc;
694      AttributeList *AttrList = ParseAttributes(&Loc);
695      DeclaratorInfo.AddAttributes(AttrList, Loc);
696    }
697
698    // NOTE: If Sema is the Action module and declarator is an instance field,
699    // this call will *not* return the created decl; LastDeclInGroup will be
700    // returned instead.
701    // See Sema::ActOnCXXMemberDeclarator for details.
702    LastDeclInGroup = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
703                                                       DeclaratorInfo,
704                                                       BitfieldSize.release(),
705                                                       Init.release(),
706                                                       LastDeclInGroup);
707
708    if (DeclaratorInfo.isFunctionDeclarator() &&
709        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
710          != DeclSpec::SCS_typedef) {
711      // We just declared a member function. If this member function
712      // has any default arguments, we'll need to parse them later.
713      LateParsedMethodDeclaration *LateMethod = 0;
714      DeclaratorChunk::FunctionTypeInfo &FTI
715        = DeclaratorInfo.getTypeObject(0).Fun;
716      for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
717        if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
718          if (!LateMethod) {
719            // Push this method onto the stack of late-parsed method
720            // declarations.
721            getCurTopClassStack().MethodDecls.push_back(
722                                   LateParsedMethodDeclaration(LastDeclInGroup));
723            LateMethod = &getCurTopClassStack().MethodDecls.back();
724
725            // Add all of the parameters prior to this one (they don't
726            // have default arguments).
727            LateMethod->DefaultArgs.reserve(FTI.NumArgs);
728            for (unsigned I = 0; I < ParamIdx; ++I)
729              LateMethod->DefaultArgs.push_back(
730                        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param));
731          }
732
733          // Add this parameter to the list of parameters (it or may
734          // not have a default argument).
735          LateMethod->DefaultArgs.push_back(
736            LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
737                                      FTI.ArgInfo[ParamIdx].DefaultArgTokens));
738        }
739      }
740    }
741
742    // If we don't have a comma, it is either the end of the list (a ';')
743    // or an error, bail out.
744    if (Tok.isNot(tok::comma))
745      break;
746
747    // Consume the comma.
748    ConsumeToken();
749
750    // Parse the next declarator.
751    DeclaratorInfo.clear();
752    BitfieldSize = 0;
753    Init = 0;
754
755    // Attributes are only allowed on the second declarator.
756    if (Tok.is(tok::kw___attribute)) {
757      SourceLocation Loc;
758      AttributeList *AttrList = ParseAttributes(&Loc);
759      DeclaratorInfo.AddAttributes(AttrList, Loc);
760    }
761
762    if (Tok.isNot(tok::colon))
763      ParseDeclarator(DeclaratorInfo);
764  }
765
766  if (Tok.is(tok::semi)) {
767    ConsumeToken();
768    // Reverse the chain list.
769    return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup);
770  }
771
772  Diag(Tok, diag::err_expected_semi_decl_list);
773  // Skip to end of block or statement
774  SkipUntil(tok::r_brace, true, true);
775  if (Tok.is(tok::semi))
776    ConsumeToken();
777  return 0;
778}
779
780/// ParseCXXMemberSpecification - Parse the class definition.
781///
782///       member-specification:
783///         member-declaration member-specification[opt]
784///         access-specifier ':' member-specification[opt]
785///
786void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
787                                         unsigned TagType, DeclTy *TagDecl) {
788  assert((TagType == DeclSpec::TST_struct ||
789         TagType == DeclSpec::TST_union  ||
790         TagType == DeclSpec::TST_class) && "Invalid TagType!");
791
792  SourceLocation LBraceLoc = ConsumeBrace();
793
794  if (!CurScope->isClassScope() && // Not about to define a nested class.
795      CurScope->isInCXXInlineMethodScope()) {
796    // We will define a local class of an inline method.
797    // Push a new LexedMethodsForTopClass for its inline methods.
798    PushTopClassStack();
799  }
800
801  // Enter a scope for the class.
802  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
803
804  if (TagDecl)
805    Actions.ActOnTagStartDefinition(CurScope, TagDecl);
806  else {
807    SkipUntil(tok::r_brace, false, false);
808    return;
809  }
810
811  // C++ 11p3: Members of a class defined with the keyword class are private
812  // by default. Members of a class defined with the keywords struct or union
813  // are public by default.
814  AccessSpecifier CurAS;
815  if (TagType == DeclSpec::TST_class)
816    CurAS = AS_private;
817  else
818    CurAS = AS_public;
819
820  // While we still have something to read, read the member-declarations.
821  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
822    // Each iteration of this loop reads one member-declaration.
823
824    // Check for extraneous top-level semicolon.
825    if (Tok.is(tok::semi)) {
826      Diag(Tok, diag::ext_extra_struct_semi);
827      ConsumeToken();
828      continue;
829    }
830
831    AccessSpecifier AS = getAccessSpecifierIfPresent();
832    if (AS != AS_none) {
833      // Current token is a C++ access specifier.
834      CurAS = AS;
835      ConsumeToken();
836      ExpectAndConsume(tok::colon, diag::err_expected_colon);
837      continue;
838    }
839
840    // Parse all the comma separated declarators.
841    ParseCXXClassMemberDeclaration(CurAS);
842  }
843
844  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
845
846  AttributeList *AttrList = 0;
847  // If attributes exist after class contents, parse them.
848  if (Tok.is(tok::kw___attribute))
849    AttrList = ParseAttributes(); // FIXME: where should I put them?
850
851  Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
852                                            LBraceLoc, RBraceLoc);
853
854  // C++ 9.2p2: Within the class member-specification, the class is regarded as
855  // complete within function bodies, default arguments,
856  // exception-specifications, and constructor ctor-initializers (including
857  // such things in nested classes).
858  //
859  // FIXME: Only function bodies and constructor ctor-initializers are
860  // parsed correctly, fix the rest.
861  if (!CurScope->getParent()->isClassScope()) {
862    // We are not inside a nested class. This class and its nested classes
863    // are complete and we can parse the delayed portions of method
864    // declarations and the lexed inline method definitions.
865    ParseLexedMethodDeclarations();
866    ParseLexedMethodDefs();
867
868    // For a local class of inline method, pop the LexedMethodsForTopClass that
869    // was previously pushed.
870
871    assert((CurScope->isInCXXInlineMethodScope() ||
872           TopClassStacks.size() == 1) &&
873           "MethodLexers not getting popped properly!");
874    if (CurScope->isInCXXInlineMethodScope())
875      PopTopClassStack();
876  }
877
878  // Leave the class scope.
879  ClassScope.Exit();
880
881  Actions.ActOnTagFinishDefinition(CurScope, TagDecl);
882}
883
884/// ParseConstructorInitializer - Parse a C++ constructor initializer,
885/// which explicitly initializes the members or base classes of a
886/// class (C++ [class.base.init]). For example, the three initializers
887/// after the ':' in the Derived constructor below:
888///
889/// @code
890/// class Base { };
891/// class Derived : Base {
892///   int x;
893///   float f;
894/// public:
895///   Derived(float f) : Base(), x(17), f(f) { }
896/// };
897/// @endcode
898///
899/// [C++]  ctor-initializer:
900///          ':' mem-initializer-list
901///
902/// [C++]  mem-initializer-list:
903///          mem-initializer
904///          mem-initializer , mem-initializer-list
905void Parser::ParseConstructorInitializer(DeclTy *ConstructorDecl) {
906  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
907
908  SourceLocation ColonLoc = ConsumeToken();
909
910  llvm::SmallVector<MemInitTy*, 4> MemInitializers;
911
912  do {
913    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
914    if (!MemInit.isInvalid())
915      MemInitializers.push_back(MemInit.get());
916
917    if (Tok.is(tok::comma))
918      ConsumeToken();
919    else if (Tok.is(tok::l_brace))
920      break;
921    else {
922      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
923      SkipUntil(tok::l_brace, true, true);
924      break;
925    }
926  } while (true);
927
928  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
929                               &MemInitializers[0], MemInitializers.size());
930}
931
932/// ParseMemInitializer - Parse a C++ member initializer, which is
933/// part of a constructor initializer that explicitly initializes one
934/// member or base class (C++ [class.base.init]). See
935/// ParseConstructorInitializer for an example.
936///
937/// [C++] mem-initializer:
938///         mem-initializer-id '(' expression-list[opt] ')'
939///
940/// [C++] mem-initializer-id:
941///         '::'[opt] nested-name-specifier[opt] class-name
942///         identifier
943Parser::MemInitResult Parser::ParseMemInitializer(DeclTy *ConstructorDecl) {
944  // FIXME: parse '::'[opt] nested-name-specifier[opt]
945
946  if (Tok.isNot(tok::identifier)) {
947    Diag(Tok, diag::err_expected_member_or_base_name);
948    return true;
949  }
950
951  // Get the identifier. This may be a member name or a class name,
952  // but we'll let the semantic analysis determine which it is.
953  IdentifierInfo *II = Tok.getIdentifierInfo();
954  SourceLocation IdLoc = ConsumeToken();
955
956  // Parse the '('.
957  if (Tok.isNot(tok::l_paren)) {
958    Diag(Tok, diag::err_expected_lparen);
959    return true;
960  }
961  SourceLocation LParenLoc = ConsumeParen();
962
963  // Parse the optional expression-list.
964  ExprVector ArgExprs(Actions);
965  CommaLocsTy CommaLocs;
966  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
967    SkipUntil(tok::r_paren);
968    return true;
969  }
970
971  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
972
973  return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, II, IdLoc,
974                                     LParenLoc, ArgExprs.take(),
975                                     ArgExprs.size(), &CommaLocs[0], RParenLoc);
976}
977
978/// ParseExceptionSpecification - Parse a C++ exception-specification
979/// (C++ [except.spec]).
980///
981///       exception-specification:
982///         'throw' '(' type-id-list [opt] ')'
983/// [MS]    'throw' '(' '...' ')'
984///
985///       type-id-list:
986///         type-id
987///         type-id-list ',' type-id
988///
989bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc) {
990  assert(Tok.is(tok::kw_throw) && "expected throw");
991
992  SourceLocation ThrowLoc = ConsumeToken();
993
994  if (!Tok.is(tok::l_paren)) {
995    return Diag(Tok, diag::err_expected_lparen_after) << "throw";
996  }
997  SourceLocation LParenLoc = ConsumeParen();
998
999  // Parse throw(...), a Microsoft extension that means "this function
1000  // can throw anything".
1001  if (Tok.is(tok::ellipsis)) {
1002    SourceLocation EllipsisLoc = ConsumeToken();
1003    if (!getLang().Microsoft)
1004      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
1005    EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1006    return false;
1007  }
1008
1009  // Parse the sequence of type-ids.
1010  while (Tok.isNot(tok::r_paren)) {
1011    ParseTypeName();
1012    if (Tok.is(tok::comma))
1013      ConsumeToken();
1014    else
1015      break;
1016  }
1017
1018  EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1019  return false;
1020}
1021