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