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