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