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