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