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