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