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