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