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