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