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