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