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