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