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