ParseDeclCXX.cpp revision 29d9c1adfadf65e2d847d44bec37746844b9e0e3
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/Basic/OperatorKinds.h"
15#include "clang/Parse/Parser.h"
16#include "clang/Parse/ParseDiagnostic.h"
17#include "clang/Parse/DeclSpec.h"
18#include "clang/Parse/Scope.h"
19#include "clang/Parse/Template.h"
20#include "ExtensionRAIIObject.h"
21using namespace clang;
22
23/// ParseNamespace - We know that the current token is a namespace keyword. This
24/// may either be a top level namespace or a block-level namespace alias.
25///
26///       namespace-definition: [C++ 7.3: basic.namespace]
27///         named-namespace-definition
28///         unnamed-namespace-definition
29///
30///       unnamed-namespace-definition:
31///         'namespace' attributes[opt] '{' namespace-body '}'
32///
33///       named-namespace-definition:
34///         original-namespace-definition
35///         extension-namespace-definition
36///
37///       original-namespace-definition:
38///         'namespace' identifier attributes[opt] '{' namespace-body '}'
39///
40///       extension-namespace-definition:
41///         'namespace' original-namespace-name '{' namespace-body '}'
42///
43///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
44///         'namespace' identifier '=' qualified-namespace-specifier ';'
45///
46Parser::DeclPtrTy Parser::ParseNamespace(unsigned Context,
47                                         SourceLocation &DeclEnd) {
48  assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
49  SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
50
51  if (Tok.is(tok::code_completion)) {
52    Actions.CodeCompleteNamespaceDecl(CurScope);
53    ConsumeToken();
54  }
55
56  SourceLocation IdentLoc;
57  IdentifierInfo *Ident = 0;
58
59  Token attrTok;
60
61  if (Tok.is(tok::identifier)) {
62    Ident = Tok.getIdentifierInfo();
63    IdentLoc = ConsumeToken();  // eat the identifier.
64  }
65
66  // Read label attributes, if present.
67  Action::AttrTy *AttrList = 0;
68  if (Tok.is(tok::kw___attribute)) {
69    attrTok = Tok;
70
71    // FIXME: save these somewhere.
72    AttrList = ParseGNUAttributes();
73  }
74
75  if (Tok.is(tok::equal)) {
76    if (AttrList)
77      Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
78
79    return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
80  }
81
82  if (Tok.isNot(tok::l_brace)) {
83    Diag(Tok, Ident ? diag::err_expected_lbrace :
84         diag::err_expected_ident_lbrace);
85    return DeclPtrTy();
86  }
87
88  SourceLocation LBrace = ConsumeBrace();
89
90  // Enter a scope for the namespace.
91  ParseScope NamespaceScope(this, Scope::DeclScope);
92
93  DeclPtrTy NamespcDecl =
94    Actions.ActOnStartNamespaceDef(CurScope, IdentLoc, Ident, LBrace);
95
96  PrettyStackTraceActionsDecl CrashInfo(NamespcDecl, NamespaceLoc, Actions,
97                                        PP.getSourceManager(),
98                                        "parsing namespace");
99
100  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
101    CXX0XAttributeList Attr;
102    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
103      Attr = ParseCXX0XAttributes();
104    ParseExternalDeclaration(Attr);
105  }
106
107  // Leave the namespace scope.
108  NamespaceScope.Exit();
109
110  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBrace);
111  Actions.ActOnFinishNamespaceDef(NamespcDecl, RBraceLoc);
112
113  DeclEnd = RBraceLoc;
114  return NamespcDecl;
115}
116
117/// ParseNamespaceAlias - Parse the part after the '=' in a namespace
118/// alias definition.
119///
120Parser::DeclPtrTy Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
121                                              SourceLocation AliasLoc,
122                                              IdentifierInfo *Alias,
123                                              SourceLocation &DeclEnd) {
124  assert(Tok.is(tok::equal) && "Not equal token");
125
126  ConsumeToken(); // eat the '='.
127
128  if (Tok.is(tok::code_completion)) {
129    Actions.CodeCompleteNamespaceAliasDecl(CurScope);
130    ConsumeToken();
131  }
132
133  CXXScopeSpec SS;
134  // Parse (optional) nested-name-specifier.
135  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
136
137  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
138    Diag(Tok, diag::err_expected_namespace_name);
139    // Skip to end of the definition and eat the ';'.
140    SkipUntil(tok::semi);
141    return DeclPtrTy();
142  }
143
144  // Parse identifier.
145  IdentifierInfo *Ident = Tok.getIdentifierInfo();
146  SourceLocation IdentLoc = ConsumeToken();
147
148  // Eat the ';'.
149  DeclEnd = Tok.getLocation();
150  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
151                   "", tok::semi);
152
153  return Actions.ActOnNamespaceAliasDef(CurScope, NamespaceLoc, AliasLoc, Alias,
154                                        SS, IdentLoc, Ident);
155}
156
157/// ParseLinkage - We know that the current token is a string_literal
158/// and just before that, that extern was seen.
159///
160///       linkage-specification: [C++ 7.5p2: dcl.link]
161///         'extern' string-literal '{' declaration-seq[opt] '}'
162///         'extern' string-literal declaration
163///
164Parser::DeclPtrTy Parser::ParseLinkage(unsigned Context) {
165  assert(Tok.is(tok::string_literal) && "Not a string literal!");
166  llvm::SmallVector<char, 8> LangBuffer;
167  // LangBuffer is guaranteed to be big enough.
168  LangBuffer.resize(Tok.getLength());
169  const char *LangBufPtr = &LangBuffer[0];
170  unsigned StrSize = PP.getSpelling(Tok, LangBufPtr);
171
172  SourceLocation Loc = ConsumeStringToken();
173
174  ParseScope LinkageScope(this, Scope::DeclScope);
175  DeclPtrTy LinkageSpec
176    = Actions.ActOnStartLinkageSpecification(CurScope,
177                                             /*FIXME: */SourceLocation(),
178                                             Loc, LangBufPtr, StrSize,
179                                       Tok.is(tok::l_brace)? Tok.getLocation()
180                                                           : SourceLocation());
181
182  CXX0XAttributeList Attr;
183  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
184    Attr = ParseCXX0XAttributes();
185  }
186
187  if (Tok.isNot(tok::l_brace)) {
188    ParseDeclarationOrFunctionDefinition(Attr.AttrList);
189    return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec,
190                                                   SourceLocation());
191  }
192
193  if (Attr.HasAttr)
194    Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
195      << Attr.Range;
196
197  SourceLocation LBrace = ConsumeBrace();
198  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
199    CXX0XAttributeList Attr;
200    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
201      Attr = ParseCXX0XAttributes();
202    ParseExternalDeclaration(Attr);
203  }
204
205  SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace);
206  return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec, RBrace);
207}
208
209/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
210/// using-directive. Assumes that current token is 'using'.
211Parser::DeclPtrTy Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
212                                                     SourceLocation &DeclEnd,
213                                                     CXX0XAttributeList Attr) {
214  assert(Tok.is(tok::kw_using) && "Not using token");
215
216  // Eat 'using'.
217  SourceLocation UsingLoc = ConsumeToken();
218
219  if (Tok.is(tok::code_completion)) {
220    Actions.CodeCompleteUsing(CurScope);
221    ConsumeToken();
222  }
223
224  if (Tok.is(tok::kw_namespace))
225    // Next token after 'using' is 'namespace' so it must be using-directive
226    return ParseUsingDirective(Context, UsingLoc, DeclEnd, Attr.AttrList);
227
228  if (Attr.HasAttr)
229    Diag(Attr.Range.getBegin(), diag::err_attributes_not_allowed)
230      << Attr.Range;
231
232  // Otherwise, it must be using-declaration.
233  // Ignore illegal attributes (the caller should already have issued an error.
234  return ParseUsingDeclaration(Context, UsingLoc, DeclEnd);
235}
236
237/// ParseUsingDirective - Parse C++ using-directive, assumes
238/// that current token is 'namespace' and 'using' was already parsed.
239///
240///       using-directive: [C++ 7.3.p4: namespace.udir]
241///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
242///                 namespace-name ;
243/// [GNU] using-directive:
244///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
245///                 namespace-name attributes[opt] ;
246///
247Parser::DeclPtrTy Parser::ParseUsingDirective(unsigned Context,
248                                              SourceLocation UsingLoc,
249                                              SourceLocation &DeclEnd,
250                                              AttributeList *Attr) {
251  assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
252
253  // Eat 'namespace'.
254  SourceLocation NamespcLoc = ConsumeToken();
255
256  if (Tok.is(tok::code_completion)) {
257    Actions.CodeCompleteUsingDirective(CurScope);
258    ConsumeToken();
259  }
260
261  CXXScopeSpec SS;
262  // Parse (optional) nested-name-specifier.
263  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
264
265  IdentifierInfo *NamespcName = 0;
266  SourceLocation IdentLoc = SourceLocation();
267
268  // Parse namespace-name.
269  if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
270    Diag(Tok, diag::err_expected_namespace_name);
271    // If there was invalid namespace name, skip to end of decl, and eat ';'.
272    SkipUntil(tok::semi);
273    // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
274    return DeclPtrTy();
275  }
276
277  // Parse identifier.
278  NamespcName = Tok.getIdentifierInfo();
279  IdentLoc = ConsumeToken();
280
281  // Parse (optional) attributes (most likely GNU strong-using extension).
282  bool GNUAttr = false;
283  if (Tok.is(tok::kw___attribute)) {
284    GNUAttr = true;
285    Attr = addAttributeLists(Attr, ParseGNUAttributes());
286  }
287
288  // Eat ';'.
289  DeclEnd = Tok.getLocation();
290  ExpectAndConsume(tok::semi,
291                   GNUAttr ? diag::err_expected_semi_after_attribute_list :
292                   diag::err_expected_semi_after_namespace_name, "", tok::semi);
293
294  return Actions.ActOnUsingDirective(CurScope, UsingLoc, NamespcLoc, SS,
295                                      IdentLoc, NamespcName, Attr);
296}
297
298/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that
299/// 'using' was already seen.
300///
301///     using-declaration: [C++ 7.3.p3: namespace.udecl]
302///       'using' 'typename'[opt] ::[opt] nested-name-specifier
303///               unqualified-id
304///       'using' :: unqualified-id
305///
306Parser::DeclPtrTy Parser::ParseUsingDeclaration(unsigned Context,
307                                                SourceLocation UsingLoc,
308                                                SourceLocation &DeclEnd,
309                                                AccessSpecifier AS) {
310  CXXScopeSpec SS;
311  SourceLocation TypenameLoc;
312  bool IsTypeName;
313
314  // Ignore optional 'typename'.
315  // FIXME: This is wrong; we should parse this as a typename-specifier.
316  if (Tok.is(tok::kw_typename)) {
317    TypenameLoc = Tok.getLocation();
318    ConsumeToken();
319    IsTypeName = true;
320  }
321  else
322    IsTypeName = false;
323
324  // Parse nested-name-specifier.
325  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
326
327  AttributeList *AttrList = 0;
328
329  // Check nested-name specifier.
330  if (SS.isInvalid()) {
331    SkipUntil(tok::semi);
332    return DeclPtrTy();
333  }
334
335  // Parse the unqualified-id. We allow parsing of both constructor and
336  // destructor names and allow the action module to diagnose any semantic
337  // errors.
338  UnqualifiedId Name;
339  if (ParseUnqualifiedId(SS,
340                         /*EnteringContext=*/false,
341                         /*AllowDestructorName=*/true,
342                         /*AllowConstructorName=*/true,
343                         /*ObjectType=*/0,
344                         Name)) {
345    SkipUntil(tok::semi);
346    return DeclPtrTy();
347  }
348
349  // Parse (optional) attributes (most likely GNU strong-using extension).
350  if (Tok.is(tok::kw___attribute))
351    AttrList = ParseGNUAttributes();
352
353  // Eat ';'.
354  DeclEnd = Tok.getLocation();
355  ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
356                   AttrList ? "attributes list" : "using declaration",
357                   tok::semi);
358
359  return Actions.ActOnUsingDeclaration(CurScope, AS, UsingLoc, SS, Name,
360                                       AttrList, IsTypeName, TypenameLoc);
361}
362
363/// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion.
364///
365///      static_assert-declaration:
366///        static_assert ( constant-expression  ,  string-literal  ) ;
367///
368Parser::DeclPtrTy Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
369  assert(Tok.is(tok::kw_static_assert) && "Not a static_assert declaration");
370  SourceLocation StaticAssertLoc = ConsumeToken();
371
372  if (Tok.isNot(tok::l_paren)) {
373    Diag(Tok, diag::err_expected_lparen);
374    return DeclPtrTy();
375  }
376
377  SourceLocation LParenLoc = ConsumeParen();
378
379  OwningExprResult AssertExpr(ParseConstantExpression());
380  if (AssertExpr.isInvalid()) {
381    SkipUntil(tok::semi);
382    return DeclPtrTy();
383  }
384
385  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
386    return DeclPtrTy();
387
388  if (Tok.isNot(tok::string_literal)) {
389    Diag(Tok, diag::err_expected_string_literal);
390    SkipUntil(tok::semi);
391    return DeclPtrTy();
392  }
393
394  OwningExprResult AssertMessage(ParseStringLiteralExpression());
395  if (AssertMessage.isInvalid())
396    return DeclPtrTy();
397
398  MatchRHSPunctuation(tok::r_paren, LParenLoc);
399
400  DeclEnd = Tok.getLocation();
401  ExpectAndConsume(tok::semi, diag::err_expected_semi_after_static_assert);
402
403  return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, move(AssertExpr),
404                                              move(AssertMessage));
405}
406
407/// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
408///
409/// 'decltype' ( expression )
410///
411void Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
412  assert(Tok.is(tok::kw_decltype) && "Not a decltype specifier");
413
414  SourceLocation StartLoc = ConsumeToken();
415  SourceLocation LParenLoc = Tok.getLocation();
416
417  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
418                       "decltype")) {
419    SkipUntil(tok::r_paren);
420    return;
421  }
422
423  // Parse the expression
424
425  // C++0x [dcl.type.simple]p4:
426  //   The operand of the decltype specifier is an unevaluated operand.
427  EnterExpressionEvaluationContext Unevaluated(Actions,
428                                               Action::Unevaluated);
429  OwningExprResult Result = ParseExpression();
430  if (Result.isInvalid()) {
431    SkipUntil(tok::r_paren);
432    return;
433  }
434
435  // Match the ')'
436  SourceLocation RParenLoc;
437  if (Tok.is(tok::r_paren))
438    RParenLoc = ConsumeParen();
439  else
440    MatchRHSPunctuation(tok::r_paren, LParenLoc);
441
442  if (RParenLoc.isInvalid())
443    return;
444
445  const char *PrevSpec = 0;
446  unsigned DiagID;
447  // Check for duplicate type specifiers (e.g. "int decltype(a)").
448  if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
449                         DiagID, Result.release()))
450    Diag(StartLoc, DiagID) << PrevSpec;
451}
452
453/// ParseClassName - Parse a C++ class-name, which names a class. Note
454/// that we only check that the result names a type; semantic analysis
455/// will need to verify that the type names a class. The result is
456/// either a type or NULL, depending on whether a type name was
457/// found.
458///
459///       class-name: [C++ 9.1]
460///         identifier
461///         simple-template-id
462///
463Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation,
464                                          const CXXScopeSpec *SS,
465                                          bool DestrExpected) {
466  // Check whether we have a template-id that names a type.
467  if (Tok.is(tok::annot_template_id)) {
468    TemplateIdAnnotation *TemplateId
469      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
470    if (TemplateId->Kind == TNK_Type_template) {
471      AnnotateTemplateIdTokenAsType(SS);
472
473      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
474      TypeTy *Type = Tok.getAnnotationValue();
475      EndLocation = Tok.getAnnotationEndLoc();
476      ConsumeToken();
477
478      if (Type)
479        return Type;
480      return true;
481    }
482
483    // Fall through to produce an error below.
484  }
485
486  if (Tok.isNot(tok::identifier)) {
487    Diag(Tok, diag::err_expected_class_name);
488    return true;
489  }
490
491  // We have an identifier; check whether it is actually a type.
492  TypeTy *Type = Actions.getTypeName(*Tok.getIdentifierInfo(),
493                                     Tok.getLocation(), CurScope, SS,
494                                     true);
495  if (!Type) {
496    Diag(Tok, DestrExpected ? diag::err_destructor_class_name
497                            : diag::err_expected_class_name);
498    return true;
499  }
500
501  // Consume the identifier.
502  EndLocation = ConsumeToken();
503  return Type;
504}
505
506/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
507/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
508/// until we reach the start of a definition or see a token that
509/// cannot start a definition.
510///
511///       class-specifier: [C++ class]
512///         class-head '{' member-specification[opt] '}'
513///         class-head '{' member-specification[opt] '}' attributes[opt]
514///       class-head:
515///         class-key identifier[opt] base-clause[opt]
516///         class-key nested-name-specifier identifier base-clause[opt]
517///         class-key nested-name-specifier[opt] simple-template-id
518///                          base-clause[opt]
519/// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
520/// [GNU]   class-key attributes[opt] nested-name-specifier
521///                          identifier base-clause[opt]
522/// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
523///                          simple-template-id base-clause[opt]
524///       class-key:
525///         'class'
526///         'struct'
527///         'union'
528///
529///       elaborated-type-specifier: [C++ dcl.type.elab]
530///         class-key ::[opt] nested-name-specifier[opt] identifier
531///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
532///                          simple-template-id
533///
534///  Note that the C++ class-specifier and elaborated-type-specifier,
535///  together, subsume the C99 struct-or-union-specifier:
536///
537///       struct-or-union-specifier: [C99 6.7.2.1]
538///         struct-or-union identifier[opt] '{' struct-contents '}'
539///         struct-or-union identifier
540/// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
541///                                                         '}' attributes[opt]
542/// [GNU]   struct-or-union attributes[opt] identifier
543///       struct-or-union:
544///         'struct'
545///         'union'
546void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
547                                 SourceLocation StartLoc, DeclSpec &DS,
548                                 const ParsedTemplateInfo &TemplateInfo,
549                                 AccessSpecifier AS) {
550  DeclSpec::TST TagType;
551  if (TagTokKind == tok::kw_struct)
552    TagType = DeclSpec::TST_struct;
553  else if (TagTokKind == tok::kw_class)
554    TagType = DeclSpec::TST_class;
555  else {
556    assert(TagTokKind == tok::kw_union && "Not a class specifier");
557    TagType = DeclSpec::TST_union;
558  }
559
560  if (Tok.is(tok::code_completion)) {
561    // Code completion for a struct, class, or union name.
562    Actions.CodeCompleteTag(CurScope, TagType);
563    ConsumeToken();
564  }
565
566  AttributeList *AttrList = 0;
567  // If attributes exist after tag, parse them.
568  if (Tok.is(tok::kw___attribute))
569    AttrList = ParseGNUAttributes();
570
571  // If declspecs exist after tag, parse them.
572  if (Tok.is(tok::kw___declspec))
573    AttrList = ParseMicrosoftDeclSpec(AttrList);
574
575  // If C++0x attributes exist here, parse them.
576  // FIXME: Are we consistent with the ordering of parsing of different
577  // styles of attributes?
578  if (isCXX0XAttributeSpecifier())
579    AttrList = addAttributeLists(AttrList, ParseCXX0XAttributes().AttrList);
580
581  if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_pod)) {
582    // GNU libstdc++ 4.2 uses __is_pod as the name of a struct template, but
583    // __is_pod is a keyword in GCC >= 4.3. Therefore, when we see the
584    // token sequence "struct __is_pod", make __is_pod into a normal
585    // identifier rather than a keyword, to allow libstdc++ 4.2 to work
586    // properly.
587    Tok.getIdentifierInfo()->setTokenID(tok::identifier);
588    Tok.setKind(tok::identifier);
589  }
590
591  if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_empty)) {
592    // GNU libstdc++ 4.2 uses __is_empty as the name of a struct template, but
593    // __is_empty is a keyword in GCC >= 4.3. Therefore, when we see the
594    // token sequence "struct __is_empty", make __is_empty into a normal
595    // identifier rather than a keyword, to allow libstdc++ 4.2 to work
596    // properly.
597    Tok.getIdentifierInfo()->setTokenID(tok::identifier);
598    Tok.setKind(tok::identifier);
599  }
600
601  // Parse the (optional) nested-name-specifier.
602  CXXScopeSpec SS;
603  if (getLang().CPlusPlus &&
604      ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true))
605    if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
606      Diag(Tok, diag::err_expected_ident);
607
608  TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
609
610  // Parse the (optional) class name or simple-template-id.
611  IdentifierInfo *Name = 0;
612  SourceLocation NameLoc;
613  TemplateIdAnnotation *TemplateId = 0;
614  if (Tok.is(tok::identifier)) {
615    Name = Tok.getIdentifierInfo();
616    NameLoc = ConsumeToken();
617
618    if (Tok.is(tok::less)) {
619      // The name was supposed to refer to a template, but didn't.
620      // Eat the template argument list and try to continue parsing this as
621      // a class (or template thereof).
622      TemplateArgList TemplateArgs;
623      SourceLocation LAngleLoc, RAngleLoc;
624      if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, &SS,
625                                           true, LAngleLoc,
626                                           TemplateArgs, RAngleLoc)) {
627        // We couldn't parse the template argument list at all, so don't
628        // try to give any location information for the list.
629        LAngleLoc = RAngleLoc = SourceLocation();
630      }
631
632      Diag(NameLoc, diag::err_explicit_spec_non_template)
633        << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
634        << (TagType == DeclSpec::TST_class? 0
635            : TagType == DeclSpec::TST_struct? 1
636            : 2)
637        << Name
638        << SourceRange(LAngleLoc, RAngleLoc);
639
640      // Strip off the last template parameter list if it was empty, since
641      // we've removed its template argument list.
642      if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
643        if (TemplateParams && TemplateParams->size() > 1) {
644          TemplateParams->pop_back();
645        } else {
646          TemplateParams = 0;
647          const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
648            = ParsedTemplateInfo::NonTemplate;
649        }
650      } else if (TemplateInfo.Kind
651                                == ParsedTemplateInfo::ExplicitInstantiation) {
652        // Pretend this is just a forward declaration.
653        TemplateParams = 0;
654        const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
655          = ParsedTemplateInfo::NonTemplate;
656        const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
657          = SourceLocation();
658        const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
659          = SourceLocation();
660      }
661
662
663    }
664  } else if (Tok.is(tok::annot_template_id)) {
665    TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
666    NameLoc = ConsumeToken();
667
668    if (TemplateId->Kind != TNK_Type_template) {
669      // The template-name in the simple-template-id refers to
670      // something other than a class template. Give an appropriate
671      // error message and skip to the ';'.
672      SourceRange Range(NameLoc);
673      if (SS.isNotEmpty())
674        Range.setBegin(SS.getBeginLoc());
675
676      Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
677        << Name << static_cast<int>(TemplateId->Kind) << Range;
678
679      DS.SetTypeSpecError();
680      SkipUntil(tok::semi, false, true);
681      TemplateId->Destroy();
682      return;
683    }
684  }
685
686  // There are four options here.  If we have 'struct foo;', then this
687  // is either a forward declaration or a friend declaration, which
688  // have to be treated differently.  If we have 'struct foo {...' or
689  // 'struct foo :...' then this is a definition. Otherwise we have
690  // something like 'struct foo xyz', a reference.
691  Action::TagUseKind TUK;
692  if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon))) {
693    if (DS.isFriendSpecified()) {
694      // C++ [class.friend]p2:
695      //   A class shall not be defined in a friend declaration.
696      Diag(Tok.getLocation(), diag::err_friend_decl_defines_class)
697        << SourceRange(DS.getFriendSpecLoc());
698
699      // Skip everything up to the semicolon, so that this looks like a proper
700      // friend class (or template thereof) declaration.
701      SkipUntil(tok::semi, true, true);
702      TUK = Action::TUK_Friend;
703    } else {
704      // Okay, this is a class definition.
705      TUK = Action::TUK_Definition;
706    }
707  } else if (Tok.is(tok::semi))
708    TUK = DS.isFriendSpecified() ? Action::TUK_Friend : Action::TUK_Declaration;
709  else
710    TUK = Action::TUK_Reference;
711
712  if (!Name && !TemplateId && TUK != Action::TUK_Definition) {
713    // We have a declaration or reference to an anonymous class.
714    Diag(StartLoc, diag::err_anon_type_definition)
715      << DeclSpec::getSpecifierName(TagType);
716
717    SkipUntil(tok::comma, true);
718
719    if (TemplateId)
720      TemplateId->Destroy();
721    return;
722  }
723
724  // Create the tag portion of the class or class template.
725  Action::DeclResult TagOrTempResult = true; // invalid
726  Action::TypeResult TypeResult = true; // invalid
727
728  // FIXME: When TUK == TUK_Reference and we have a template-id, we need
729  // to turn that template-id into a type.
730
731  bool Owned = false;
732  if (TemplateId) {
733    // Explicit specialization, class template partial specialization,
734    // or explicit instantiation.
735    ASTTemplateArgsPtr TemplateArgsPtr(Actions,
736                                       TemplateId->getTemplateArgs(),
737                                       TemplateId->NumArgs);
738    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
739        TUK == Action::TUK_Declaration) {
740      // This is an explicit instantiation of a class template.
741      TagOrTempResult
742        = Actions.ActOnExplicitInstantiation(CurScope,
743                                             TemplateInfo.ExternLoc,
744                                             TemplateInfo.TemplateLoc,
745                                             TagType,
746                                             StartLoc,
747                                             SS,
748                                     TemplateTy::make(TemplateId->Template),
749                                             TemplateId->TemplateNameLoc,
750                                             TemplateId->LAngleLoc,
751                                             TemplateArgsPtr,
752                                             TemplateId->RAngleLoc,
753                                             AttrList);
754    } else if (TUK == Action::TUK_Reference) {
755      TypeResult
756        = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
757                                      TemplateId->TemplateNameLoc,
758                                      TemplateId->LAngleLoc,
759                                      TemplateArgsPtr,
760                                      TemplateId->RAngleLoc);
761
762      TypeResult = Actions.ActOnTagTemplateIdType(TypeResult, TUK,
763                                                  TagType, StartLoc);
764    } else {
765      // This is an explicit specialization or a class template
766      // partial specialization.
767      TemplateParameterLists FakedParamLists;
768
769      if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
770        // This looks like an explicit instantiation, because we have
771        // something like
772        //
773        //   template class Foo<X>
774        //
775        // but it actually has a definition. Most likely, this was
776        // meant to be an explicit specialization, but the user forgot
777        // the '<>' after 'template'.
778        assert(TUK == Action::TUK_Definition && "Expected a definition here");
779
780        SourceLocation LAngleLoc
781          = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
782        Diag(TemplateId->TemplateNameLoc,
783             diag::err_explicit_instantiation_with_definition)
784          << SourceRange(TemplateInfo.TemplateLoc)
785          << CodeModificationHint::CreateInsertion(LAngleLoc, "<>");
786
787        // Create a fake template parameter list that contains only
788        // "template<>", so that we treat this construct as a class
789        // template specialization.
790        FakedParamLists.push_back(
791          Actions.ActOnTemplateParameterList(0, SourceLocation(),
792                                             TemplateInfo.TemplateLoc,
793                                             LAngleLoc,
794                                             0, 0,
795                                             LAngleLoc));
796        TemplateParams = &FakedParamLists;
797      }
798
799      // Build the class template specialization.
800      TagOrTempResult
801        = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TUK,
802                       StartLoc, SS,
803                       TemplateTy::make(TemplateId->Template),
804                       TemplateId->TemplateNameLoc,
805                       TemplateId->LAngleLoc,
806                       TemplateArgsPtr,
807                       TemplateId->RAngleLoc,
808                       AttrList,
809                       Action::MultiTemplateParamsArg(Actions,
810                                    TemplateParams? &(*TemplateParams)[0] : 0,
811                                 TemplateParams? TemplateParams->size() : 0));
812    }
813    TemplateId->Destroy();
814  } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
815             TUK == Action::TUK_Declaration) {
816    // Explicit instantiation of a member of a class template
817    // specialization, e.g.,
818    //
819    //   template struct Outer<int>::Inner;
820    //
821    TagOrTempResult
822      = Actions.ActOnExplicitInstantiation(CurScope,
823                                           TemplateInfo.ExternLoc,
824                                           TemplateInfo.TemplateLoc,
825                                           TagType, StartLoc, SS, Name,
826                                           NameLoc, AttrList);
827  } else {
828    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
829        TUK == Action::TUK_Definition) {
830      // FIXME: Diagnose this particular error.
831    }
832
833    bool IsDependent = false;
834
835    // Declaration or definition of a class type
836    TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TUK, StartLoc, SS,
837                                       Name, NameLoc, AttrList, AS,
838                                  Action::MultiTemplateParamsArg(Actions,
839                                    TemplateParams? &(*TemplateParams)[0] : 0,
840                                    TemplateParams? TemplateParams->size() : 0),
841                                       Owned, IsDependent);
842
843    // If ActOnTag said the type was dependent, try again with the
844    // less common call.
845    if (IsDependent)
846      TypeResult = Actions.ActOnDependentTag(CurScope, TagType, TUK,
847                                             SS, Name, StartLoc, NameLoc);
848  }
849
850  // Parse the optional base clause (C++ only).
851  if (getLang().CPlusPlus && Tok.is(tok::colon))
852    ParseBaseClause(TagOrTempResult.get());
853
854  // If there is a body, parse it and inform the actions module.
855  if (Tok.is(tok::l_brace))
856    if (getLang().CPlusPlus)
857      ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
858    else
859      ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
860  else if (TUK == Action::TUK_Definition) {
861    // FIXME: Complain that we have a base-specifier list but no
862    // definition.
863    Diag(Tok, diag::err_expected_lbrace);
864  }
865
866  void *Result;
867  if (!TypeResult.isInvalid()) {
868    TagType = DeclSpec::TST_typename;
869    Result = TypeResult.get();
870    Owned = false;
871  } else if (!TagOrTempResult.isInvalid()) {
872    Result = TagOrTempResult.get().getAs<void>();
873  } else {
874    DS.SetTypeSpecError();
875    return;
876  }
877
878  const char *PrevSpec = 0;
879  unsigned DiagID;
880
881  if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, DiagID,
882                         Result, Owned))
883    Diag(StartLoc, DiagID) << PrevSpec;
884}
885
886/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
887///
888///       base-clause : [C++ class.derived]
889///         ':' base-specifier-list
890///       base-specifier-list:
891///         base-specifier '...'[opt]
892///         base-specifier-list ',' base-specifier '...'[opt]
893void Parser::ParseBaseClause(DeclPtrTy ClassDecl) {
894  assert(Tok.is(tok::colon) && "Not a base clause");
895  ConsumeToken();
896
897  // Build up an array of parsed base specifiers.
898  llvm::SmallVector<BaseTy *, 8> BaseInfo;
899
900  while (true) {
901    // Parse a base-specifier.
902    BaseResult Result = ParseBaseSpecifier(ClassDecl);
903    if (Result.isInvalid()) {
904      // Skip the rest of this base specifier, up until the comma or
905      // opening brace.
906      SkipUntil(tok::comma, tok::l_brace, true, true);
907    } else {
908      // Add this to our array of base specifiers.
909      BaseInfo.push_back(Result.get());
910    }
911
912    // If the next token is a comma, consume it and keep reading
913    // base-specifiers.
914    if (Tok.isNot(tok::comma)) break;
915
916    // Consume the comma.
917    ConsumeToken();
918  }
919
920  // Attach the base specifiers
921  Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
922}
923
924/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
925/// one entry in the base class list of a class specifier, for example:
926///    class foo : public bar, virtual private baz {
927/// 'public bar' and 'virtual private baz' are each base-specifiers.
928///
929///       base-specifier: [C++ class.derived]
930///         ::[opt] nested-name-specifier[opt] class-name
931///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
932///                        class-name
933///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
934///                        class-name
935Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) {
936  bool IsVirtual = false;
937  SourceLocation StartLoc = Tok.getLocation();
938
939  // Parse the 'virtual' keyword.
940  if (Tok.is(tok::kw_virtual))  {
941    ConsumeToken();
942    IsVirtual = true;
943  }
944
945  // Parse an (optional) access specifier.
946  AccessSpecifier Access = getAccessSpecifierIfPresent();
947  if (Access)
948    ConsumeToken();
949
950  // Parse the 'virtual' keyword (again!), in case it came after the
951  // access specifier.
952  if (Tok.is(tok::kw_virtual))  {
953    SourceLocation VirtualLoc = ConsumeToken();
954    if (IsVirtual) {
955      // Complain about duplicate 'virtual'
956      Diag(VirtualLoc, diag::err_dup_virtual)
957        << CodeModificationHint::CreateRemoval(VirtualLoc);
958    }
959
960    IsVirtual = true;
961  }
962
963  // Parse optional '::' and optional nested-name-specifier.
964  CXXScopeSpec SS;
965  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true);
966
967  // The location of the base class itself.
968  SourceLocation BaseLoc = Tok.getLocation();
969
970  // Parse the class-name.
971  SourceLocation EndLocation;
972  TypeResult BaseType = ParseClassName(EndLocation, &SS);
973  if (BaseType.isInvalid())
974    return true;
975
976  // Find the complete source range for the base-specifier.
977  SourceRange Range(StartLoc, EndLocation);
978
979  // Notify semantic analysis that we have parsed a complete
980  // base-specifier.
981  return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
982                                    BaseType.get(), BaseLoc);
983}
984
985/// getAccessSpecifierIfPresent - Determine whether the next token is
986/// a C++ access-specifier.
987///
988///       access-specifier: [C++ class.derived]
989///         'private'
990///         'protected'
991///         'public'
992AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
993  switch (Tok.getKind()) {
994  default: return AS_none;
995  case tok::kw_private: return AS_private;
996  case tok::kw_protected: return AS_protected;
997  case tok::kw_public: return AS_public;
998  }
999}
1000
1001void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo,
1002                                             DeclPtrTy ThisDecl) {
1003  // We just declared a member function. If this member function
1004  // has any default arguments, we'll need to parse them later.
1005  LateParsedMethodDeclaration *LateMethod = 0;
1006  DeclaratorChunk::FunctionTypeInfo &FTI
1007    = DeclaratorInfo.getTypeObject(0).Fun;
1008  for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1009    if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1010      if (!LateMethod) {
1011        // Push this method onto the stack of late-parsed method
1012        // declarations.
1013        getCurrentClass().MethodDecls.push_back(
1014                                LateParsedMethodDeclaration(ThisDecl));
1015        LateMethod = &getCurrentClass().MethodDecls.back();
1016        LateMethod->TemplateScope = CurScope->isTemplateParamScope();
1017
1018        // Add all of the parameters prior to this one (they don't
1019        // have default arguments).
1020        LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1021        for (unsigned I = 0; I < ParamIdx; ++I)
1022          LateMethod->DefaultArgs.push_back(
1023                    LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param));
1024      }
1025
1026      // Add this parameter to the list of parameters (it or may
1027      // not have a default argument).
1028      LateMethod->DefaultArgs.push_back(
1029        LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1030                                  FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1031    }
1032  }
1033}
1034
1035/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1036///
1037///       member-declaration:
1038///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
1039///         function-definition ';'[opt]
1040///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1041///         using-declaration                                            [TODO]
1042/// [C++0x] static_assert-declaration
1043///         template-declaration
1044/// [GNU]   '__extension__' member-declaration
1045///
1046///       member-declarator-list:
1047///         member-declarator
1048///         member-declarator-list ',' member-declarator
1049///
1050///       member-declarator:
1051///         declarator pure-specifier[opt]
1052///         declarator constant-initializer[opt]
1053///         identifier[opt] ':' constant-expression
1054///
1055///       pure-specifier:
1056///         '= 0'
1057///
1058///       constant-initializer:
1059///         '=' constant-expression
1060///
1061void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1062                                       const ParsedTemplateInfo &TemplateInfo) {
1063  // static_assert-declaration
1064  if (Tok.is(tok::kw_static_assert)) {
1065    // FIXME: Check for templates
1066    SourceLocation DeclEnd;
1067    ParseStaticAssertDeclaration(DeclEnd);
1068    return;
1069  }
1070
1071  if (Tok.is(tok::kw_template)) {
1072    assert(!TemplateInfo.TemplateParams &&
1073           "Nested template improperly parsed?");
1074    SourceLocation DeclEnd;
1075    ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
1076                                         AS);
1077    return;
1078  }
1079
1080  // Handle:  member-declaration ::= '__extension__' member-declaration
1081  if (Tok.is(tok::kw___extension__)) {
1082    // __extension__ silences extension warnings in the subexpression.
1083    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1084    ConsumeToken();
1085    return ParseCXXClassMemberDeclaration(AS, TemplateInfo);
1086  }
1087
1088  CXX0XAttributeList AttrList;
1089  // Optional C++0x attribute-specifier
1090  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
1091    AttrList = ParseCXX0XAttributes();
1092  }
1093
1094  if (Tok.is(tok::kw_using)) {
1095    // FIXME: Check for template aliases
1096
1097    if (AttrList.HasAttr)
1098      Diag(AttrList.Range.getBegin(), diag::err_attributes_not_allowed)
1099        << AttrList.Range;
1100
1101    // Eat 'using'.
1102    SourceLocation UsingLoc = ConsumeToken();
1103
1104    if (Tok.is(tok::kw_namespace)) {
1105      Diag(UsingLoc, diag::err_using_namespace_in_class);
1106      SkipUntil(tok::semi, true, true);
1107    }
1108    else {
1109      SourceLocation DeclEnd;
1110      // Otherwise, it must be using-declaration.
1111      ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd, AS);
1112    }
1113    return;
1114  }
1115
1116  SourceLocation DSStart = Tok.getLocation();
1117  // decl-specifier-seq:
1118  // Parse the common declaration-specifiers piece.
1119  ParsingDeclSpec DS(*this);
1120  DS.AddAttributes(AttrList.AttrList);
1121  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class);
1122
1123  Action::MultiTemplateParamsArg TemplateParams(Actions,
1124      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
1125      TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
1126
1127  if (Tok.is(tok::semi)) {
1128    ConsumeToken();
1129    Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
1130    return;
1131  }
1132
1133  ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
1134
1135  if (Tok.isNot(tok::colon)) {
1136    // Parse the first declarator.
1137    ParseDeclarator(DeclaratorInfo);
1138    // Error parsing the declarator?
1139    if (!DeclaratorInfo.hasName()) {
1140      // If so, skip until the semi-colon or a }.
1141      SkipUntil(tok::r_brace, true);
1142      if (Tok.is(tok::semi))
1143        ConsumeToken();
1144      return;
1145    }
1146
1147    // If attributes exist after the declarator, but before an '{', parse them.
1148    if (Tok.is(tok::kw___attribute)) {
1149      SourceLocation Loc;
1150      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1151      DeclaratorInfo.AddAttributes(AttrList, Loc);
1152    }
1153
1154    // function-definition:
1155    if (Tok.is(tok::l_brace)
1156        || (DeclaratorInfo.isFunctionDeclarator() &&
1157            (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) {
1158      if (!DeclaratorInfo.isFunctionDeclarator()) {
1159        Diag(Tok, diag::err_func_def_no_params);
1160        ConsumeBrace();
1161        SkipUntil(tok::r_brace, true);
1162        return;
1163      }
1164
1165      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1166        Diag(Tok, diag::err_function_declared_typedef);
1167        // This recovery skips the entire function body. It would be nice
1168        // to simply call ParseCXXInlineMethodDef() below, however Sema
1169        // assumes the declarator represents a function, not a typedef.
1170        ConsumeBrace();
1171        SkipUntil(tok::r_brace, true);
1172        return;
1173      }
1174
1175      ParseCXXInlineMethodDef(AS, DeclaratorInfo, TemplateInfo);
1176      return;
1177    }
1178  }
1179
1180  // member-declarator-list:
1181  //   member-declarator
1182  //   member-declarator-list ',' member-declarator
1183
1184  llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup;
1185  OwningExprResult BitfieldSize(Actions);
1186  OwningExprResult Init(Actions);
1187  bool Deleted = false;
1188
1189  while (1) {
1190    // member-declarator:
1191    //   declarator pure-specifier[opt]
1192    //   declarator constant-initializer[opt]
1193    //   identifier[opt] ':' constant-expression
1194
1195    if (Tok.is(tok::colon)) {
1196      ConsumeToken();
1197      BitfieldSize = ParseConstantExpression();
1198      if (BitfieldSize.isInvalid())
1199        SkipUntil(tok::comma, true, true);
1200    }
1201
1202    // pure-specifier:
1203    //   '= 0'
1204    //
1205    // constant-initializer:
1206    //   '=' constant-expression
1207    //
1208    // defaulted/deleted function-definition:
1209    //   '=' 'default'                          [TODO]
1210    //   '=' 'delete'
1211
1212    if (Tok.is(tok::equal)) {
1213      ConsumeToken();
1214      if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) {
1215        ConsumeToken();
1216        Deleted = true;
1217      } else {
1218        Init = ParseInitializer();
1219        if (Init.isInvalid())
1220          SkipUntil(tok::comma, true, true);
1221      }
1222    }
1223
1224    // If attributes exist after the declarator, parse them.
1225    if (Tok.is(tok::kw___attribute)) {
1226      SourceLocation Loc;
1227      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1228      DeclaratorInfo.AddAttributes(AttrList, Loc);
1229    }
1230
1231    // NOTE: If Sema is the Action module and declarator is an instance field,
1232    // this call will *not* return the created decl; It will return null.
1233    // See Sema::ActOnCXXMemberDeclarator for details.
1234
1235    DeclPtrTy ThisDecl;
1236    if (DS.isFriendSpecified()) {
1237      // TODO: handle initializers, bitfields, 'delete'
1238      ThisDecl = Actions.ActOnFriendFunctionDecl(CurScope, DeclaratorInfo,
1239                                                 /*IsDefinition*/ false,
1240                                                 move(TemplateParams));
1241    } else {
1242      ThisDecl = Actions.ActOnCXXMemberDeclarator(CurScope, AS,
1243                                                  DeclaratorInfo,
1244                                                  move(TemplateParams),
1245                                                  BitfieldSize.release(),
1246                                                  Init.release(),
1247                                                  /*IsDefinition*/Deleted,
1248                                                  Deleted);
1249    }
1250    if (ThisDecl)
1251      DeclsInGroup.push_back(ThisDecl);
1252
1253    if (DeclaratorInfo.isFunctionDeclarator() &&
1254        DeclaratorInfo.getDeclSpec().getStorageClassSpec()
1255          != DeclSpec::SCS_typedef) {
1256      HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl);
1257    }
1258
1259    DeclaratorInfo.complete(ThisDecl);
1260
1261    // If we don't have a comma, it is either the end of the list (a ';')
1262    // or an error, bail out.
1263    if (Tok.isNot(tok::comma))
1264      break;
1265
1266    // Consume the comma.
1267    ConsumeToken();
1268
1269    // Parse the next declarator.
1270    DeclaratorInfo.clear();
1271    BitfieldSize = 0;
1272    Init = 0;
1273    Deleted = false;
1274
1275    // Attributes are only allowed on the second declarator.
1276    if (Tok.is(tok::kw___attribute)) {
1277      SourceLocation Loc;
1278      AttributeList *AttrList = ParseGNUAttributes(&Loc);
1279      DeclaratorInfo.AddAttributes(AttrList, Loc);
1280    }
1281
1282    if (Tok.isNot(tok::colon))
1283      ParseDeclarator(DeclaratorInfo);
1284  }
1285
1286  if (Tok.is(tok::semi)) {
1287    ConsumeToken();
1288    Actions.FinalizeDeclaratorGroup(CurScope, DS, DeclsInGroup.data(),
1289                                    DeclsInGroup.size());
1290    return;
1291  }
1292
1293  Diag(Tok, diag::err_expected_semi_decl_list);
1294  // Skip to end of block or statement
1295  SkipUntil(tok::r_brace, true, true);
1296  if (Tok.is(tok::semi))
1297    ConsumeToken();
1298  return;
1299}
1300
1301/// ParseCXXMemberSpecification - Parse the class definition.
1302///
1303///       member-specification:
1304///         member-declaration member-specification[opt]
1305///         access-specifier ':' member-specification[opt]
1306///
1307void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
1308                                         unsigned TagType, DeclPtrTy TagDecl) {
1309  assert((TagType == DeclSpec::TST_struct ||
1310         TagType == DeclSpec::TST_union  ||
1311         TagType == DeclSpec::TST_class) && "Invalid TagType!");
1312
1313  PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions,
1314                                        PP.getSourceManager(),
1315                                        "parsing struct/union/class body");
1316
1317  SourceLocation LBraceLoc = ConsumeBrace();
1318
1319  // Determine whether this is a top-level (non-nested) class.
1320  bool TopLevelClass = ClassStack.empty() ||
1321    CurScope->isInCXXInlineMethodScope();
1322
1323  // Enter a scope for the class.
1324  ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
1325
1326  // Note that we are parsing a new (potentially-nested) class definition.
1327  ParsingClassDefinition ParsingDef(*this, TagDecl, TopLevelClass);
1328
1329  if (TagDecl)
1330    Actions.ActOnTagStartDefinition(CurScope, TagDecl);
1331  else {
1332    SkipUntil(tok::r_brace, false, false);
1333    return;
1334  }
1335
1336  // C++ 11p3: Members of a class defined with the keyword class are private
1337  // by default. Members of a class defined with the keywords struct or union
1338  // are public by default.
1339  AccessSpecifier CurAS;
1340  if (TagType == DeclSpec::TST_class)
1341    CurAS = AS_private;
1342  else
1343    CurAS = AS_public;
1344
1345  // While we still have something to read, read the member-declarations.
1346  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1347    // Each iteration of this loop reads one member-declaration.
1348
1349    // Check for extraneous top-level semicolon.
1350    if (Tok.is(tok::semi)) {
1351      Diag(Tok, diag::ext_extra_struct_semi)
1352        << CodeModificationHint::CreateRemoval(Tok.getLocation());
1353      ConsumeToken();
1354      continue;
1355    }
1356
1357    AccessSpecifier AS = getAccessSpecifierIfPresent();
1358    if (AS != AS_none) {
1359      // Current token is a C++ access specifier.
1360      CurAS = AS;
1361      ConsumeToken();
1362      ExpectAndConsume(tok::colon, diag::err_expected_colon);
1363      continue;
1364    }
1365
1366    // FIXME: Make sure we don't have a template here.
1367
1368    // Parse all the comma separated declarators.
1369    ParseCXXClassMemberDeclaration(CurAS);
1370  }
1371
1372  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1373
1374  AttributeList *AttrList = 0;
1375  // If attributes exist after class contents, parse them.
1376  if (Tok.is(tok::kw___attribute))
1377    AttrList = ParseGNUAttributes(); // FIXME: where should I put them?
1378
1379  Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl,
1380                                            LBraceLoc, RBraceLoc);
1381
1382  // C++ 9.2p2: Within the class member-specification, the class is regarded as
1383  // complete within function bodies, default arguments,
1384  // exception-specifications, and constructor ctor-initializers (including
1385  // such things in nested classes).
1386  //
1387  // FIXME: Only function bodies and constructor ctor-initializers are
1388  // parsed correctly, fix the rest.
1389  if (TopLevelClass) {
1390    // We are not inside a nested class. This class and its nested classes
1391    // are complete and we can parse the delayed portions of method
1392    // declarations and the lexed inline method definitions.
1393    ParseLexedMethodDeclarations(getCurrentClass());
1394    ParseLexedMethodDefs(getCurrentClass());
1395  }
1396
1397  // Leave the class scope.
1398  ParsingDef.Pop();
1399  ClassScope.Exit();
1400
1401  Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc);
1402}
1403
1404/// ParseConstructorInitializer - Parse a C++ constructor initializer,
1405/// which explicitly initializes the members or base classes of a
1406/// class (C++ [class.base.init]). For example, the three initializers
1407/// after the ':' in the Derived constructor below:
1408///
1409/// @code
1410/// class Base { };
1411/// class Derived : Base {
1412///   int x;
1413///   float f;
1414/// public:
1415///   Derived(float f) : Base(), x(17), f(f) { }
1416/// };
1417/// @endcode
1418///
1419/// [C++]  ctor-initializer:
1420///          ':' mem-initializer-list
1421///
1422/// [C++]  mem-initializer-list:
1423///          mem-initializer
1424///          mem-initializer , mem-initializer-list
1425void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) {
1426  assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
1427
1428  SourceLocation ColonLoc = ConsumeToken();
1429
1430  llvm::SmallVector<MemInitTy*, 4> MemInitializers;
1431
1432  do {
1433    MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
1434    if (!MemInit.isInvalid())
1435      MemInitializers.push_back(MemInit.get());
1436
1437    if (Tok.is(tok::comma))
1438      ConsumeToken();
1439    else if (Tok.is(tok::l_brace))
1440      break;
1441    else {
1442      // Skip over garbage, until we get to '{'.  Don't eat the '{'.
1443      Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
1444      SkipUntil(tok::l_brace, true, true);
1445      break;
1446    }
1447  } while (true);
1448
1449  Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
1450                               MemInitializers.data(), MemInitializers.size());
1451}
1452
1453/// ParseMemInitializer - Parse a C++ member initializer, which is
1454/// part of a constructor initializer that explicitly initializes one
1455/// member or base class (C++ [class.base.init]). See
1456/// ParseConstructorInitializer for an example.
1457///
1458/// [C++] mem-initializer:
1459///         mem-initializer-id '(' expression-list[opt] ')'
1460///
1461/// [C++] mem-initializer-id:
1462///         '::'[opt] nested-name-specifier[opt] class-name
1463///         identifier
1464Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) {
1465  // parse '::'[opt] nested-name-specifier[opt]
1466  CXXScopeSpec SS;
1467  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false);
1468  TypeTy *TemplateTypeTy = 0;
1469  if (Tok.is(tok::annot_template_id)) {
1470    TemplateIdAnnotation *TemplateId
1471      = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1472    if (TemplateId->Kind == TNK_Type_template) {
1473      AnnotateTemplateIdTokenAsType(&SS);
1474      assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1475      TemplateTypeTy = Tok.getAnnotationValue();
1476    }
1477    // FIXME. May need to check for TNK_Dependent_template as well.
1478  }
1479  if (!TemplateTypeTy && Tok.isNot(tok::identifier)) {
1480    Diag(Tok, diag::err_expected_member_or_base_name);
1481    return true;
1482  }
1483
1484  // Get the identifier. This may be a member name or a class name,
1485  // but we'll let the semantic analysis determine which it is.
1486  IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0;
1487  SourceLocation IdLoc = ConsumeToken();
1488
1489  // Parse the '('.
1490  if (Tok.isNot(tok::l_paren)) {
1491    Diag(Tok, diag::err_expected_lparen);
1492    return true;
1493  }
1494  SourceLocation LParenLoc = ConsumeParen();
1495
1496  // Parse the optional expression-list.
1497  ExprVector ArgExprs(Actions);
1498  CommaLocsTy CommaLocs;
1499  if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
1500    SkipUntil(tok::r_paren);
1501    return true;
1502  }
1503
1504  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1505
1506  return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, SS, II,
1507                                     TemplateTypeTy, IdLoc,
1508                                     LParenLoc, ArgExprs.take(),
1509                                     ArgExprs.size(), CommaLocs.data(),
1510                                     RParenLoc);
1511}
1512
1513/// ParseExceptionSpecification - Parse a C++ exception-specification
1514/// (C++ [except.spec]).
1515///
1516///       exception-specification:
1517///         'throw' '(' type-id-list [opt] ')'
1518/// [MS]    'throw' '(' '...' ')'
1519///
1520///       type-id-list:
1521///         type-id
1522///         type-id-list ',' type-id
1523///
1524bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc,
1525                                         llvm::SmallVector<TypeTy*, 2>
1526                                             &Exceptions,
1527                                         llvm::SmallVector<SourceRange, 2>
1528                                             &Ranges,
1529                                         bool &hasAnyExceptionSpec) {
1530  assert(Tok.is(tok::kw_throw) && "expected throw");
1531
1532  SourceLocation ThrowLoc = ConsumeToken();
1533
1534  if (!Tok.is(tok::l_paren)) {
1535    return Diag(Tok, diag::err_expected_lparen_after) << "throw";
1536  }
1537  SourceLocation LParenLoc = ConsumeParen();
1538
1539  // Parse throw(...), a Microsoft extension that means "this function
1540  // can throw anything".
1541  if (Tok.is(tok::ellipsis)) {
1542    hasAnyExceptionSpec = true;
1543    SourceLocation EllipsisLoc = ConsumeToken();
1544    if (!getLang().Microsoft)
1545      Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
1546    EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1547    return false;
1548  }
1549
1550  // Parse the sequence of type-ids.
1551  SourceRange Range;
1552  while (Tok.isNot(tok::r_paren)) {
1553    TypeResult Res(ParseTypeName(&Range));
1554    if (!Res.isInvalid()) {
1555      Exceptions.push_back(Res.get());
1556      Ranges.push_back(Range);
1557    }
1558    if (Tok.is(tok::comma))
1559      ConsumeToken();
1560    else
1561      break;
1562  }
1563
1564  EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
1565  return false;
1566}
1567
1568/// \brief We have just started parsing the definition of a new class,
1569/// so push that class onto our stack of classes that is currently
1570/// being parsed.
1571void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool TopLevelClass) {
1572  assert((TopLevelClass || !ClassStack.empty()) &&
1573         "Nested class without outer class");
1574  ClassStack.push(new ParsingClass(ClassDecl, TopLevelClass));
1575}
1576
1577/// \brief Deallocate the given parsed class and all of its nested
1578/// classes.
1579void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
1580  for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I)
1581    DeallocateParsedClasses(Class->NestedClasses[I]);
1582  delete Class;
1583}
1584
1585/// \brief Pop the top class of the stack of classes that are
1586/// currently being parsed.
1587///
1588/// This routine should be called when we have finished parsing the
1589/// definition of a class, but have not yet popped the Scope
1590/// associated with the class's definition.
1591///
1592/// \returns true if the class we've popped is a top-level class,
1593/// false otherwise.
1594void Parser::PopParsingClass() {
1595  assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
1596
1597  ParsingClass *Victim = ClassStack.top();
1598  ClassStack.pop();
1599  if (Victim->TopLevelClass) {
1600    // Deallocate all of the nested classes of this class,
1601    // recursively: we don't need to keep any of this information.
1602    DeallocateParsedClasses(Victim);
1603    return;
1604  }
1605  assert(!ClassStack.empty() && "Missing top-level class?");
1606
1607  if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() &&
1608      Victim->NestedClasses.empty()) {
1609    // The victim is a nested class, but we will not need to perform
1610    // any processing after the definition of this class since it has
1611    // no members whose handling was delayed. Therefore, we can just
1612    // remove this nested class.
1613    delete Victim;
1614    return;
1615  }
1616
1617  // This nested class has some members that will need to be processed
1618  // after the top-level class is completely defined. Therefore, add
1619  // it to the list of nested classes within its parent.
1620  assert(CurScope->isClassScope() && "Nested class outside of class scope?");
1621  ClassStack.top()->NestedClasses.push_back(Victim);
1622  Victim->TemplateScope = CurScope->getParent()->isTemplateParamScope();
1623}
1624
1625/// ParseCXX0XAttributes - Parse a C++0x attribute-specifier. Currently only
1626/// parses standard attributes.
1627///
1628/// [C++0x] attribute-specifier:
1629///         '[' '[' attribute-list ']' ']'
1630///
1631/// [C++0x] attribute-list:
1632///         attribute[opt]
1633///         attribute-list ',' attribute[opt]
1634///
1635/// [C++0x] attribute:
1636///         attribute-token attribute-argument-clause[opt]
1637///
1638/// [C++0x] attribute-token:
1639///         identifier
1640///         attribute-scoped-token
1641///
1642/// [C++0x] attribute-scoped-token:
1643///         attribute-namespace '::' identifier
1644///
1645/// [C++0x] attribute-namespace:
1646///         identifier
1647///
1648/// [C++0x] attribute-argument-clause:
1649///         '(' balanced-token-seq ')'
1650///
1651/// [C++0x] balanced-token-seq:
1652///         balanced-token
1653///         balanced-token-seq balanced-token
1654///
1655/// [C++0x] balanced-token:
1656///         '(' balanced-token-seq ')'
1657///         '[' balanced-token-seq ']'
1658///         '{' balanced-token-seq '}'
1659///         any token but '(', ')', '[', ']', '{', or '}'
1660CXX0XAttributeList Parser::ParseCXX0XAttributes(SourceLocation *EndLoc) {
1661  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
1662      && "Not a C++0x attribute list");
1663
1664  SourceLocation StartLoc = Tok.getLocation(), Loc;
1665  AttributeList *CurrAttr = 0;
1666
1667  ConsumeBracket();
1668  ConsumeBracket();
1669
1670  if (Tok.is(tok::comma)) {
1671    Diag(Tok.getLocation(), diag::err_expected_ident);
1672    ConsumeToken();
1673  }
1674
1675  while (Tok.is(tok::identifier) || Tok.is(tok::comma)) {
1676    // attribute not present
1677    if (Tok.is(tok::comma)) {
1678      ConsumeToken();
1679      continue;
1680    }
1681
1682    IdentifierInfo *ScopeName = 0, *AttrName = Tok.getIdentifierInfo();
1683    SourceLocation ScopeLoc, AttrLoc = ConsumeToken();
1684
1685    // scoped attribute
1686    if (Tok.is(tok::coloncolon)) {
1687      ConsumeToken();
1688
1689      if (!Tok.is(tok::identifier)) {
1690        Diag(Tok.getLocation(), diag::err_expected_ident);
1691        SkipUntil(tok::r_square, tok::comma, true, true);
1692        continue;
1693      }
1694
1695      ScopeName = AttrName;
1696      ScopeLoc = AttrLoc;
1697
1698      AttrName = Tok.getIdentifierInfo();
1699      AttrLoc = ConsumeToken();
1700    }
1701
1702    bool AttrParsed = false;
1703    // No scoped names are supported; ideally we could put all non-standard
1704    // attributes into namespaces.
1705    if (!ScopeName) {
1706      switch(AttributeList::getKind(AttrName))
1707      {
1708      // No arguments
1709      case AttributeList::AT_base_check:
1710      case AttributeList::AT_carries_dependency:
1711      case AttributeList::AT_final:
1712      case AttributeList::AT_hiding:
1713      case AttributeList::AT_noreturn:
1714      case AttributeList::AT_override: {
1715        if (Tok.is(tok::l_paren)) {
1716          Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_arguments)
1717            << AttrName->getName();
1718          break;
1719        }
1720
1721        CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc, 0,
1722                                     SourceLocation(), 0, 0, CurrAttr, false,
1723                                     true);
1724        AttrParsed = true;
1725        break;
1726      }
1727
1728      // One argument; must be a type-id or assignment-expression
1729      case AttributeList::AT_aligned: {
1730        if (Tok.isNot(tok::l_paren)) {
1731          Diag(Tok.getLocation(), diag::err_cxx0x_attribute_requires_arguments)
1732            << AttrName->getName();
1733          break;
1734        }
1735        SourceLocation ParamLoc = ConsumeParen();
1736
1737        OwningExprResult ArgExpr = ParseCXX0XAlignArgument(ParamLoc);
1738
1739        MatchRHSPunctuation(tok::r_paren, ParamLoc);
1740
1741        ExprVector ArgExprs(Actions);
1742        ArgExprs.push_back(ArgExpr.release());
1743        CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc,
1744                                     0, ParamLoc, ArgExprs.take(), 1, CurrAttr,
1745                                     false, true);
1746
1747        AttrParsed = true;
1748        break;
1749      }
1750
1751      // Silence warnings
1752      default: break;
1753      }
1754    }
1755
1756    // Skip the entire parameter clause, if any
1757    if (!AttrParsed && Tok.is(tok::l_paren)) {
1758      ConsumeParen();
1759      // SkipUntil maintains the balancedness of tokens.
1760      SkipUntil(tok::r_paren, false);
1761    }
1762  }
1763
1764  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
1765    SkipUntil(tok::r_square, false);
1766  Loc = Tok.getLocation();
1767  if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
1768    SkipUntil(tok::r_square, false);
1769
1770  CXX0XAttributeList Attr (CurrAttr, SourceRange(StartLoc, Loc), true);
1771  return Attr;
1772}
1773
1774/// ParseCXX0XAlignArgument - Parse the argument to C++0x's [[align]]
1775/// attribute.
1776///
1777/// FIXME: Simply returns an alignof() expression if the argument is a
1778/// type. Ideally, the type should be propagated directly into Sema.
1779///
1780/// [C++0x] 'align' '(' type-id ')'
1781/// [C++0x] 'align' '(' assignment-expression ')'
1782Parser::OwningExprResult Parser::ParseCXX0XAlignArgument(SourceLocation Start) {
1783  if (isTypeIdInParens()) {
1784    EnterExpressionEvaluationContext Unevaluated(Actions,
1785                                                  Action::Unevaluated);
1786    SourceLocation TypeLoc = Tok.getLocation();
1787    TypeTy *Ty = ParseTypeName().get();
1788    SourceRange TypeRange(Start, Tok.getLocation());
1789    return Actions.ActOnSizeOfAlignOfExpr(TypeLoc, false, true, Ty,
1790                                              TypeRange);
1791  } else
1792    return ParseConstantExpression();
1793}
1794