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