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