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