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