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