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