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