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