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