]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / Parse / ParseDeclCXX.cpp
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/Sema/DeclSpec.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ParsedTemplate.h"
20 #include "clang/Sema/PrettyDeclStackTrace.h"
21 #include "clang/Sema/SemaDiagnostic.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "RAIIObjectsForParser.h"
24 using namespace clang;
25
26 /// ParseNamespace - We know that the current token is a namespace keyword. This
27 /// may either be a top level namespace or a block-level namespace alias. If
28 /// there was an inline keyword, it has already been parsed.
29 ///
30 ///       namespace-definition: [C++ 7.3: basic.namespace]
31 ///         named-namespace-definition
32 ///         unnamed-namespace-definition
33 ///
34 ///       unnamed-namespace-definition:
35 ///         'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
36 ///
37 ///       named-namespace-definition:
38 ///         original-namespace-definition
39 ///         extension-namespace-definition
40 ///
41 ///       original-namespace-definition:
42 ///         'inline'[opt] 'namespace' identifier attributes[opt]
43 ///             '{' namespace-body '}'
44 ///
45 ///       extension-namespace-definition:
46 ///         'inline'[opt] 'namespace' original-namespace-name
47 ///             '{' namespace-body '}'
48 ///
49 ///       namespace-alias-definition:  [C++ 7.3.2: namespace.alias]
50 ///         'namespace' identifier '=' qualified-namespace-specifier ';'
51 ///
52 Decl *Parser::ParseNamespace(unsigned Context,
53                              SourceLocation &DeclEnd,
54                              SourceLocation InlineLoc) {
55   assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
56   SourceLocation NamespaceLoc = ConsumeToken();  // eat the 'namespace'.
57   ObjCDeclContextSwitch ObjCDC(*this);
58     
59   if (Tok.is(tok::code_completion)) {
60     Actions.CodeCompleteNamespaceDecl(getCurScope());
61     cutOffParsing();
62     return 0;
63   }
64
65   SourceLocation IdentLoc;
66   IdentifierInfo *Ident = 0;
67   std::vector<SourceLocation> ExtraIdentLoc;
68   std::vector<IdentifierInfo*> ExtraIdent;
69   std::vector<SourceLocation> ExtraNamespaceLoc;
70
71   Token attrTok;
72
73   if (Tok.is(tok::identifier)) {
74     Ident = Tok.getIdentifierInfo();
75     IdentLoc = ConsumeToken();  // eat the identifier.
76     while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
77       ExtraNamespaceLoc.push_back(ConsumeToken());
78       ExtraIdent.push_back(Tok.getIdentifierInfo());
79       ExtraIdentLoc.push_back(ConsumeToken());
80     }
81   }
82
83   // Read label attributes, if present.
84   ParsedAttributes attrs(AttrFactory);
85   if (Tok.is(tok::kw___attribute)) {
86     attrTok = Tok;
87     ParseGNUAttributes(attrs);
88   }
89
90   if (Tok.is(tok::equal)) {
91     if (Ident == 0) {
92       Diag(Tok, diag::err_expected_ident);
93       // Skip to end of the definition and eat the ';'.
94       SkipUntil(tok::semi);
95       return 0;
96     }
97     if (!attrs.empty())
98       Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
99     if (InlineLoc.isValid())
100       Diag(InlineLoc, diag::err_inline_namespace_alias)
101           << FixItHint::CreateRemoval(InlineLoc);
102     return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
103   }
104
105
106   BalancedDelimiterTracker T(*this, tok::l_brace);
107   if (T.consumeOpen()) {
108     if (!ExtraIdent.empty()) {
109       Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
110           << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
111     }
112     Diag(Tok, Ident ? diag::err_expected_lbrace :
113          diag::err_expected_ident_lbrace);
114     return 0;
115   }
116
117   if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || 
118       getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || 
119       getCurScope()->getFnParent()) {
120     if (!ExtraIdent.empty()) {
121       Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
122           << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
123     }
124     Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
125     SkipUntil(tok::r_brace, false);
126     return 0;
127   }
128
129   if (!ExtraIdent.empty()) {
130     TentativeParsingAction TPA(*this);
131     SkipUntil(tok::r_brace, /*StopAtSemi*/false, /*DontConsume*/true);
132     Token rBraceToken = Tok;
133     TPA.Revert();
134
135     if (!rBraceToken.is(tok::r_brace)) {
136       Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
137           << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
138     } else {
139       std::string NamespaceFix;
140       for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
141            E = ExtraIdent.end(); I != E; ++I) {
142         NamespaceFix += " { namespace ";
143         NamespaceFix += (*I)->getName();
144       }
145
146       std::string RBraces;
147       for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
148         RBraces +=  "} ";
149
150       Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
151           << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
152                                                       ExtraIdentLoc.back()),
153                                           NamespaceFix)
154           << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
155     }
156   }
157
158   // If we're still good, complain about inline namespaces in non-C++0x now.
159   if (InlineLoc.isValid())
160     Diag(InlineLoc, getLangOpts().CPlusPlus0x ?
161          diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
162
163   // Enter a scope for the namespace.
164   ParseScope NamespaceScope(this, Scope::DeclScope);
165
166   Decl *NamespcDecl =
167     Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
168                                    IdentLoc, Ident, T.getOpenLocation(), 
169                                    attrs.getList());
170
171   PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
172                                       "parsing namespace");
173
174   // Parse the contents of the namespace.  This includes parsing recovery on 
175   // any improperly nested namespaces.
176   ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
177                       InlineLoc, attrs, T);
178
179   // Leave the namespace scope.
180   NamespaceScope.Exit();
181
182   DeclEnd = T.getCloseLocation();
183   Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
184
185   return NamespcDecl;
186 }
187
188 /// ParseInnerNamespace - Parse the contents of a namespace.
189 void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
190                                  std::vector<IdentifierInfo*>& Ident,
191                                  std::vector<SourceLocation>& NamespaceLoc,
192                                  unsigned int index, SourceLocation& InlineLoc,
193                                  ParsedAttributes& attrs,
194                                  BalancedDelimiterTracker &Tracker) {
195   if (index == Ident.size()) {
196     while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
197       ParsedAttributesWithRange attrs(AttrFactory);
198       MaybeParseCXX0XAttributes(attrs);
199       MaybeParseMicrosoftAttributes(attrs);
200       ParseExternalDeclaration(attrs);
201     }
202
203     // The caller is what called check -- we are simply calling
204     // the close for it.
205     Tracker.consumeClose();
206
207     return;
208   }
209
210   // Parse improperly nested namespaces.
211   ParseScope NamespaceScope(this, Scope::DeclScope);
212   Decl *NamespcDecl =
213     Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
214                                    NamespaceLoc[index], IdentLoc[index],
215                                    Ident[index], Tracker.getOpenLocation(), 
216                                    attrs.getList());
217
218   ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
219                       attrs, Tracker);
220
221   NamespaceScope.Exit();
222
223   Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
224 }
225
226 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
227 /// alias definition.
228 ///
229 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
230                                   SourceLocation AliasLoc,
231                                   IdentifierInfo *Alias,
232                                   SourceLocation &DeclEnd) {
233   assert(Tok.is(tok::equal) && "Not equal token");
234
235   ConsumeToken(); // eat the '='.
236
237   if (Tok.is(tok::code_completion)) {
238     Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
239     cutOffParsing();
240     return 0;
241   }
242
243   CXXScopeSpec SS;
244   // Parse (optional) nested-name-specifier.
245   ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
246
247   if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
248     Diag(Tok, diag::err_expected_namespace_name);
249     // Skip to end of the definition and eat the ';'.
250     SkipUntil(tok::semi);
251     return 0;
252   }
253
254   // Parse identifier.
255   IdentifierInfo *Ident = Tok.getIdentifierInfo();
256   SourceLocation IdentLoc = ConsumeToken();
257
258   // Eat the ';'.
259   DeclEnd = Tok.getLocation();
260   ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
261                    "", tok::semi);
262
263   return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
264                                         SS, IdentLoc, Ident);
265 }
266
267 /// ParseLinkage - We know that the current token is a string_literal
268 /// and just before that, that extern was seen.
269 ///
270 ///       linkage-specification: [C++ 7.5p2: dcl.link]
271 ///         'extern' string-literal '{' declaration-seq[opt] '}'
272 ///         'extern' string-literal declaration
273 ///
274 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
275   assert(Tok.is(tok::string_literal) && "Not a string literal!");
276   SmallString<8> LangBuffer;
277   bool Invalid = false;
278   StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid);
279   if (Invalid)
280     return 0;
281
282   // FIXME: This is incorrect: linkage-specifiers are parsed in translation
283   // phase 7, so string-literal concatenation is supposed to occur.
284   //   extern "" "C" "" "+" "+" { } is legal.
285   if (Tok.hasUDSuffix())
286     Diag(Tok, diag::err_invalid_string_udl);
287   SourceLocation Loc = ConsumeStringToken();
288
289   ParseScope LinkageScope(this, Scope::DeclScope);
290   Decl *LinkageSpec
291     = Actions.ActOnStartLinkageSpecification(getCurScope(),
292                                              DS.getSourceRange().getBegin(),
293                                              Loc, Lang,
294                                       Tok.is(tok::l_brace) ? Tok.getLocation()
295                                                            : SourceLocation());
296
297   ParsedAttributesWithRange attrs(AttrFactory);
298   MaybeParseCXX0XAttributes(attrs);
299   MaybeParseMicrosoftAttributes(attrs);
300
301   if (Tok.isNot(tok::l_brace)) {
302     // Reset the source range in DS, as the leading "extern"
303     // does not really belong to the inner declaration ...
304     DS.SetRangeStart(SourceLocation());
305     DS.SetRangeEnd(SourceLocation());
306     // ... but anyway remember that such an "extern" was seen.
307     DS.setExternInLinkageSpec(true);
308     ParseExternalDeclaration(attrs, &DS);
309     return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
310                                                    SourceLocation());
311   }
312
313   DS.abort();
314
315   ProhibitAttributes(attrs);
316
317   BalancedDelimiterTracker T(*this, tok::l_brace);
318   T.consumeOpen();
319   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
320     ParsedAttributesWithRange attrs(AttrFactory);
321     MaybeParseCXX0XAttributes(attrs);
322     MaybeParseMicrosoftAttributes(attrs);
323     ParseExternalDeclaration(attrs);
324   }
325
326   T.consumeClose();
327   return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
328                                                  T.getCloseLocation());
329 }
330
331 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
332 /// using-directive. Assumes that current token is 'using'.
333 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
334                                          const ParsedTemplateInfo &TemplateInfo,
335                                                SourceLocation &DeclEnd,
336                                              ParsedAttributesWithRange &attrs,
337                                                Decl **OwnedType) {
338   assert(Tok.is(tok::kw_using) && "Not using token");
339   ObjCDeclContextSwitch ObjCDC(*this);
340   
341   // Eat 'using'.
342   SourceLocation UsingLoc = ConsumeToken();
343
344   if (Tok.is(tok::code_completion)) {
345     Actions.CodeCompleteUsing(getCurScope());
346     cutOffParsing();
347     return 0;
348   }
349
350   // 'using namespace' means this is a using-directive.
351   if (Tok.is(tok::kw_namespace)) {
352     // Template parameters are always an error here.
353     if (TemplateInfo.Kind) {
354       SourceRange R = TemplateInfo.getSourceRange();
355       Diag(UsingLoc, diag::err_templated_using_directive)
356         << R << FixItHint::CreateRemoval(R);
357     }
358
359     return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
360   }
361
362   // Otherwise, it must be a using-declaration or an alias-declaration.
363
364   // Using declarations can't have attributes.
365   ProhibitAttributes(attrs);
366
367   return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
368                                     AS_none, OwnedType);
369 }
370
371 /// ParseUsingDirective - Parse C++ using-directive, assumes
372 /// that current token is 'namespace' and 'using' was already parsed.
373 ///
374 ///       using-directive: [C++ 7.3.p4: namespace.udir]
375 ///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
376 ///                 namespace-name ;
377 /// [GNU] using-directive:
378 ///        'using' 'namespace' ::[opt] nested-name-specifier[opt]
379 ///                 namespace-name attributes[opt] ;
380 ///
381 Decl *Parser::ParseUsingDirective(unsigned Context,
382                                   SourceLocation UsingLoc,
383                                   SourceLocation &DeclEnd,
384                                   ParsedAttributes &attrs) {
385   assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
386
387   // Eat 'namespace'.
388   SourceLocation NamespcLoc = ConsumeToken();
389
390   if (Tok.is(tok::code_completion)) {
391     Actions.CodeCompleteUsingDirective(getCurScope());
392     cutOffParsing();
393     return 0;
394   }
395
396   CXXScopeSpec SS;
397   // Parse (optional) nested-name-specifier.
398   ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
399
400   IdentifierInfo *NamespcName = 0;
401   SourceLocation IdentLoc = SourceLocation();
402
403   // Parse namespace-name.
404   if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
405     Diag(Tok, diag::err_expected_namespace_name);
406     // If there was invalid namespace name, skip to end of decl, and eat ';'.
407     SkipUntil(tok::semi);
408     // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
409     return 0;
410   }
411
412   // Parse identifier.
413   NamespcName = Tok.getIdentifierInfo();
414   IdentLoc = ConsumeToken();
415
416   // Parse (optional) attributes (most likely GNU strong-using extension).
417   bool GNUAttr = false;
418   if (Tok.is(tok::kw___attribute)) {
419     GNUAttr = true;
420     ParseGNUAttributes(attrs);
421   }
422
423   // Eat ';'.
424   DeclEnd = Tok.getLocation();
425   ExpectAndConsume(tok::semi,
426                    GNUAttr ? diag::err_expected_semi_after_attribute_list
427                            : diag::err_expected_semi_after_namespace_name, 
428                    "", tok::semi);
429
430   return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
431                                      IdentLoc, NamespcName, attrs.getList());
432 }
433
434 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
435 /// Assumes that 'using' was already seen.
436 ///
437 ///     using-declaration: [C++ 7.3.p3: namespace.udecl]
438 ///       'using' 'typename'[opt] ::[opt] nested-name-specifier
439 ///               unqualified-id
440 ///       'using' :: unqualified-id
441 ///
442 ///     alias-declaration: C++0x [decl.typedef]p2
443 ///       'using' identifier = type-id ;
444 ///
445 Decl *Parser::ParseUsingDeclaration(unsigned Context,
446                                     const ParsedTemplateInfo &TemplateInfo,
447                                     SourceLocation UsingLoc,
448                                     SourceLocation &DeclEnd,
449                                     AccessSpecifier AS,
450                                     Decl **OwnedType) {
451   CXXScopeSpec SS;
452   SourceLocation TypenameLoc;
453   bool IsTypeName;
454   ParsedAttributesWithRange attrs(AttrFactory);
455
456   // FIXME: Simply skip the attributes and diagnose, don't bother parsing them.
457   MaybeParseCXX0XAttributes(attrs);
458   ProhibitAttributes(attrs);
459   attrs.clear();
460   attrs.Range = SourceRange();
461
462   // Ignore optional 'typename'.
463   // FIXME: This is wrong; we should parse this as a typename-specifier.
464   if (Tok.is(tok::kw_typename)) {
465     TypenameLoc = Tok.getLocation();
466     ConsumeToken();
467     IsTypeName = true;
468   }
469   else
470     IsTypeName = false;
471
472   // Parse nested-name-specifier.
473   ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
474
475   // Check nested-name specifier.
476   if (SS.isInvalid()) {
477     SkipUntil(tok::semi);
478     return 0;
479   }
480
481   // Parse the unqualified-id. We allow parsing of both constructor and
482   // destructor names and allow the action module to diagnose any semantic
483   // errors.
484   SourceLocation TemplateKWLoc;
485   UnqualifiedId Name;
486   if (ParseUnqualifiedId(SS,
487                          /*EnteringContext=*/false,
488                          /*AllowDestructorName=*/true,
489                          /*AllowConstructorName=*/true,
490                          ParsedType(),
491                          TemplateKWLoc,
492                          Name)) {
493     SkipUntil(tok::semi);
494     return 0;
495   }
496
497   MaybeParseCXX0XAttributes(attrs);
498
499   // Maybe this is an alias-declaration.
500   bool IsAliasDecl = Tok.is(tok::equal);
501   TypeResult TypeAlias;
502   if (IsAliasDecl) {
503     // TODO: Attribute support. C++0x attributes may appear before the equals.
504     // Where can GNU attributes appear?
505     ConsumeToken();
506
507     Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
508          diag::warn_cxx98_compat_alias_declaration :
509          diag::ext_alias_declaration);
510
511     // Type alias templates cannot be specialized.
512     int SpecKind = -1;
513     if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
514         Name.getKind() == UnqualifiedId::IK_TemplateId)
515       SpecKind = 0;
516     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
517       SpecKind = 1;
518     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
519       SpecKind = 2;
520     if (SpecKind != -1) {
521       SourceRange Range;
522       if (SpecKind == 0)
523         Range = SourceRange(Name.TemplateId->LAngleLoc,
524                             Name.TemplateId->RAngleLoc);
525       else
526         Range = TemplateInfo.getSourceRange();
527       Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
528         << SpecKind << Range;
529       SkipUntil(tok::semi);
530       return 0;
531     }
532
533     // Name must be an identifier.
534     if (Name.getKind() != UnqualifiedId::IK_Identifier) {
535       Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
536       // No removal fixit: can't recover from this.
537       SkipUntil(tok::semi);
538       return 0;
539     } else if (IsTypeName)
540       Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
541         << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
542                              SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
543     else if (SS.isNotEmpty())
544       Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
545         << FixItHint::CreateRemoval(SS.getRange());
546
547     TypeAlias = ParseTypeName(0, TemplateInfo.Kind ?
548                               Declarator::AliasTemplateContext :
549                               Declarator::AliasDeclContext, AS, OwnedType);
550   } else {
551     // C++11 attributes are not allowed on a using-declaration, but GNU ones
552     // are.
553     ProhibitAttributes(attrs);
554
555     // Parse (optional) attributes (most likely GNU strong-using extension).
556     MaybeParseGNUAttributes(attrs);
557   }
558
559   // Eat ';'.
560   DeclEnd = Tok.getLocation();
561   ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
562                    !attrs.empty() ? "attributes list" :
563                    IsAliasDecl ? "alias declaration" : "using declaration",
564                    tok::semi);
565
566   // Diagnose an attempt to declare a templated using-declaration.
567   // In C++0x, alias-declarations can be templates:
568   //   template <...> using id = type;
569   if (TemplateInfo.Kind && !IsAliasDecl) {
570     SourceRange R = TemplateInfo.getSourceRange();
571     Diag(UsingLoc, diag::err_templated_using_declaration)
572       << R << FixItHint::CreateRemoval(R);
573
574     // Unfortunately, we have to bail out instead of recovering by
575     // ignoring the parameters, just in case the nested name specifier
576     // depends on the parameters.
577     return 0;
578   }
579
580   // "typename" keyword is allowed for identifiers only,
581   // because it may be a type definition.
582   if (IsTypeName && Name.getKind() != UnqualifiedId::IK_Identifier) {
583     Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
584       << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
585     // Proceed parsing, but reset the IsTypeName flag.
586     IsTypeName = false;
587   }
588
589   if (IsAliasDecl) {
590     TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
591     MultiTemplateParamsArg TemplateParamsArg(
592       TemplateParams ? TemplateParams->data() : 0,
593       TemplateParams ? TemplateParams->size() : 0);
594     // FIXME: Propagate attributes.
595     return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
596                                          UsingLoc, Name, TypeAlias);
597   }
598
599   return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS,
600                                        Name, attrs.getList(),
601                                        IsTypeName, TypenameLoc);
602 }
603
604 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
605 ///
606 /// [C++0x] static_assert-declaration:
607 ///           static_assert ( constant-expression  ,  string-literal  ) ;
608 ///
609 /// [C11]   static_assert-declaration:
610 ///           _Static_assert ( constant-expression  ,  string-literal  ) ;
611 ///
612 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
613   assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) &&
614          "Not a static_assert declaration");
615
616   if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
617     Diag(Tok, diag::ext_c11_static_assert);
618   if (Tok.is(tok::kw_static_assert))
619     Diag(Tok, diag::warn_cxx98_compat_static_assert);
620
621   SourceLocation StaticAssertLoc = ConsumeToken();
622
623   BalancedDelimiterTracker T(*this, tok::l_paren);
624   if (T.consumeOpen()) {
625     Diag(Tok, diag::err_expected_lparen);
626     SkipMalformedDecl();
627     return 0;
628   }
629
630   ExprResult AssertExpr(ParseConstantExpression());
631   if (AssertExpr.isInvalid()) {
632     SkipMalformedDecl();
633     return 0;
634   }
635
636   if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
637     return 0;
638
639   if (!isTokenStringLiteral()) {
640     Diag(Tok, diag::err_expected_string_literal);
641     SkipMalformedDecl();
642     return 0;
643   }
644
645   ExprResult AssertMessage(ParseStringLiteralExpression());
646   if (AssertMessage.isInvalid()) {
647     SkipMalformedDecl();
648     return 0;
649   }
650
651   T.consumeClose();
652
653   DeclEnd = Tok.getLocation();
654   ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
655
656   return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
657                                               AssertExpr.take(),
658                                               AssertMessage.take(),
659                                               T.getCloseLocation());
660 }
661
662 /// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
663 ///
664 /// 'decltype' ( expression )
665 ///
666 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
667   assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
668            && "Not a decltype specifier");
669   
670
671   ExprResult Result;
672   SourceLocation StartLoc = Tok.getLocation();
673   SourceLocation EndLoc;
674
675   if (Tok.is(tok::annot_decltype)) {
676     Result = getExprAnnotation(Tok);
677     EndLoc = Tok.getAnnotationEndLoc();
678     ConsumeToken();
679     if (Result.isInvalid()) {
680       DS.SetTypeSpecError();
681       return EndLoc;
682     }
683   } else {
684     if (Tok.getIdentifierInfo()->isStr("decltype"))
685       Diag(Tok, diag::warn_cxx98_compat_decltype);
686
687     ConsumeToken();
688
689     BalancedDelimiterTracker T(*this, tok::l_paren);
690     if (T.expectAndConsume(diag::err_expected_lparen_after,
691                            "decltype", tok::r_paren)) {
692       DS.SetTypeSpecError();
693       return T.getOpenLocation() == Tok.getLocation() ?
694              StartLoc : T.getOpenLocation();
695     }
696
697     // Parse the expression
698
699     // C++0x [dcl.type.simple]p4:
700     //   The operand of the decltype specifier is an unevaluated operand.
701     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
702                                                  0, /*IsDecltype=*/true);
703     Result = ParseExpression();
704     if (Result.isInvalid()) {
705       DS.SetTypeSpecError();
706       if (SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true)) {
707         EndLoc = ConsumeParen();
708       } else {
709         if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
710           // Backtrack to get the location of the last token before the semi.
711           PP.RevertCachedTokens(2);
712           ConsumeToken(); // the semi.
713           EndLoc = ConsumeAnyToken();
714           assert(Tok.is(tok::semi));
715         } else {
716           EndLoc = Tok.getLocation();
717         }
718       }
719       return EndLoc;
720     }
721
722     // Match the ')'
723     T.consumeClose();
724     if (T.getCloseLocation().isInvalid()) {
725       DS.SetTypeSpecError();
726       // FIXME: this should return the location of the last token
727       //        that was consumed (by "consumeClose()")
728       return T.getCloseLocation();
729     }
730
731     Result = Actions.ActOnDecltypeExpression(Result.take());
732     if (Result.isInvalid()) {
733       DS.SetTypeSpecError();
734       return T.getCloseLocation();
735     }
736
737     EndLoc = T.getCloseLocation();
738   }
739
740   const char *PrevSpec = 0;
741   unsigned DiagID;
742   // Check for duplicate type specifiers (e.g. "int decltype(a)").
743   if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
744                          DiagID, Result.release())) {
745     Diag(StartLoc, DiagID) << PrevSpec;
746     DS.SetTypeSpecError();
747   }
748   return EndLoc;
749 }
750
751 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS, 
752                                                SourceLocation StartLoc,
753                                                SourceLocation EndLoc) {
754   // make sure we have a token we can turn into an annotation token
755   if (PP.isBacktrackEnabled())
756     PP.RevertCachedTokens(1);
757   else
758     PP.EnterToken(Tok);
759
760   Tok.setKind(tok::annot_decltype);
761   setExprAnnotation(Tok, DS.getTypeSpecType() == TST_decltype ? 
762                          DS.getRepAsExpr() : ExprResult());
763   Tok.setAnnotationEndLoc(EndLoc);
764   Tok.setLocation(StartLoc);
765   PP.AnnotateCachedTokens(Tok);
766 }
767
768 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
769   assert(Tok.is(tok::kw___underlying_type) &&
770          "Not an underlying type specifier");
771
772   SourceLocation StartLoc = ConsumeToken();
773   BalancedDelimiterTracker T(*this, tok::l_paren);
774   if (T.expectAndConsume(diag::err_expected_lparen_after,
775                        "__underlying_type", tok::r_paren)) {
776     return;
777   }
778
779   TypeResult Result = ParseTypeName();
780   if (Result.isInvalid()) {
781     SkipUntil(tok::r_paren);
782     return;
783   }
784
785   // Match the ')'
786   T.consumeClose();
787   if (T.getCloseLocation().isInvalid())
788     return;
789
790   const char *PrevSpec = 0;
791   unsigned DiagID;
792   if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
793                          DiagID, Result.release()))
794     Diag(StartLoc, DiagID) << PrevSpec;
795 }
796
797 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
798 /// class name or decltype-specifier. Note that we only check that the result 
799 /// names a type; semantic analysis will need to verify that the type names a 
800 /// class. The result is either a type or null, depending on whether a type 
801 /// name was found.
802 ///
803 ///       base-type-specifier: [C++ 10.1]
804 ///         class-or-decltype
805 ///       class-or-decltype: [C++ 10.1]
806 ///         nested-name-specifier[opt] class-name
807 ///         decltype-specifier
808 ///       class-name: [C++ 9.1]
809 ///         identifier
810 ///         simple-template-id
811 ///
812 Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
813                                                   SourceLocation &EndLocation) {
814   // Ignore attempts to use typename
815   if (Tok.is(tok::kw_typename)) {
816     Diag(Tok, diag::err_expected_class_name_not_template)
817       << FixItHint::CreateRemoval(Tok.getLocation());
818     ConsumeToken();
819   }
820
821   // Parse optional nested-name-specifier
822   CXXScopeSpec SS;
823   ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
824
825   BaseLoc = Tok.getLocation();
826
827   // Parse decltype-specifier
828   // tok == kw_decltype is just error recovery, it can only happen when SS 
829   // isn't empty
830   if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
831     if (SS.isNotEmpty())
832       Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
833         << FixItHint::CreateRemoval(SS.getRange());
834     // Fake up a Declarator to use with ActOnTypeName.
835     DeclSpec DS(AttrFactory);
836
837     EndLocation = ParseDecltypeSpecifier(DS);
838
839     Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
840     return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
841   }
842
843   // Check whether we have a template-id that names a type.
844   if (Tok.is(tok::annot_template_id)) {
845     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
846     if (TemplateId->Kind == TNK_Type_template ||
847         TemplateId->Kind == TNK_Dependent_template_name) {
848       AnnotateTemplateIdTokenAsType();
849
850       assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
851       ParsedType Type = getTypeAnnotation(Tok);
852       EndLocation = Tok.getAnnotationEndLoc();
853       ConsumeToken();
854
855       if (Type)
856         return Type;
857       return true;
858     }
859
860     // Fall through to produce an error below.
861   }
862
863   if (Tok.isNot(tok::identifier)) {
864     Diag(Tok, diag::err_expected_class_name);
865     return true;
866   }
867
868   IdentifierInfo *Id = Tok.getIdentifierInfo();
869   SourceLocation IdLoc = ConsumeToken();
870
871   if (Tok.is(tok::less)) {
872     // It looks the user intended to write a template-id here, but the
873     // template-name was wrong. Try to fix that.
874     TemplateNameKind TNK = TNK_Type_template;
875     TemplateTy Template;
876     if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
877                                              &SS, Template, TNK)) {
878       Diag(IdLoc, diag::err_unknown_template_name)
879         << Id;
880     }
881
882     if (!Template)
883       return true;
884
885     // Form the template name
886     UnqualifiedId TemplateName;
887     TemplateName.setIdentifier(Id, IdLoc);
888
889     // Parse the full template-id, then turn it into a type.
890     if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
891                                 TemplateName, true))
892       return true;
893     if (TNK == TNK_Dependent_template_name)
894       AnnotateTemplateIdTokenAsType();
895
896     // If we didn't end up with a typename token, there's nothing more we
897     // can do.
898     if (Tok.isNot(tok::annot_typename))
899       return true;
900
901     // Retrieve the type from the annotation token, consume that token, and
902     // return.
903     EndLocation = Tok.getAnnotationEndLoc();
904     ParsedType Type = getTypeAnnotation(Tok);
905     ConsumeToken();
906     return Type;
907   }
908
909   // We have an identifier; check whether it is actually a type.
910   IdentifierInfo *CorrectedII = 0;
911   ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
912                                         false, ParsedType(),
913                                         /*IsCtorOrDtorName=*/false,
914                                         /*NonTrivialTypeSourceInfo=*/true,
915                                         &CorrectedII);
916   if (!Type) {
917     Diag(IdLoc, diag::err_expected_class_name);
918     return true;
919   }
920
921   // Consume the identifier.
922   EndLocation = IdLoc;
923
924   // Fake up a Declarator to use with ActOnTypeName.
925   DeclSpec DS(AttrFactory);
926   DS.SetRangeStart(IdLoc);
927   DS.SetRangeEnd(EndLocation);
928   DS.getTypeSpecScope() = SS;
929
930   const char *PrevSpec = 0;
931   unsigned DiagID;
932   DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type);
933
934   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
935   return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
936 }
937
938 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
939   while (Tok.is(tok::kw___single_inheritance) ||
940          Tok.is(tok::kw___multiple_inheritance) ||
941          Tok.is(tok::kw___virtual_inheritance)) {
942     IdentifierInfo *AttrName = Tok.getIdentifierInfo();
943     SourceLocation AttrNameLoc = ConsumeToken();
944     attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
945                  SourceLocation(), 0, 0, AttributeList::AS_GNU);
946   }
947 }
948
949 /// Determine whether the following tokens are valid after a type-specifier
950 /// which could be a standalone declaration. This will conservatively return
951 /// true if there's any doubt, and is appropriate for insert-';' fixits.
952 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
953   // This switch enumerates the valid "follow" set for type-specifiers.
954   switch (Tok.getKind()) {
955   default: break;
956   case tok::semi:               // struct foo {...} ;
957   case tok::star:               // struct foo {...} *         P;
958   case tok::amp:                // struct foo {...} &         R = ...
959   case tok::identifier:         // struct foo {...} V         ;
960   case tok::r_paren:            //(struct foo {...} )         {4}
961   case tok::annot_cxxscope:     // struct foo {...} a::       b;
962   case tok::annot_typename:     // struct foo {...} a         ::b;
963   case tok::annot_template_id:  // struct foo {...} a<int>    ::b;
964   case tok::l_paren:            // struct foo {...} (         x);
965   case tok::comma:              // __builtin_offsetof(struct foo{...} ,
966     return true;
967   case tok::colon:
968     return CouldBeBitfield;     // enum E { ... }   :         2;
969   // Type qualifiers
970   case tok::kw_const:           // struct foo {...} const     x;
971   case tok::kw_volatile:        // struct foo {...} volatile  x;
972   case tok::kw_restrict:        // struct foo {...} restrict  x;
973   case tok::kw_inline:          // struct foo {...} inline    foo() {};
974   // Storage-class specifiers
975   case tok::kw_static:          // struct foo {...} static    x;
976   case tok::kw_extern:          // struct foo {...} extern    x;
977   case tok::kw_typedef:         // struct foo {...} typedef   x;
978   case tok::kw_register:        // struct foo {...} register  x;
979   case tok::kw_auto:            // struct foo {...} auto      x;
980   case tok::kw_mutable:         // struct foo {...} mutable   x;
981   case tok::kw_constexpr:       // struct foo {...} constexpr x;
982     // As shown above, type qualifiers and storage class specifiers absolutely
983     // can occur after class specifiers according to the grammar.  However,
984     // almost no one actually writes code like this.  If we see one of these,
985     // it is much more likely that someone missed a semi colon and the
986     // type/storage class specifier we're seeing is part of the *next*
987     // intended declaration, as in:
988     //
989     //   struct foo { ... }
990     //   typedef int X;
991     //
992     // We'd really like to emit a missing semicolon error instead of emitting
993     // an error on the 'int' saying that you can't have two type specifiers in
994     // the same declaration of X.  Because of this, we look ahead past this
995     // token to see if it's a type specifier.  If so, we know the code is
996     // otherwise invalid, so we can produce the expected semi error.
997     if (!isKnownToBeTypeSpecifier(NextToken()))
998       return true;
999     break;
1000   case tok::r_brace:  // struct bar { struct foo {...} }
1001     // Missing ';' at end of struct is accepted as an extension in C mode.
1002     if (!getLangOpts().CPlusPlus)
1003       return true;
1004     break;
1005   }
1006   return false;
1007 }
1008
1009 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1010 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1011 /// until we reach the start of a definition or see a token that
1012 /// cannot start a definition.
1013 ///
1014 ///       class-specifier: [C++ class]
1015 ///         class-head '{' member-specification[opt] '}'
1016 ///         class-head '{' member-specification[opt] '}' attributes[opt]
1017 ///       class-head:
1018 ///         class-key identifier[opt] base-clause[opt]
1019 ///         class-key nested-name-specifier identifier base-clause[opt]
1020 ///         class-key nested-name-specifier[opt] simple-template-id
1021 ///                          base-clause[opt]
1022 /// [GNU]   class-key attributes[opt] identifier[opt] base-clause[opt]
1023 /// [GNU]   class-key attributes[opt] nested-name-specifier
1024 ///                          identifier base-clause[opt]
1025 /// [GNU]   class-key attributes[opt] nested-name-specifier[opt]
1026 ///                          simple-template-id base-clause[opt]
1027 ///       class-key:
1028 ///         'class'
1029 ///         'struct'
1030 ///         'union'
1031 ///
1032 ///       elaborated-type-specifier: [C++ dcl.type.elab]
1033 ///         class-key ::[opt] nested-name-specifier[opt] identifier
1034 ///         class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1035 ///                          simple-template-id
1036 ///
1037 ///  Note that the C++ class-specifier and elaborated-type-specifier,
1038 ///  together, subsume the C99 struct-or-union-specifier:
1039 ///
1040 ///       struct-or-union-specifier: [C99 6.7.2.1]
1041 ///         struct-or-union identifier[opt] '{' struct-contents '}'
1042 ///         struct-or-union identifier
1043 /// [GNU]   struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1044 ///                                                         '}' attributes[opt]
1045 /// [GNU]   struct-or-union attributes[opt] identifier
1046 ///       struct-or-union:
1047 ///         'struct'
1048 ///         'union'
1049 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1050                                  SourceLocation StartLoc, DeclSpec &DS,
1051                                  const ParsedTemplateInfo &TemplateInfo,
1052                                  AccessSpecifier AS, 
1053                                  bool EnteringContext, DeclSpecContext DSC) {
1054   DeclSpec::TST TagType;
1055   if (TagTokKind == tok::kw_struct)
1056     TagType = DeclSpec::TST_struct;
1057   else if (TagTokKind == tok::kw___interface)
1058     TagType = DeclSpec::TST_interface;
1059   else if (TagTokKind == tok::kw_class)
1060     TagType = DeclSpec::TST_class;
1061   else {
1062     assert(TagTokKind == tok::kw_union && "Not a class specifier");
1063     TagType = DeclSpec::TST_union;
1064   }
1065
1066   if (Tok.is(tok::code_completion)) {
1067     // Code completion for a struct, class, or union name.
1068     Actions.CodeCompleteTag(getCurScope(), TagType);
1069     return cutOffParsing();
1070   }
1071
1072   // C++03 [temp.explicit] 14.7.2/8:
1073   //   The usual access checking rules do not apply to names used to specify
1074   //   explicit instantiations.
1075   //
1076   // As an extension we do not perform access checking on the names used to
1077   // specify explicit specializations either. This is important to allow
1078   // specializing traits classes for private types.
1079   //
1080   // Note that we don't suppress if this turns out to be an elaborated
1081   // type specifier.
1082   bool shouldDelayDiagsInTag =
1083     (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1084      TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1085   SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1086
1087   ParsedAttributesWithRange attrs(AttrFactory);
1088   // If attributes exist after tag, parse them.
1089   if (Tok.is(tok::kw___attribute))
1090     ParseGNUAttributes(attrs);
1091
1092   // If declspecs exist after tag, parse them.
1093   while (Tok.is(tok::kw___declspec))
1094     ParseMicrosoftDeclSpec(attrs);
1095
1096   // Parse inheritance specifiers.
1097   if (Tok.is(tok::kw___single_inheritance) ||
1098       Tok.is(tok::kw___multiple_inheritance) ||
1099       Tok.is(tok::kw___virtual_inheritance))
1100       ParseMicrosoftInheritanceClassAttributes(attrs);
1101
1102   // If C++0x attributes exist here, parse them.
1103   // FIXME: Are we consistent with the ordering of parsing of different
1104   // styles of attributes?
1105   MaybeParseCXX0XAttributes(attrs);
1106
1107   if (TagType == DeclSpec::TST_struct &&
1108       !Tok.is(tok::identifier) &&
1109       Tok.getIdentifierInfo() &&
1110       (Tok.is(tok::kw___is_arithmetic) ||
1111        Tok.is(tok::kw___is_convertible) ||
1112        Tok.is(tok::kw___is_empty) ||
1113        Tok.is(tok::kw___is_floating_point) ||
1114        Tok.is(tok::kw___is_function) ||
1115        Tok.is(tok::kw___is_fundamental) ||
1116        Tok.is(tok::kw___is_integral) ||
1117        Tok.is(tok::kw___is_member_function_pointer) ||
1118        Tok.is(tok::kw___is_member_pointer) ||
1119        Tok.is(tok::kw___is_pod) ||
1120        Tok.is(tok::kw___is_pointer) ||
1121        Tok.is(tok::kw___is_same) ||
1122        Tok.is(tok::kw___is_scalar) ||
1123        Tok.is(tok::kw___is_signed) ||
1124        Tok.is(tok::kw___is_unsigned) ||
1125        Tok.is(tok::kw___is_void))) {
1126     // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1127     // name of struct templates, but some are keywords in GCC >= 4.3
1128     // and Clang. Therefore, when we see the token sequence "struct
1129     // X", make X into a normal identifier rather than a keyword, to
1130     // allow libstdc++ 4.2 and libc++ to work properly.
1131     Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1132     Tok.setKind(tok::identifier);
1133   }
1134
1135   // Parse the (optional) nested-name-specifier.
1136   CXXScopeSpec &SS = DS.getTypeSpecScope();
1137   if (getLangOpts().CPlusPlus) {
1138     // "FOO : BAR" is not a potential typo for "FOO::BAR".
1139     ColonProtectionRAIIObject X(*this);
1140
1141     if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1142       DS.SetTypeSpecError();
1143     if (SS.isSet())
1144       if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
1145         Diag(Tok, diag::err_expected_ident);
1146   }
1147
1148   TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1149
1150   // Parse the (optional) class name or simple-template-id.
1151   IdentifierInfo *Name = 0;
1152   SourceLocation NameLoc;
1153   TemplateIdAnnotation *TemplateId = 0;
1154   if (Tok.is(tok::identifier)) {
1155     Name = Tok.getIdentifierInfo();
1156     NameLoc = ConsumeToken();
1157
1158     if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1159       // The name was supposed to refer to a template, but didn't.
1160       // Eat the template argument list and try to continue parsing this as
1161       // a class (or template thereof).
1162       TemplateArgList TemplateArgs;
1163       SourceLocation LAngleLoc, RAngleLoc;
1164       if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1165                                            true, LAngleLoc,
1166                                            TemplateArgs, RAngleLoc)) {
1167         // We couldn't parse the template argument list at all, so don't
1168         // try to give any location information for the list.
1169         LAngleLoc = RAngleLoc = SourceLocation();
1170       }
1171
1172       Diag(NameLoc, diag::err_explicit_spec_non_template)
1173         << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1174         << (TagType == DeclSpec::TST_class? 0
1175             : TagType == DeclSpec::TST_struct? 1
1176             : TagType == DeclSpec::TST_interface? 2
1177             : 3)
1178         << Name
1179         << SourceRange(LAngleLoc, RAngleLoc);
1180
1181       // Strip off the last template parameter list if it was empty, since
1182       // we've removed its template argument list.
1183       if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1184         if (TemplateParams && TemplateParams->size() > 1) {
1185           TemplateParams->pop_back();
1186         } else {
1187           TemplateParams = 0;
1188           const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1189             = ParsedTemplateInfo::NonTemplate;
1190         }
1191       } else if (TemplateInfo.Kind
1192                                 == ParsedTemplateInfo::ExplicitInstantiation) {
1193         // Pretend this is just a forward declaration.
1194         TemplateParams = 0;
1195         const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1196           = ParsedTemplateInfo::NonTemplate;
1197         const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1198           = SourceLocation();
1199         const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1200           = SourceLocation();
1201       }
1202     }
1203   } else if (Tok.is(tok::annot_template_id)) {
1204     TemplateId = takeTemplateIdAnnotation(Tok);
1205     NameLoc = ConsumeToken();
1206
1207     if (TemplateId->Kind != TNK_Type_template &&
1208         TemplateId->Kind != TNK_Dependent_template_name) {
1209       // The template-name in the simple-template-id refers to
1210       // something other than a class template. Give an appropriate
1211       // error message and skip to the ';'.
1212       SourceRange Range(NameLoc);
1213       if (SS.isNotEmpty())
1214         Range.setBegin(SS.getBeginLoc());
1215
1216       Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1217         << Name << static_cast<int>(TemplateId->Kind) << Range;
1218
1219       DS.SetTypeSpecError();
1220       SkipUntil(tok::semi, false, true);
1221       return;
1222     }
1223   }
1224
1225   // There are four options here.
1226   //  - If we are in a trailing return type, this is always just a reference,
1227   //    and we must not try to parse a definition. For instance,
1228   //      [] () -> struct S { };
1229   //    does not define a type.
1230   //  - If we have 'struct foo {...', 'struct foo :...',
1231   //    'struct foo final :' or 'struct foo final {', then this is a definition.
1232   //  - If we have 'struct foo;', then this is either a forward declaration
1233   //    or a friend declaration, which have to be treated differently.
1234   //  - Otherwise we have something like 'struct foo xyz', a reference.
1235   // However, in type-specifier-seq's, things look like declarations but are
1236   // just references, e.g.
1237   //   new struct s;
1238   // or
1239   //   &T::operator struct s;
1240   // For these, DSC is DSC_type_specifier.
1241   Sema::TagUseKind TUK;
1242   if (DSC == DSC_trailing)
1243     TUK = Sema::TUK_Reference;
1244   else if (Tok.is(tok::l_brace) ||
1245            (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1246            (isCXX0XFinalKeyword() &&
1247             (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1248     if (DS.isFriendSpecified()) {
1249       // C++ [class.friend]p2:
1250       //   A class shall not be defined in a friend declaration.
1251       Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1252         << SourceRange(DS.getFriendSpecLoc());
1253
1254       // Skip everything up to the semicolon, so that this looks like a proper
1255       // friend class (or template thereof) declaration.
1256       SkipUntil(tok::semi, true, true);
1257       TUK = Sema::TUK_Friend;
1258     } else {
1259       // Okay, this is a class definition.
1260       TUK = Sema::TUK_Definition;
1261     }
1262   } else if (DSC != DSC_type_specifier &&
1263              (Tok.is(tok::semi) ||
1264               (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1265     TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1266     if (Tok.isNot(tok::semi)) {
1267       // A semicolon was missing after this declaration. Diagnose and recover.
1268       ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1269         DeclSpec::getSpecifierName(TagType));
1270       PP.EnterToken(Tok);
1271       Tok.setKind(tok::semi);
1272     }
1273   } else
1274     TUK = Sema::TUK_Reference;
1275
1276   // If this is an elaborated type specifier, and we delayed
1277   // diagnostics before, just merge them into the current pool.
1278   if (shouldDelayDiagsInTag) {
1279     diagsFromTag.done();
1280     if (TUK == Sema::TUK_Reference)
1281       diagsFromTag.redelay();
1282   }
1283
1284   if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1285                                TUK != Sema::TUK_Definition)) {
1286     if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1287       // We have a declaration or reference to an anonymous class.
1288       Diag(StartLoc, diag::err_anon_type_definition)
1289         << DeclSpec::getSpecifierName(TagType);
1290     }
1291
1292     SkipUntil(tok::comma, true);
1293     return;
1294   }
1295
1296   // Create the tag portion of the class or class template.
1297   DeclResult TagOrTempResult = true; // invalid
1298   TypeResult TypeResult = true; // invalid
1299
1300   bool Owned = false;
1301   if (TemplateId) {
1302     // Explicit specialization, class template partial specialization,
1303     // or explicit instantiation.
1304     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1305                                        TemplateId->NumArgs);
1306     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1307         TUK == Sema::TUK_Declaration) {
1308       // This is an explicit instantiation of a class template.
1309       ProhibitAttributes(attrs);
1310
1311       TagOrTempResult
1312         = Actions.ActOnExplicitInstantiation(getCurScope(),
1313                                              TemplateInfo.ExternLoc,
1314                                              TemplateInfo.TemplateLoc,
1315                                              TagType,
1316                                              StartLoc,
1317                                              SS,
1318                                              TemplateId->Template,
1319                                              TemplateId->TemplateNameLoc,
1320                                              TemplateId->LAngleLoc,
1321                                              TemplateArgsPtr,
1322                                              TemplateId->RAngleLoc,
1323                                              attrs.getList());
1324
1325     // Friend template-ids are treated as references unless
1326     // they have template headers, in which case they're ill-formed
1327     // (FIXME: "template <class T> friend class A<T>::B<int>;").
1328     // We diagnose this error in ActOnClassTemplateSpecialization.
1329     } else if (TUK == Sema::TUK_Reference ||
1330                (TUK == Sema::TUK_Friend &&
1331                 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1332       ProhibitAttributes(attrs);
1333       TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1334                                                   TemplateId->SS,
1335                                                   TemplateId->TemplateKWLoc,
1336                                                   TemplateId->Template,
1337                                                   TemplateId->TemplateNameLoc,
1338                                                   TemplateId->LAngleLoc,
1339                                                   TemplateArgsPtr,
1340                                                   TemplateId->RAngleLoc);
1341     } else {
1342       // This is an explicit specialization or a class template
1343       // partial specialization.
1344       TemplateParameterLists FakedParamLists;
1345
1346       if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1347         // This looks like an explicit instantiation, because we have
1348         // something like
1349         //
1350         //   template class Foo<X>
1351         //
1352         // but it actually has a definition. Most likely, this was
1353         // meant to be an explicit specialization, but the user forgot
1354         // the '<>' after 'template'.
1355         assert(TUK == Sema::TUK_Definition && "Expected a definition here");
1356
1357         SourceLocation LAngleLoc
1358           = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1359         Diag(TemplateId->TemplateNameLoc,
1360              diag::err_explicit_instantiation_with_definition)
1361           << SourceRange(TemplateInfo.TemplateLoc)
1362           << FixItHint::CreateInsertion(LAngleLoc, "<>");
1363
1364         // Create a fake template parameter list that contains only
1365         // "template<>", so that we treat this construct as a class
1366         // template specialization.
1367         FakedParamLists.push_back(
1368           Actions.ActOnTemplateParameterList(0, SourceLocation(),
1369                                              TemplateInfo.TemplateLoc,
1370                                              LAngleLoc,
1371                                              0, 0,
1372                                              LAngleLoc));
1373         TemplateParams = &FakedParamLists;
1374       }
1375
1376       // Build the class template specialization.
1377       TagOrTempResult
1378         = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK,
1379                        StartLoc, DS.getModulePrivateSpecLoc(), SS,
1380                        TemplateId->Template,
1381                        TemplateId->TemplateNameLoc,
1382                        TemplateId->LAngleLoc,
1383                        TemplateArgsPtr,
1384                        TemplateId->RAngleLoc,
1385                        attrs.getList(),
1386                        MultiTemplateParamsArg(
1387                                     TemplateParams? &(*TemplateParams)[0] : 0,
1388                                  TemplateParams? TemplateParams->size() : 0));
1389     }
1390   } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1391              TUK == Sema::TUK_Declaration) {
1392     // Explicit instantiation of a member of a class template
1393     // specialization, e.g.,
1394     //
1395     //   template struct Outer<int>::Inner;
1396     //
1397     ProhibitAttributes(attrs);
1398
1399     TagOrTempResult
1400       = Actions.ActOnExplicitInstantiation(getCurScope(),
1401                                            TemplateInfo.ExternLoc,
1402                                            TemplateInfo.TemplateLoc,
1403                                            TagType, StartLoc, SS, Name,
1404                                            NameLoc, attrs.getList());
1405   } else if (TUK == Sema::TUK_Friend &&
1406              TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1407     ProhibitAttributes(attrs);
1408
1409     TagOrTempResult =
1410       Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1411                                       TagType, StartLoc, SS,
1412                                       Name, NameLoc, attrs.getList(),
1413                                       MultiTemplateParamsArg(
1414                                     TemplateParams? &(*TemplateParams)[0] : 0,
1415                                  TemplateParams? TemplateParams->size() : 0));
1416   } else {
1417     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1418         TUK == Sema::TUK_Definition) {
1419       // FIXME: Diagnose this particular error.
1420     }
1421
1422     if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1423       ProhibitAttributes(attrs);
1424
1425     bool IsDependent = false;
1426
1427     // Don't pass down template parameter lists if this is just a tag
1428     // reference.  For example, we don't need the template parameters here:
1429     //   template <class T> class A *makeA(T t);
1430     MultiTemplateParamsArg TParams;
1431     if (TUK != Sema::TUK_Reference && TemplateParams)
1432       TParams =
1433         MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1434
1435     // Declaration or definition of a class type
1436     TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1437                                        SS, Name, NameLoc, attrs.getList(), AS,
1438                                        DS.getModulePrivateSpecLoc(),
1439                                        TParams, Owned, IsDependent,
1440                                        SourceLocation(), false,
1441                                        clang::TypeResult());
1442
1443     // If ActOnTag said the type was dependent, try again with the
1444     // less common call.
1445     if (IsDependent) {
1446       assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1447       TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1448                                              SS, Name, StartLoc, NameLoc);
1449     }
1450   }
1451
1452   // If there is a body, parse it and inform the actions module.
1453   if (TUK == Sema::TUK_Definition) {
1454     assert(Tok.is(tok::l_brace) ||
1455            (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1456            isCXX0XFinalKeyword());
1457     if (getLangOpts().CPlusPlus)
1458       ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
1459     else
1460       ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1461   }
1462
1463   const char *PrevSpec = 0;
1464   unsigned DiagID;
1465   bool Result;
1466   if (!TypeResult.isInvalid()) {
1467     Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1468                                 NameLoc.isValid() ? NameLoc : StartLoc,
1469                                 PrevSpec, DiagID, TypeResult.get());
1470   } else if (!TagOrTempResult.isInvalid()) {
1471     Result = DS.SetTypeSpecType(TagType, StartLoc,
1472                                 NameLoc.isValid() ? NameLoc : StartLoc,
1473                                 PrevSpec, DiagID, TagOrTempResult.get(), Owned);
1474   } else {
1475     DS.SetTypeSpecError();
1476     return;
1477   }
1478
1479   if (Result)
1480     Diag(StartLoc, DiagID) << PrevSpec;
1481
1482   // At this point, we've successfully parsed a class-specifier in 'definition'
1483   // form (e.g. "struct foo { int x; }".  While we could just return here, we're
1484   // going to look at what comes after it to improve error recovery.  If an
1485   // impossible token occurs next, we assume that the programmer forgot a ; at
1486   // the end of the declaration and recover that way.
1487   //
1488   // Also enforce C++ [temp]p3:
1489   //   In a template-declaration which defines a class, no declarator
1490   //   is permitted.
1491   if (TUK == Sema::TUK_Definition &&
1492       (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1493     ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1494       DeclSpec::getSpecifierName(TagType));
1495     // Push this token back into the preprocessor and change our current token
1496     // to ';' so that the rest of the code recovers as though there were an
1497     // ';' after the definition.
1498     PP.EnterToken(Tok);
1499     Tok.setKind(tok::semi);
1500   }
1501 }
1502
1503 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1504 ///
1505 ///       base-clause : [C++ class.derived]
1506 ///         ':' base-specifier-list
1507 ///       base-specifier-list:
1508 ///         base-specifier '...'[opt]
1509 ///         base-specifier-list ',' base-specifier '...'[opt]
1510 void Parser::ParseBaseClause(Decl *ClassDecl) {
1511   assert(Tok.is(tok::colon) && "Not a base clause");
1512   ConsumeToken();
1513
1514   // Build up an array of parsed base specifiers.
1515   SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1516
1517   while (true) {
1518     // Parse a base-specifier.
1519     BaseResult Result = ParseBaseSpecifier(ClassDecl);
1520     if (Result.isInvalid()) {
1521       // Skip the rest of this base specifier, up until the comma or
1522       // opening brace.
1523       SkipUntil(tok::comma, tok::l_brace, true, true);
1524     } else {
1525       // Add this to our array of base specifiers.
1526       BaseInfo.push_back(Result.get());
1527     }
1528
1529     // If the next token is a comma, consume it and keep reading
1530     // base-specifiers.
1531     if (Tok.isNot(tok::comma)) break;
1532
1533     // Consume the comma.
1534     ConsumeToken();
1535   }
1536
1537   // Attach the base specifiers
1538   Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1539 }
1540
1541 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1542 /// one entry in the base class list of a class specifier, for example:
1543 ///    class foo : public bar, virtual private baz {
1544 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1545 ///
1546 ///       base-specifier: [C++ class.derived]
1547 ///         ::[opt] nested-name-specifier[opt] class-name
1548 ///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
1549 ///                        base-type-specifier
1550 ///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
1551 ///                        base-type-specifier
1552 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1553   bool IsVirtual = false;
1554   SourceLocation StartLoc = Tok.getLocation();
1555
1556   // Parse the 'virtual' keyword.
1557   if (Tok.is(tok::kw_virtual))  {
1558     ConsumeToken();
1559     IsVirtual = true;
1560   }
1561
1562   // Parse an (optional) access specifier.
1563   AccessSpecifier Access = getAccessSpecifierIfPresent();
1564   if (Access != AS_none)
1565     ConsumeToken();
1566
1567   // Parse the 'virtual' keyword (again!), in case it came after the
1568   // access specifier.
1569   if (Tok.is(tok::kw_virtual))  {
1570     SourceLocation VirtualLoc = ConsumeToken();
1571     if (IsVirtual) {
1572       // Complain about duplicate 'virtual'
1573       Diag(VirtualLoc, diag::err_dup_virtual)
1574         << FixItHint::CreateRemoval(VirtualLoc);
1575     }
1576
1577     IsVirtual = true;
1578   }
1579
1580   // Parse the class-name.
1581   SourceLocation EndLocation;
1582   SourceLocation BaseLoc;
1583   TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1584   if (BaseType.isInvalid())
1585     return true;
1586
1587   // Parse the optional ellipsis (for a pack expansion). The ellipsis is 
1588   // actually part of the base-specifier-list grammar productions, but we
1589   // parse it here for convenience.
1590   SourceLocation EllipsisLoc;
1591   if (Tok.is(tok::ellipsis))
1592     EllipsisLoc = ConsumeToken();
1593   
1594   // Find the complete source range for the base-specifier.
1595   SourceRange Range(StartLoc, EndLocation);
1596
1597   // Notify semantic analysis that we have parsed a complete
1598   // base-specifier.
1599   return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
1600                                     BaseType.get(), BaseLoc, EllipsisLoc);
1601 }
1602
1603 /// getAccessSpecifierIfPresent - Determine whether the next token is
1604 /// a C++ access-specifier.
1605 ///
1606 ///       access-specifier: [C++ class.derived]
1607 ///         'private'
1608 ///         'protected'
1609 ///         'public'
1610 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1611   switch (Tok.getKind()) {
1612   default: return AS_none;
1613   case tok::kw_private: return AS_private;
1614   case tok::kw_protected: return AS_protected;
1615   case tok::kw_public: return AS_public;
1616   }
1617 }
1618
1619 /// \brief If the given declarator has any parts for which parsing has to be
1620 /// delayed, e.g., default arguments, create a late-parsed method declaration
1621 /// record to handle the parsing at the end of the class definition.
1622 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1623                                             Decl *ThisDecl) {
1624   // We just declared a member function. If this member function
1625   // has any default arguments, we'll need to parse them later.
1626   LateParsedMethodDeclaration *LateMethod = 0;
1627   DeclaratorChunk::FunctionTypeInfo &FTI
1628     = DeclaratorInfo.getFunctionTypeInfo();
1629
1630   for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1631     if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1632       if (!LateMethod) {
1633         // Push this method onto the stack of late-parsed method
1634         // declarations.
1635         LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1636         getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1637         LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1638
1639         // Add all of the parameters prior to this one (they don't
1640         // have default arguments).
1641         LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1642         for (unsigned I = 0; I < ParamIdx; ++I)
1643           LateMethod->DefaultArgs.push_back(
1644                              LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
1645       }
1646
1647       // Add this parameter to the list of parameters (it may or may
1648       // not have a default argument).
1649       LateMethod->DefaultArgs.push_back(
1650         LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1651                                   FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1652     }
1653   }
1654 }
1655
1656 /// isCXX0XVirtSpecifier - Determine whether the given token is a C++0x
1657 /// virt-specifier.
1658 ///
1659 ///       virt-specifier:
1660 ///         override
1661 ///         final
1662 VirtSpecifiers::Specifier Parser::isCXX0XVirtSpecifier(const Token &Tok) const {
1663   if (!getLangOpts().CPlusPlus)
1664     return VirtSpecifiers::VS_None;
1665
1666   if (Tok.is(tok::identifier)) {
1667     IdentifierInfo *II = Tok.getIdentifierInfo();
1668
1669     // Initialize the contextual keywords.
1670     if (!Ident_final) {
1671       Ident_final = &PP.getIdentifierTable().get("final");
1672       Ident_override = &PP.getIdentifierTable().get("override");
1673     }
1674
1675     if (II == Ident_override)
1676       return VirtSpecifiers::VS_Override;
1677
1678     if (II == Ident_final)
1679       return VirtSpecifiers::VS_Final;
1680   }
1681
1682   return VirtSpecifiers::VS_None;
1683 }
1684
1685 /// ParseOptionalCXX0XVirtSpecifierSeq - Parse a virt-specifier-seq.
1686 ///
1687 ///       virt-specifier-seq:
1688 ///         virt-specifier
1689 ///         virt-specifier-seq virt-specifier
1690 void Parser::ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS,
1691                                                 bool IsInterface) {
1692   while (true) {
1693     VirtSpecifiers::Specifier Specifier = isCXX0XVirtSpecifier();
1694     if (Specifier == VirtSpecifiers::VS_None)
1695       return;
1696
1697     // C++ [class.mem]p8:
1698     //   A virt-specifier-seq shall contain at most one of each virt-specifier.
1699     const char *PrevSpec = 0;
1700     if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
1701       Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
1702         << PrevSpec
1703         << FixItHint::CreateRemoval(Tok.getLocation());
1704
1705     if (IsInterface && Specifier == VirtSpecifiers::VS_Final) {
1706       Diag(Tok.getLocation(), diag::err_override_control_interface)
1707         << VirtSpecifiers::getSpecifierName(Specifier);
1708     } else {
1709       Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
1710            diag::warn_cxx98_compat_override_control_keyword :
1711            diag::ext_override_control_keyword)
1712         << VirtSpecifiers::getSpecifierName(Specifier);
1713     }
1714     ConsumeToken();
1715   }
1716 }
1717
1718 /// isCXX0XFinalKeyword - Determine whether the next token is a C++0x
1719 /// contextual 'final' keyword.
1720 bool Parser::isCXX0XFinalKeyword() const {
1721   if (!getLangOpts().CPlusPlus)
1722     return false;
1723
1724   if (!Tok.is(tok::identifier))
1725     return false;
1726
1727   // Initialize the contextual keywords.
1728   if (!Ident_final) {
1729     Ident_final = &PP.getIdentifierTable().get("final");
1730     Ident_override = &PP.getIdentifierTable().get("override");
1731   }
1732   
1733   return Tok.getIdentifierInfo() == Ident_final;
1734 }
1735
1736 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1737 ///
1738 ///       member-declaration:
1739 ///         decl-specifier-seq[opt] member-declarator-list[opt] ';'
1740 ///         function-definition ';'[opt]
1741 ///         ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1742 ///         using-declaration                                            [TODO]
1743 /// [C++0x] static_assert-declaration
1744 ///         template-declaration
1745 /// [GNU]   '__extension__' member-declaration
1746 ///
1747 ///       member-declarator-list:
1748 ///         member-declarator
1749 ///         member-declarator-list ',' member-declarator
1750 ///
1751 ///       member-declarator:
1752 ///         declarator virt-specifier-seq[opt] pure-specifier[opt]
1753 ///         declarator constant-initializer[opt]
1754 /// [C++11] declarator brace-or-equal-initializer[opt]
1755 ///         identifier[opt] ':' constant-expression
1756 ///
1757 ///       virt-specifier-seq:
1758 ///         virt-specifier
1759 ///         virt-specifier-seq virt-specifier
1760 ///
1761 ///       virt-specifier:
1762 ///         override
1763 ///         final
1764 /// 
1765 ///       pure-specifier:
1766 ///         '= 0'
1767 ///
1768 ///       constant-initializer:
1769 ///         '=' constant-expression
1770 ///
1771 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1772                                             AttributeList *AccessAttrs,
1773                                        const ParsedTemplateInfo &TemplateInfo,
1774                                        ParsingDeclRAIIObject *TemplateDiags) {
1775   if (Tok.is(tok::at)) {
1776     if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
1777       Diag(Tok, diag::err_at_defs_cxx);
1778     else
1779       Diag(Tok, diag::err_at_in_class);
1780     
1781     ConsumeToken();
1782     SkipUntil(tok::r_brace);
1783     return;
1784   }
1785   
1786   // Access declarations.
1787   bool MalformedTypeSpec = false;
1788   if (!TemplateInfo.Kind &&
1789       (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) {
1790     if (TryAnnotateCXXScopeToken())
1791       MalformedTypeSpec = true;
1792
1793     bool isAccessDecl;
1794     if (Tok.isNot(tok::annot_cxxscope))
1795       isAccessDecl = false;
1796     else if (NextToken().is(tok::identifier))
1797       isAccessDecl = GetLookAheadToken(2).is(tok::semi);
1798     else
1799       isAccessDecl = NextToken().is(tok::kw_operator);
1800
1801     if (isAccessDecl) {
1802       // Collect the scope specifier token we annotated earlier.
1803       CXXScopeSpec SS;
1804       ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 
1805                                      /*EnteringContext=*/false);
1806
1807       // Try to parse an unqualified-id.
1808       SourceLocation TemplateKWLoc;
1809       UnqualifiedId Name;
1810       if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
1811                              TemplateKWLoc, Name)) {
1812         SkipUntil(tok::semi);
1813         return;
1814       }
1815
1816       // TODO: recover from mistakenly-qualified operator declarations.
1817       if (ExpectAndConsume(tok::semi,
1818                            diag::err_expected_semi_after,
1819                            "access declaration",
1820                            tok::semi))
1821         return;
1822
1823       Actions.ActOnUsingDeclaration(getCurScope(), AS,
1824                                     false, SourceLocation(),
1825                                     SS, Name,
1826                                     /* AttrList */ 0,
1827                                     /* IsTypeName */ false,
1828                                     SourceLocation());
1829       return;
1830     }
1831   }
1832
1833   // static_assert-declaration
1834   if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) {
1835     // FIXME: Check for templates
1836     SourceLocation DeclEnd;
1837     ParseStaticAssertDeclaration(DeclEnd);
1838     return;
1839   }
1840
1841   if (Tok.is(tok::kw_template)) {
1842     assert(!TemplateInfo.TemplateParams &&
1843            "Nested template improperly parsed?");
1844     SourceLocation DeclEnd;
1845     ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
1846                                          AS, AccessAttrs);
1847     return;
1848   }
1849
1850   // Handle:  member-declaration ::= '__extension__' member-declaration
1851   if (Tok.is(tok::kw___extension__)) {
1852     // __extension__ silences extension warnings in the subexpression.
1853     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1854     ConsumeToken();
1855     return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
1856                                           TemplateInfo, TemplateDiags);
1857   }
1858
1859   // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1860   // is a bitfield.
1861   ColonProtectionRAIIObject X(*this);
1862
1863   ParsedAttributesWithRange attrs(AttrFactory);
1864   // Optional C++0x attribute-specifier
1865   MaybeParseCXX0XAttributes(attrs);
1866   MaybeParseMicrosoftAttributes(attrs);
1867
1868   if (Tok.is(tok::kw_using)) {
1869     ProhibitAttributes(attrs);
1870
1871     // Eat 'using'.
1872     SourceLocation UsingLoc = ConsumeToken();
1873
1874     if (Tok.is(tok::kw_namespace)) {
1875       Diag(UsingLoc, diag::err_using_namespace_in_class);
1876       SkipUntil(tok::semi, true, true);
1877     } else {
1878       SourceLocation DeclEnd;
1879       // Otherwise, it must be a using-declaration or an alias-declaration.
1880       ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
1881                             UsingLoc, DeclEnd, AS);
1882     }
1883     return;
1884   }
1885
1886   // Hold late-parsed attributes so we can attach a Decl to them later.
1887   LateParsedAttrList CommonLateParsedAttrs;
1888
1889   // decl-specifier-seq:
1890   // Parse the common declaration-specifiers piece.
1891   ParsingDeclSpec DS(*this, TemplateDiags);
1892   DS.takeAttributesFrom(attrs);
1893   if (MalformedTypeSpec)
1894     DS.SetTypeSpecError();
1895   ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
1896                              &CommonLateParsedAttrs);
1897
1898   MultiTemplateParamsArg TemplateParams(
1899       TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
1900       TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
1901
1902   if (Tok.is(tok::semi)) {
1903     ConsumeToken();
1904     Decl *TheDecl =
1905       Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
1906     DS.complete(TheDecl);
1907     return;
1908   }
1909
1910   ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
1911   VirtSpecifiers VS;
1912
1913   // Hold late-parsed attributes so we can attach a Decl to them later.
1914   LateParsedAttrList LateParsedAttrs;
1915
1916   SourceLocation EqualLoc;
1917   bool HasInitializer = false;
1918   ExprResult Init;
1919   if (Tok.isNot(tok::colon)) {
1920     // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1921     ColonProtectionRAIIObject X(*this);
1922
1923     // Parse the first declarator.
1924     ParseDeclarator(DeclaratorInfo);
1925     // Error parsing the declarator?
1926     if (!DeclaratorInfo.hasName()) {
1927       // If so, skip until the semi-colon or a }.
1928       SkipUntil(tok::r_brace, true, true);
1929       if (Tok.is(tok::semi))
1930         ConsumeToken();
1931       return;
1932     }
1933
1934     ParseOptionalCXX0XVirtSpecifierSeq(VS, getCurrentClass().IsInterface);
1935
1936     // If attributes exist after the declarator, but before an '{', parse them.
1937     MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
1938
1939     // MSVC permits pure specifier on inline functions declared at class scope.
1940     // Hence check for =0 before checking for function definition.
1941     if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
1942         DeclaratorInfo.isFunctionDeclarator() && 
1943         NextToken().is(tok::numeric_constant)) {
1944       EqualLoc = ConsumeToken();
1945       Init = ParseInitializer();
1946       if (Init.isInvalid())
1947         SkipUntil(tok::comma, true, true);
1948       else
1949         HasInitializer = true;
1950     }
1951
1952     FunctionDefinitionKind DefinitionKind = FDK_Declaration;
1953     // function-definition:
1954     //
1955     // In C++11, a non-function declarator followed by an open brace is a
1956     // braced-init-list for an in-class member initialization, not an
1957     // erroneous function definition.
1958     if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus0x) {
1959       DefinitionKind = FDK_Definition;
1960     } else if (DeclaratorInfo.isFunctionDeclarator()) {
1961       if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
1962         DefinitionKind = FDK_Definition;
1963       } else if (Tok.is(tok::equal)) {
1964         const Token &KW = NextToken();
1965         if (KW.is(tok::kw_default))
1966           DefinitionKind = FDK_Defaulted;
1967         else if (KW.is(tok::kw_delete))
1968           DefinitionKind = FDK_Deleted;
1969       }
1970     }
1971
1972     if (DefinitionKind) {
1973       if (!DeclaratorInfo.isFunctionDeclarator()) {
1974         Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
1975         ConsumeBrace();
1976         SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1977         
1978         // Consume the optional ';'
1979         if (Tok.is(tok::semi))
1980           ConsumeToken();
1981         return;
1982       }
1983
1984       if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1985         Diag(DeclaratorInfo.getIdentifierLoc(),
1986              diag::err_function_declared_typedef);
1987         // This recovery skips the entire function body. It would be nice
1988         // to simply call ParseCXXInlineMethodDef() below, however Sema
1989         // assumes the declarator represents a function, not a typedef.
1990         ConsumeBrace();
1991         SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1992
1993         // Consume the optional ';'
1994         if (Tok.is(tok::semi))
1995           ConsumeToken();
1996         return;
1997       }
1998
1999       Decl *FunDecl =
2000         ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2001                                 VS, DefinitionKind, Init);
2002
2003       for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2004         CommonLateParsedAttrs[i]->addDecl(FunDecl);
2005       }
2006       for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2007         LateParsedAttrs[i]->addDecl(FunDecl);
2008       }
2009       LateParsedAttrs.clear();
2010
2011       // Consume the ';' - it's optional unless we have a delete or default
2012       if (Tok.is(tok::semi))
2013         ConsumeExtraSemi(AfterMemberFunctionDefinition);
2014
2015       return;
2016     }
2017   }
2018
2019   // member-declarator-list:
2020   //   member-declarator
2021   //   member-declarator-list ',' member-declarator
2022
2023   SmallVector<Decl *, 8> DeclsInGroup;
2024   ExprResult BitfieldSize;
2025   bool ExpectSemi = true;
2026
2027   while (1) {
2028     // member-declarator:
2029     //   declarator pure-specifier[opt]
2030     //   declarator brace-or-equal-initializer[opt]
2031     //   identifier[opt] ':' constant-expression
2032     if (Tok.is(tok::colon)) {
2033       ConsumeToken();
2034       BitfieldSize = ParseConstantExpression();
2035       if (BitfieldSize.isInvalid())
2036         SkipUntil(tok::comma, true, true);
2037     }
2038
2039     // If a simple-asm-expr is present, parse it.
2040     if (Tok.is(tok::kw_asm)) {
2041       SourceLocation Loc;
2042       ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2043       if (AsmLabel.isInvalid())
2044         SkipUntil(tok::comma, true, true);
2045  
2046       DeclaratorInfo.setAsmLabel(AsmLabel.release());
2047       DeclaratorInfo.SetRangeEnd(Loc);
2048     }
2049
2050     // If attributes exist after the declarator, parse them.
2051     MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2052
2053     // FIXME: When g++ adds support for this, we'll need to check whether it
2054     // goes before or after the GNU attributes and __asm__.
2055     ParseOptionalCXX0XVirtSpecifierSeq(VS, getCurrentClass().IsInterface);
2056
2057     InClassInitStyle HasInClassInit = ICIS_NoInit;
2058     if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
2059       if (BitfieldSize.get()) {
2060         Diag(Tok, diag::err_bitfield_member_init);
2061         SkipUntil(tok::comma, true, true);
2062       } else {
2063         HasInitializer = true;
2064         if (!DeclaratorInfo.isDeclarationOfFunction() &&
2065             DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2066               != DeclSpec::SCS_static &&
2067             DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2068               != DeclSpec::SCS_typedef)
2069           HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2070       }
2071     }
2072
2073     // NOTE: If Sema is the Action module and declarator is an instance field,
2074     // this call will *not* return the created decl; It will return null.
2075     // See Sema::ActOnCXXMemberDeclarator for details.
2076
2077     Decl *ThisDecl = 0;
2078     if (DS.isFriendSpecified()) {
2079       // TODO: handle initializers, bitfields, 'delete'
2080       ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2081                                                  TemplateParams);
2082     } else {
2083       ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2084                                                   DeclaratorInfo,
2085                                                   TemplateParams,
2086                                                   BitfieldSize.release(),
2087                                                   VS, HasInClassInit);
2088       if (AccessAttrs)
2089         Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs,
2090                                          false, true);
2091     }
2092     
2093     // Set the Decl for any late parsed attributes
2094     for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2095       CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2096     }
2097     for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2098       LateParsedAttrs[i]->addDecl(ThisDecl);
2099     }
2100     LateParsedAttrs.clear();
2101
2102     // Handle the initializer.
2103     if (HasInClassInit != ICIS_NoInit) {
2104       // The initializer was deferred; parse it and cache the tokens.
2105       Diag(Tok, getLangOpts().CPlusPlus0x ?
2106            diag::warn_cxx98_compat_nonstatic_member_init :
2107            diag::ext_nonstatic_member_init);
2108
2109       if (DeclaratorInfo.isArrayOfUnknownBound()) {
2110         // C++11 [dcl.array]p3: An array bound may also be omitted when the
2111         // declarator is followed by an initializer.
2112         //
2113         // A brace-or-equal-initializer for a member-declarator is not an
2114         // initializer in the grammar, so this is ill-formed.
2115         Diag(Tok, diag::err_incomplete_array_member_init);
2116         SkipUntil(tok::comma, true, true);
2117         if (ThisDecl)
2118           // Avoid later warnings about a class member of incomplete type.
2119           ThisDecl->setInvalidDecl();
2120       } else
2121         ParseCXXNonStaticMemberInitializer(ThisDecl);
2122     } else if (HasInitializer) {
2123       // Normal initializer.
2124       if (!Init.isUsable())
2125         Init = ParseCXXMemberInitializer(ThisDecl,
2126                  DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2127       
2128       if (Init.isInvalid())
2129         SkipUntil(tok::comma, true, true);
2130       else if (ThisDecl)
2131         Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2132                                    DS.getTypeSpecType() == DeclSpec::TST_auto);      
2133     } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2134       // No initializer.
2135       Actions.ActOnUninitializedDecl(ThisDecl, 
2136                                    DS.getTypeSpecType() == DeclSpec::TST_auto);
2137     }
2138     
2139     if (ThisDecl) {
2140       Actions.FinalizeDeclaration(ThisDecl);
2141       DeclsInGroup.push_back(ThisDecl);
2142     }
2143     
2144     if (ThisDecl && DeclaratorInfo.isFunctionDeclarator() &&
2145         DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2146           != DeclSpec::SCS_typedef) {
2147       HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2148     }
2149
2150     DeclaratorInfo.complete(ThisDecl);
2151
2152     // If we don't have a comma, it is either the end of the list (a ';')
2153     // or an error, bail out.
2154     if (Tok.isNot(tok::comma))
2155       break;
2156
2157     // Consume the comma.
2158     SourceLocation CommaLoc = ConsumeToken();
2159
2160     if (Tok.isAtStartOfLine() &&
2161         !MightBeDeclarator(Declarator::MemberContext)) {
2162       // This comma was followed by a line-break and something which can't be
2163       // the start of a declarator. The comma was probably a typo for a
2164       // semicolon.
2165       Diag(CommaLoc, diag::err_expected_semi_declaration)
2166         << FixItHint::CreateReplacement(CommaLoc, ";");
2167       ExpectSemi = false;
2168       break;
2169     }
2170
2171     // Parse the next declarator.
2172     DeclaratorInfo.clear();
2173     VS.clear();
2174     BitfieldSize = true;
2175     Init = true;
2176     HasInitializer = false;
2177     DeclaratorInfo.setCommaLoc(CommaLoc);
2178
2179     // Attributes are only allowed on the second declarator.
2180     MaybeParseGNUAttributes(DeclaratorInfo);
2181
2182     if (Tok.isNot(tok::colon))
2183       ParseDeclarator(DeclaratorInfo);
2184   }
2185
2186   if (ExpectSemi &&
2187       ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2188     // Skip to end of block or statement.
2189     SkipUntil(tok::r_brace, true, true);
2190     // If we stopped at a ';', eat it.
2191     if (Tok.is(tok::semi)) ConsumeToken();
2192     return;
2193   }
2194
2195   Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(),
2196                                   DeclsInGroup.size());
2197 }
2198
2199 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
2200 /// pure-specifier. Also detect and reject any attempted defaulted/deleted
2201 /// function definition. The location of the '=', if any, will be placed in
2202 /// EqualLoc.
2203 ///
2204 ///   pure-specifier:
2205 ///     '= 0'
2206 ///
2207 ///   brace-or-equal-initializer:
2208 ///     '=' initializer-expression
2209 ///     braced-init-list
2210 ///
2211 ///   initializer-clause:
2212 ///     assignment-expression
2213 ///     braced-init-list
2214 ///
2215 ///   defaulted/deleted function-definition:                                                                                                                                                                                               
2216 ///     '=' 'default'
2217 ///     '=' 'delete'
2218 ///
2219 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2220 /// be a constant-expression.
2221 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2222                                              SourceLocation &EqualLoc) {
2223   assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
2224          && "Data member initializer not starting with '=' or '{'");
2225
2226   EnterExpressionEvaluationContext Context(Actions, 
2227                                            Sema::PotentiallyEvaluated,
2228                                            D);
2229   if (Tok.is(tok::equal)) {
2230     EqualLoc = ConsumeToken();
2231     if (Tok.is(tok::kw_delete)) {
2232       // In principle, an initializer of '= delete p;' is legal, but it will
2233       // never type-check. It's better to diagnose it as an ill-formed expression
2234       // than as an ill-formed deleted non-function member.
2235       // An initializer of '= delete p, foo' will never be parsed, because
2236       // a top-level comma always ends the initializer expression.
2237       const Token &Next = NextToken();
2238       if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) ||
2239            Next.is(tok::eof)) {
2240         if (IsFunction)
2241           Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2242             << 1 /* delete */;
2243         else
2244           Diag(ConsumeToken(), diag::err_deleted_non_function);
2245         return ExprResult();
2246       }
2247     } else if (Tok.is(tok::kw_default)) {
2248       if (IsFunction)
2249         Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2250           << 0 /* default */;
2251       else
2252         Diag(ConsumeToken(), diag::err_default_special_members);
2253       return ExprResult();
2254     }
2255
2256   }
2257   return ParseInitializer();
2258 }
2259
2260 /// ParseCXXMemberSpecification - Parse the class definition.
2261 ///
2262 ///       member-specification:
2263 ///         member-declaration member-specification[opt]
2264 ///         access-specifier ':' member-specification[opt]
2265 ///
2266 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2267                                          unsigned TagType, Decl *TagDecl) {
2268   assert((TagType == DeclSpec::TST_struct ||
2269          TagType == DeclSpec::TST_interface ||
2270          TagType == DeclSpec::TST_union  ||
2271          TagType == DeclSpec::TST_class) && "Invalid TagType!");
2272
2273   PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2274                                       "parsing struct/union/class body");
2275
2276   // Determine whether this is a non-nested class. Note that local
2277   // classes are *not* considered to be nested classes.
2278   bool NonNestedClass = true;
2279   if (!ClassStack.empty()) {
2280     for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2281       if (S->isClassScope()) {
2282         // We're inside a class scope, so this is a nested class.
2283         NonNestedClass = false;
2284
2285         // The Microsoft extension __interface does not permit nested classes.
2286         if (getCurrentClass().IsInterface) {
2287           Diag(RecordLoc, diag::err_invalid_member_in_interface)
2288             << /*ErrorType=*/6
2289             << (isa<NamedDecl>(TagDecl)
2290                   ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2291                   : "<anonymous>");
2292         }
2293         break;
2294       }
2295
2296       if ((S->getFlags() & Scope::FnScope)) {
2297         // If we're in a function or function template declared in the
2298         // body of a class, then this is a local class rather than a
2299         // nested class.
2300         const Scope *Parent = S->getParent();
2301         if (Parent->isTemplateParamScope())
2302           Parent = Parent->getParent();
2303         if (Parent->isClassScope())
2304           break;
2305       }
2306     }
2307   }
2308
2309   // Enter a scope for the class.
2310   ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2311
2312   // Note that we are parsing a new (potentially-nested) class definition.
2313   ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2314                                     TagType == DeclSpec::TST_interface);
2315
2316   if (TagDecl)
2317     Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2318
2319   SourceLocation FinalLoc;
2320
2321   // Parse the optional 'final' keyword.
2322   if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2323     assert(isCXX0XFinalKeyword() && "not a class definition");
2324     FinalLoc = ConsumeToken();
2325
2326     if (TagType == DeclSpec::TST_interface) {
2327       Diag(FinalLoc, diag::err_override_control_interface)
2328         << "final";
2329     } else {
2330       Diag(FinalLoc, getLangOpts().CPlusPlus0x ?
2331            diag::warn_cxx98_compat_override_control_keyword :
2332            diag::ext_override_control_keyword) << "final";
2333     }
2334   }
2335
2336   if (Tok.is(tok::colon)) {
2337     ParseBaseClause(TagDecl);
2338
2339     if (!Tok.is(tok::l_brace)) {
2340       Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
2341
2342       if (TagDecl)
2343         Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2344       return;
2345     }
2346   }
2347
2348   assert(Tok.is(tok::l_brace));
2349   BalancedDelimiterTracker T(*this, tok::l_brace);
2350   T.consumeOpen();
2351
2352   if (TagDecl)
2353     Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2354                                             T.getOpenLocation());
2355
2356   // C++ 11p3: Members of a class defined with the keyword class are private
2357   // by default. Members of a class defined with the keywords struct or union
2358   // are public by default.
2359   AccessSpecifier CurAS;
2360   if (TagType == DeclSpec::TST_class)
2361     CurAS = AS_private;
2362   else
2363     CurAS = AS_public;
2364   ParsedAttributes AccessAttrs(AttrFactory);
2365
2366   if (TagDecl) {
2367     // While we still have something to read, read the member-declarations.
2368     while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2369       // Each iteration of this loop reads one member-declaration.
2370
2371       if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
2372           Tok.is(tok::kw___if_not_exists))) {
2373         ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2374         continue;
2375       }
2376
2377       // Check for extraneous top-level semicolon.
2378       if (Tok.is(tok::semi)) {
2379         ConsumeExtraSemi(InsideStruct, TagType);
2380         continue;
2381       }
2382
2383       if (Tok.is(tok::annot_pragma_vis)) {
2384         HandlePragmaVisibility();
2385         continue;
2386       }
2387
2388       if (Tok.is(tok::annot_pragma_pack)) {
2389         HandlePragmaPack();
2390         continue;
2391       }
2392
2393       if (Tok.is(tok::annot_pragma_align)) {
2394         HandlePragmaAlign();
2395         continue;
2396       }
2397
2398       AccessSpecifier AS = getAccessSpecifierIfPresent();
2399       if (AS != AS_none) {
2400         // Current token is a C++ access specifier.
2401         CurAS = AS;
2402         SourceLocation ASLoc = Tok.getLocation();
2403         unsigned TokLength = Tok.getLength();
2404         ConsumeToken();
2405         AccessAttrs.clear();
2406         MaybeParseGNUAttributes(AccessAttrs);
2407
2408         SourceLocation EndLoc;
2409         if (Tok.is(tok::colon)) {
2410           EndLoc = Tok.getLocation();
2411           ConsumeToken();
2412         } else if (Tok.is(tok::semi)) {
2413           EndLoc = Tok.getLocation();
2414           ConsumeToken();
2415           Diag(EndLoc, diag::err_expected_colon) 
2416             << FixItHint::CreateReplacement(EndLoc, ":");
2417         } else {
2418           EndLoc = ASLoc.getLocWithOffset(TokLength);
2419           Diag(EndLoc, diag::err_expected_colon) 
2420             << FixItHint::CreateInsertion(EndLoc, ":");
2421         }
2422
2423         // The Microsoft extension __interface does not permit non-public
2424         // access specifiers.
2425         if (TagType == DeclSpec::TST_interface && CurAS != AS_public) {
2426           Diag(ASLoc, diag::err_access_specifier_interface)
2427             << (CurAS == AS_protected);
2428         }
2429
2430         if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
2431                                          AccessAttrs.getList())) {
2432           // found another attribute than only annotations
2433           AccessAttrs.clear();
2434         }
2435
2436         continue;
2437       }
2438
2439       // FIXME: Make sure we don't have a template here.
2440
2441       // Parse all the comma separated declarators.
2442       ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
2443     }
2444
2445     T.consumeClose();
2446   } else {
2447     SkipUntil(tok::r_brace, false, false);
2448   }
2449
2450   // If attributes exist after class contents, parse them.
2451   ParsedAttributes attrs(AttrFactory);
2452   MaybeParseGNUAttributes(attrs);
2453
2454   if (TagDecl)
2455     Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
2456                                               T.getOpenLocation(), 
2457                                               T.getCloseLocation(),
2458                                               attrs.getList());
2459
2460   // C++11 [class.mem]p2:
2461   //   Within the class member-specification, the class is regarded as complete
2462   //   within function bodies, default arguments, and
2463   //   brace-or-equal-initializers for non-static data members (including such
2464   //   things in nested classes).
2465   if (TagDecl && NonNestedClass) {
2466     // We are not inside a nested class. This class and its nested classes
2467     // are complete and we can parse the delayed portions of method
2468     // declarations and the lexed inline method definitions, along with any
2469     // delayed attributes.
2470     SourceLocation SavedPrevTokLocation = PrevTokLocation;
2471     ParseLexedAttributes(getCurrentClass());
2472     ParseLexedMethodDeclarations(getCurrentClass());
2473
2474     // We've finished with all pending member declarations.
2475     Actions.ActOnFinishCXXMemberDecls();
2476
2477     ParseLexedMemberInitializers(getCurrentClass());
2478     ParseLexedMethodDefs(getCurrentClass());
2479     PrevTokLocation = SavedPrevTokLocation;
2480   }
2481
2482   if (TagDecl)
2483     Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, 
2484                                      T.getCloseLocation());
2485
2486   // Leave the class scope.
2487   ParsingDef.Pop();
2488   ClassScope.Exit();
2489 }
2490
2491 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
2492 /// which explicitly initializes the members or base classes of a
2493 /// class (C++ [class.base.init]). For example, the three initializers
2494 /// after the ':' in the Derived constructor below:
2495 ///
2496 /// @code
2497 /// class Base { };
2498 /// class Derived : Base {
2499 ///   int x;
2500 ///   float f;
2501 /// public:
2502 ///   Derived(float f) : Base(), x(17), f(f) { }
2503 /// };
2504 /// @endcode
2505 ///
2506 /// [C++]  ctor-initializer:
2507 ///          ':' mem-initializer-list
2508 ///
2509 /// [C++]  mem-initializer-list:
2510 ///          mem-initializer ...[opt]
2511 ///          mem-initializer ...[opt] , mem-initializer-list
2512 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
2513   assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
2514
2515   // Poison the SEH identifiers so they are flagged as illegal in constructor initializers
2516   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
2517   SourceLocation ColonLoc = ConsumeToken();
2518
2519   SmallVector<CXXCtorInitializer*, 4> MemInitializers;
2520   bool AnyErrors = false;
2521
2522   do {
2523     if (Tok.is(tok::code_completion)) {
2524       Actions.CodeCompleteConstructorInitializer(ConstructorDecl, 
2525                                                  MemInitializers.data(), 
2526                                                  MemInitializers.size());
2527       return cutOffParsing();
2528     } else {
2529       MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
2530       if (!MemInit.isInvalid())
2531         MemInitializers.push_back(MemInit.get());
2532       else
2533         AnyErrors = true;
2534     }
2535     
2536     if (Tok.is(tok::comma))
2537       ConsumeToken();
2538     else if (Tok.is(tok::l_brace))
2539       break;
2540     // If the next token looks like a base or member initializer, assume that
2541     // we're just missing a comma.
2542     else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
2543       SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2544       Diag(Loc, diag::err_ctor_init_missing_comma)
2545         << FixItHint::CreateInsertion(Loc, ", ");
2546     } else {
2547       // Skip over garbage, until we get to '{'.  Don't eat the '{'.
2548       Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
2549       SkipUntil(tok::l_brace, true, true);
2550       break;
2551     }
2552   } while (true);
2553
2554   Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
2555                                MemInitializers.data(), MemInitializers.size(),
2556                                AnyErrors);
2557 }
2558
2559 /// ParseMemInitializer - Parse a C++ member initializer, which is
2560 /// part of a constructor initializer that explicitly initializes one
2561 /// member or base class (C++ [class.base.init]). See
2562 /// ParseConstructorInitializer for an example.
2563 ///
2564 /// [C++] mem-initializer:
2565 ///         mem-initializer-id '(' expression-list[opt] ')'
2566 /// [C++0x] mem-initializer-id braced-init-list
2567 ///
2568 /// [C++] mem-initializer-id:
2569 ///         '::'[opt] nested-name-specifier[opt] class-name
2570 ///         identifier
2571 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
2572   // parse '::'[opt] nested-name-specifier[opt]
2573   CXXScopeSpec SS;
2574   ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
2575   ParsedType TemplateTypeTy;
2576   if (Tok.is(tok::annot_template_id)) {
2577     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2578     if (TemplateId->Kind == TNK_Type_template ||
2579         TemplateId->Kind == TNK_Dependent_template_name) {
2580       AnnotateTemplateIdTokenAsType();
2581       assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
2582       TemplateTypeTy = getTypeAnnotation(Tok);
2583     }
2584   }
2585   // Uses of decltype will already have been converted to annot_decltype by
2586   // ParseOptionalCXXScopeSpecifier at this point.
2587   if (!TemplateTypeTy && Tok.isNot(tok::identifier)
2588       && Tok.isNot(tok::annot_decltype)) {
2589     Diag(Tok, diag::err_expected_member_or_base_name);
2590     return true;
2591   }
2592
2593   IdentifierInfo *II = 0;
2594   DeclSpec DS(AttrFactory);
2595   SourceLocation IdLoc = Tok.getLocation();
2596   if (Tok.is(tok::annot_decltype)) {
2597     // Get the decltype expression, if there is one.
2598     ParseDecltypeSpecifier(DS);
2599   } else {
2600     if (Tok.is(tok::identifier))
2601       // Get the identifier. This may be a member name or a class name,
2602       // but we'll let the semantic analysis determine which it is.
2603       II = Tok.getIdentifierInfo();
2604     ConsumeToken();
2605   }
2606
2607
2608   // Parse the '('.
2609   if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
2610     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2611
2612     ExprResult InitList = ParseBraceInitializer();
2613     if (InitList.isInvalid())
2614       return true;
2615
2616     SourceLocation EllipsisLoc;
2617     if (Tok.is(tok::ellipsis))
2618       EllipsisLoc = ConsumeToken();
2619
2620     return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2621                                        TemplateTypeTy, DS, IdLoc, 
2622                                        InitList.take(), EllipsisLoc);
2623   } else if(Tok.is(tok::l_paren)) {
2624     BalancedDelimiterTracker T(*this, tok::l_paren);
2625     T.consumeOpen();
2626
2627     // Parse the optional expression-list.
2628     ExprVector ArgExprs;
2629     CommaLocsTy CommaLocs;
2630     if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
2631       SkipUntil(tok::r_paren);
2632       return true;
2633     }
2634
2635     T.consumeClose();
2636
2637     SourceLocation EllipsisLoc;
2638     if (Tok.is(tok::ellipsis))
2639       EllipsisLoc = ConsumeToken();
2640
2641     return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2642                                        TemplateTypeTy, DS, IdLoc,
2643                                        T.getOpenLocation(), ArgExprs.data(),
2644                                        ArgExprs.size(), T.getCloseLocation(),
2645                                        EllipsisLoc);
2646   }
2647
2648   Diag(Tok, getLangOpts().CPlusPlus0x ? diag::err_expected_lparen_or_lbrace
2649                                   : diag::err_expected_lparen);
2650   return true;
2651 }
2652
2653 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
2654 ///
2655 ///       exception-specification:
2656 ///         dynamic-exception-specification
2657 ///         noexcept-specification
2658 ///
2659 ///       noexcept-specification:
2660 ///         'noexcept'
2661 ///         'noexcept' '(' constant-expression ')'
2662 ExceptionSpecificationType
2663 Parser::tryParseExceptionSpecification(
2664                     SourceRange &SpecificationRange,
2665                     SmallVectorImpl<ParsedType> &DynamicExceptions,
2666                     SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2667                     ExprResult &NoexceptExpr) {
2668   ExceptionSpecificationType Result = EST_None;
2669
2670   // See if there's a dynamic specification.
2671   if (Tok.is(tok::kw_throw)) {
2672     Result = ParseDynamicExceptionSpecification(SpecificationRange,
2673                                                 DynamicExceptions,
2674                                                 DynamicExceptionRanges);
2675     assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
2676            "Produced different number of exception types and ranges.");
2677   }
2678
2679   // If there's no noexcept specification, we're done.
2680   if (Tok.isNot(tok::kw_noexcept))
2681     return Result;
2682
2683   Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
2684
2685   // If we already had a dynamic specification, parse the noexcept for,
2686   // recovery, but emit a diagnostic and don't store the results.
2687   SourceRange NoexceptRange;
2688   ExceptionSpecificationType NoexceptType = EST_None;
2689
2690   SourceLocation KeywordLoc = ConsumeToken();
2691   if (Tok.is(tok::l_paren)) {
2692     // There is an argument.
2693     BalancedDelimiterTracker T(*this, tok::l_paren);
2694     T.consumeOpen();
2695     NoexceptType = EST_ComputedNoexcept;
2696     NoexceptExpr = ParseConstantExpression();
2697     // The argument must be contextually convertible to bool. We use
2698     // ActOnBooleanCondition for this purpose.
2699     if (!NoexceptExpr.isInvalid())
2700       NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
2701                                                    NoexceptExpr.get());
2702     T.consumeClose();
2703     NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
2704   } else {
2705     // There is no argument.
2706     NoexceptType = EST_BasicNoexcept;
2707     NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
2708   }
2709
2710   if (Result == EST_None) {
2711     SpecificationRange = NoexceptRange;
2712     Result = NoexceptType;
2713
2714     // If there's a dynamic specification after a noexcept specification,
2715     // parse that and ignore the results.
2716     if (Tok.is(tok::kw_throw)) {
2717       Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2718       ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
2719                                          DynamicExceptionRanges);
2720     }
2721   } else {
2722     Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2723   }
2724
2725   return Result;
2726 }
2727
2728 /// ParseDynamicExceptionSpecification - Parse a C++
2729 /// dynamic-exception-specification (C++ [except.spec]).
2730 ///
2731 ///       dynamic-exception-specification:
2732 ///         'throw' '(' type-id-list [opt] ')'
2733 /// [MS]    'throw' '(' '...' ')'
2734 ///
2735 ///       type-id-list:
2736 ///         type-id ... [opt]
2737 ///         type-id-list ',' type-id ... [opt]
2738 ///
2739 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
2740                                   SourceRange &SpecificationRange,
2741                                   SmallVectorImpl<ParsedType> &Exceptions,
2742                                   SmallVectorImpl<SourceRange> &Ranges) {
2743   assert(Tok.is(tok::kw_throw) && "expected throw");
2744
2745   SpecificationRange.setBegin(ConsumeToken());
2746   BalancedDelimiterTracker T(*this, tok::l_paren);
2747   if (T.consumeOpen()) {
2748     Diag(Tok, diag::err_expected_lparen_after) << "throw";
2749     SpecificationRange.setEnd(SpecificationRange.getBegin());
2750     return EST_DynamicNone;
2751   }
2752
2753   // Parse throw(...), a Microsoft extension that means "this function
2754   // can throw anything".
2755   if (Tok.is(tok::ellipsis)) {
2756     SourceLocation EllipsisLoc = ConsumeToken();
2757     if (!getLangOpts().MicrosoftExt)
2758       Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
2759     T.consumeClose();
2760     SpecificationRange.setEnd(T.getCloseLocation());
2761     return EST_MSAny;
2762   }
2763
2764   // Parse the sequence of type-ids.
2765   SourceRange Range;
2766   while (Tok.isNot(tok::r_paren)) {
2767     TypeResult Res(ParseTypeName(&Range));
2768
2769     if (Tok.is(tok::ellipsis)) {
2770       // C++0x [temp.variadic]p5:
2771       //   - In a dynamic-exception-specification (15.4); the pattern is a 
2772       //     type-id.
2773       SourceLocation Ellipsis = ConsumeToken();
2774       Range.setEnd(Ellipsis);
2775       if (!Res.isInvalid())
2776         Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
2777     }
2778
2779     if (!Res.isInvalid()) {
2780       Exceptions.push_back(Res.get());
2781       Ranges.push_back(Range);
2782     }
2783     
2784     if (Tok.is(tok::comma))
2785       ConsumeToken();
2786     else
2787       break;
2788   }
2789
2790   T.consumeClose();
2791   SpecificationRange.setEnd(T.getCloseLocation());
2792   return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
2793 }
2794
2795 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
2796 /// function declaration.
2797 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
2798   assert(Tok.is(tok::arrow) && "expected arrow");
2799
2800   ConsumeToken();
2801
2802   return ParseTypeName(&Range, Declarator::TrailingReturnContext);
2803 }
2804
2805 /// \brief We have just started parsing the definition of a new class,
2806 /// so push that class onto our stack of classes that is currently
2807 /// being parsed.
2808 Sema::ParsingClassState
2809 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
2810                          bool IsInterface) {
2811   assert((NonNestedClass || !ClassStack.empty()) &&
2812          "Nested class without outer class");
2813   ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
2814   return Actions.PushParsingClass();
2815 }
2816
2817 /// \brief Deallocate the given parsed class and all of its nested
2818 /// classes.
2819 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
2820   for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
2821     delete Class->LateParsedDeclarations[I];
2822   delete Class;
2823 }
2824
2825 /// \brief Pop the top class of the stack of classes that are
2826 /// currently being parsed.
2827 ///
2828 /// This routine should be called when we have finished parsing the
2829 /// definition of a class, but have not yet popped the Scope
2830 /// associated with the class's definition.
2831 void Parser::PopParsingClass(Sema::ParsingClassState state) {
2832   assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
2833
2834   Actions.PopParsingClass(state);
2835
2836   ParsingClass *Victim = ClassStack.top();
2837   ClassStack.pop();
2838   if (Victim->TopLevelClass) {
2839     // Deallocate all of the nested classes of this class,
2840     // recursively: we don't need to keep any of this information.
2841     DeallocateParsedClasses(Victim);
2842     return;
2843   }
2844   assert(!ClassStack.empty() && "Missing top-level class?");
2845
2846   if (Victim->LateParsedDeclarations.empty()) {
2847     // The victim is a nested class, but we will not need to perform
2848     // any processing after the definition of this class since it has
2849     // no members whose handling was delayed. Therefore, we can just
2850     // remove this nested class.
2851     DeallocateParsedClasses(Victim);
2852     return;
2853   }
2854
2855   // This nested class has some members that will need to be processed
2856   // after the top-level class is completely defined. Therefore, add
2857   // it to the list of nested classes within its parent.
2858   assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
2859   ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
2860   Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
2861 }
2862
2863 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
2864 ///
2865 /// \return the parsed identifier on success, and 0 if the next token is not an
2866 /// attribute-token.
2867 ///
2868 /// C++11 [dcl.attr.grammar]p3:
2869 ///   If a keyword or an alternative token that satisfies the syntactic
2870 ///   requirements of an identifier is contained in an attribute-token,
2871 ///   it is considered an identifier.
2872 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
2873   switch (Tok.getKind()) {
2874   default:
2875     // Identifiers and keywords have identifier info attached.
2876     if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
2877       Loc = ConsumeToken();
2878       return II;
2879     }
2880     return 0;
2881
2882   case tok::ampamp:       // 'and'
2883   case tok::pipe:         // 'bitor'
2884   case tok::pipepipe:     // 'or'
2885   case tok::caret:        // 'xor'
2886   case tok::tilde:        // 'compl'
2887   case tok::amp:          // 'bitand'
2888   case tok::ampequal:     // 'and_eq'
2889   case tok::pipeequal:    // 'or_eq'
2890   case tok::caretequal:   // 'xor_eq'
2891   case tok::exclaim:      // 'not'
2892   case tok::exclaimequal: // 'not_eq'
2893     // Alternative tokens do not have identifier info, but their spelling
2894     // starts with an alphabetical character.
2895     llvm::SmallString<8> SpellingBuf;
2896     StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf);
2897     if (std::isalpha(Spelling[0])) {
2898       Loc = ConsumeToken();
2899       return &PP.getIdentifierTable().get(Spelling);
2900     }
2901     return 0;
2902   }
2903 }
2904
2905 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
2906                                                IdentifierInfo *ScopeName) {
2907   switch (AttributeList::getKind(AttrName, ScopeName,
2908                                  AttributeList::AS_CXX11)) {
2909   case AttributeList::AT_CarriesDependency:
2910   case AttributeList::AT_FallThrough:
2911   case AttributeList::AT_NoReturn: {
2912     return true;
2913   }
2914
2915   default:
2916     return false;
2917   }
2918 }
2919
2920 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Currently
2921 /// only parses standard attributes.
2922 ///
2923 /// [C++11] attribute-specifier:
2924 ///         '[' '[' attribute-list ']' ']'
2925 ///         alignment-specifier
2926 ///
2927 /// [C++11] attribute-list:
2928 ///         attribute[opt]
2929 ///         attribute-list ',' attribute[opt]
2930 ///         attribute '...'
2931 ///         attribute-list ',' attribute '...'
2932 ///
2933 /// [C++11] attribute:
2934 ///         attribute-token attribute-argument-clause[opt]
2935 ///
2936 /// [C++11] attribute-token:
2937 ///         identifier
2938 ///         attribute-scoped-token
2939 ///
2940 /// [C++11] attribute-scoped-token:
2941 ///         attribute-namespace '::' identifier
2942 ///
2943 /// [C++11] attribute-namespace:
2944 ///         identifier
2945 ///
2946 /// [C++11] attribute-argument-clause:
2947 ///         '(' balanced-token-seq ')'
2948 ///
2949 /// [C++11] balanced-token-seq:
2950 ///         balanced-token
2951 ///         balanced-token-seq balanced-token
2952 ///
2953 /// [C++11] balanced-token:
2954 ///         '(' balanced-token-seq ')'
2955 ///         '[' balanced-token-seq ']'
2956 ///         '{' balanced-token-seq '}'
2957 ///         any token but '(', ')', '[', ']', '{', or '}'
2958 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2959                                           SourceLocation *endLoc) {
2960   if (Tok.is(tok::kw_alignas)) {
2961     Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
2962     ParseAlignmentSpecifier(attrs, endLoc);
2963     return;
2964   }
2965
2966   assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
2967       && "Not a C++11 attribute list");
2968
2969   Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
2970
2971   ConsumeBracket();
2972   ConsumeBracket();
2973
2974   while (Tok.isNot(tok::r_square)) {
2975     // attribute not present
2976     if (Tok.is(tok::comma)) {
2977       ConsumeToken();
2978       continue;
2979     }
2980
2981     SourceLocation ScopeLoc, AttrLoc;
2982     IdentifierInfo *ScopeName = 0, *AttrName = 0;
2983
2984     AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
2985     if (!AttrName)
2986       // Break out to the "expected ']'" diagnostic.
2987       break;
2988
2989     // scoped attribute
2990     if (Tok.is(tok::coloncolon)) {
2991       ConsumeToken();
2992
2993       ScopeName = AttrName;
2994       ScopeLoc = AttrLoc;
2995
2996       AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
2997       if (!AttrName) {
2998         Diag(Tok.getLocation(), diag::err_expected_ident);
2999         SkipUntil(tok::r_square, tok::comma, true, true);
3000         continue;
3001       }
3002     }
3003
3004     bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName,ScopeName);
3005     bool AttrParsed = false;
3006
3007     // Parse attribute arguments
3008     if (Tok.is(tok::l_paren)) {
3009       if (ScopeName && ScopeName->getName() == "gnu") {
3010         ParseGNUAttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3011                               ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3012         AttrParsed = true;
3013       } else {
3014         if (StandardAttr)
3015           Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_arguments)
3016             << AttrName->getName();
3017
3018         // FIXME: handle other formats of c++11 attribute arguments
3019         ConsumeParen();
3020         SkipUntil(tok::r_paren, false);
3021       }
3022     }
3023
3024     if (!AttrParsed)
3025       attrs.addNew(AttrName,
3026                    SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3027                                AttrLoc),
3028                    ScopeName, ScopeLoc, 0,
3029                    SourceLocation(), 0, 0, AttributeList::AS_CXX11);
3030
3031     if (Tok.is(tok::ellipsis)) {
3032       ConsumeToken();
3033
3034       Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3035         << AttrName->getName();
3036     }
3037   }
3038
3039   if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
3040     SkipUntil(tok::r_square, false);
3041   if (endLoc)
3042     *endLoc = Tok.getLocation();
3043   if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
3044     SkipUntil(tok::r_square, false);
3045 }
3046
3047 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3048 ///
3049 /// attribute-specifier-seq:
3050 ///       attribute-specifier-seq[opt] attribute-specifier
3051 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3052                                   SourceLocation *endLoc) {
3053   SourceLocation StartLoc = Tok.getLocation(), Loc;
3054   if (!endLoc)
3055     endLoc = &Loc;
3056
3057   do {
3058     ParseCXX11AttributeSpecifier(attrs, endLoc);
3059   } while (isCXX11AttributeSpecifier());
3060
3061   attrs.Range = SourceRange(StartLoc, *endLoc);
3062 }
3063
3064 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
3065 ///
3066 /// [MS] ms-attribute:
3067 ///             '[' token-seq ']'
3068 ///
3069 /// [MS] ms-attribute-seq:
3070 ///             ms-attribute[opt]
3071 ///             ms-attribute ms-attribute-seq
3072 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3073                                       SourceLocation *endLoc) {
3074   assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3075
3076   while (Tok.is(tok::l_square)) {
3077     // FIXME: If this is actually a C++11 attribute, parse it as one.
3078     ConsumeBracket();
3079     SkipUntil(tok::r_square, true, true);
3080     if (endLoc) *endLoc = Tok.getLocation();
3081     ExpectAndConsume(tok::r_square, diag::err_expected_rsquare);
3082   }
3083 }
3084
3085 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3086                                                     AccessSpecifier& CurAS) {
3087   IfExistsCondition Result;
3088   if (ParseMicrosoftIfExistsCondition(Result))
3089     return;
3090   
3091   BalancedDelimiterTracker Braces(*this, tok::l_brace);
3092   if (Braces.consumeOpen()) {
3093     Diag(Tok, diag::err_expected_lbrace);
3094     return;
3095   }
3096
3097   switch (Result.Behavior) {
3098   case IEB_Parse:
3099     // Parse the declarations below.
3100     break;
3101         
3102   case IEB_Dependent:
3103     Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3104       << Result.IsIfExists;
3105     // Fall through to skip.
3106       
3107   case IEB_Skip:
3108     Braces.skipToEnd();
3109     return;
3110   }
3111
3112   while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
3113     // __if_exists, __if_not_exists can nest.
3114     if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
3115       ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3116       continue;
3117     }
3118
3119     // Check for extraneous top-level semicolon.
3120     if (Tok.is(tok::semi)) {
3121       ConsumeExtraSemi(InsideStruct, TagType);
3122       continue;
3123     }
3124
3125     AccessSpecifier AS = getAccessSpecifierIfPresent();
3126     if (AS != AS_none) {
3127       // Current token is a C++ access specifier.
3128       CurAS = AS;
3129       SourceLocation ASLoc = Tok.getLocation();
3130       ConsumeToken();
3131       if (Tok.is(tok::colon))
3132         Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3133       else
3134         Diag(Tok, diag::err_expected_colon);
3135       ConsumeToken();
3136       continue;
3137     }
3138
3139     // Parse all the comma separated declarators.
3140     ParseCXXClassMemberDeclaration(CurAS, 0);
3141   }
3142   
3143   Braces.consumeClose();
3144 }