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