1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++ Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/PrettyDeclStackTrace.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/Parse/RAIIObjectsForParser.h"
24 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/ParsedTemplate.h"
26 #include "clang/Sema/Scope.h"
27 #include "llvm/ADT/SmallString.h"
29 using namespace clang;
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.
35 /// namespace-definition: [C++: namespace.def]
36 /// named-namespace-definition
37 /// unnamed-namespace-definition
38 /// nested-namespace-definition
40 /// named-namespace-definition:
41 /// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
42 /// namespace-body '}'
44 /// unnamed-namespace-definition:
45 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
47 /// nested-namespace-definition:
48 /// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
49 /// identifier '{' namespace-body '}'
51 /// enclosing-namespace-specifier:
53 /// enclosing-namespace-specifier '::' 'inline'[opt] identifier
55 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
56 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
58 Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
59 SourceLocation &DeclEnd,
60 SourceLocation InlineLoc) {
61 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
62 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
63 ObjCDeclContextSwitch ObjCDC(*this);
65 if (Tok.is(tok::code_completion)) {
66 Actions.CodeCompleteNamespaceDecl(getCurScope());
71 SourceLocation IdentLoc;
72 IdentifierInfo *Ident = nullptr;
73 InnerNamespaceInfoList ExtraNSs;
74 SourceLocation FirstNestedInlineLoc;
76 ParsedAttributesWithRange attrs(AttrFactory);
77 SourceLocation attrLoc;
78 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
79 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
80 ? diag::warn_cxx14_compat_ns_enum_attribute
81 : diag::ext_ns_enum_attribute)
83 attrLoc = Tok.getLocation();
84 ParseCXX11Attributes(attrs);
87 if (Tok.is(tok::identifier)) {
88 Ident = Tok.getIdentifierInfo();
89 IdentLoc = ConsumeToken(); // eat the identifier.
90 while (Tok.is(tok::coloncolon) &&
91 (NextToken().is(tok::identifier) ||
92 (NextToken().is(tok::kw_inline) &&
93 GetLookAheadToken(2).is(tok::identifier)))) {
95 InnerNamespaceInfo Info;
96 Info.NamespaceLoc = ConsumeToken();
98 if (Tok.is(tok::kw_inline)) {
99 Info.InlineLoc = ConsumeToken();
100 if (FirstNestedInlineLoc.isInvalid())
101 FirstNestedInlineLoc = Info.InlineLoc;
104 Info.Ident = Tok.getIdentifierInfo();
105 Info.IdentLoc = ConsumeToken();
107 ExtraNSs.push_back(Info);
111 // A nested namespace definition cannot have attributes.
112 if (!ExtraNSs.empty() && attrLoc.isValid())
113 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
115 // Read label attributes, if present.
116 if (Tok.is(tok::kw___attribute)) {
117 attrLoc = Tok.getLocation();
118 ParseGNUAttributes(attrs);
121 if (Tok.is(tok::equal)) {
123 Diag(Tok, diag::err_expected) << tok::identifier;
124 // Skip to end of the definition and eat the ';'.
125 SkipUntil(tok::semi);
128 if (attrLoc.isValid())
129 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
130 if (InlineLoc.isValid())
131 Diag(InlineLoc, diag::err_inline_namespace_alias)
132 << FixItHint::CreateRemoval(InlineLoc);
133 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
134 return Actions.ConvertDeclToDeclGroup(NSAlias);
137 BalancedDelimiterTracker T(*this, tok::l_brace);
138 if (T.consumeOpen()) {
140 Diag(Tok, diag::err_expected) << tok::l_brace;
142 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
146 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
147 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
148 getCurScope()->getFnParent()) {
149 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
150 SkipUntil(tok::r_brace);
154 if (ExtraNSs.empty()) {
155 // Normal namespace definition, not a nested-namespace-definition.
156 } else if (InlineLoc.isValid()) {
157 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
158 } else if (getLangOpts().CPlusPlus2a) {
159 Diag(ExtraNSs[0].NamespaceLoc,
160 diag::warn_cxx14_compat_nested_namespace_definition);
161 if (FirstNestedInlineLoc.isValid())
162 Diag(FirstNestedInlineLoc,
163 diag::warn_cxx17_compat_inline_nested_namespace_definition);
164 } else if (getLangOpts().CPlusPlus17) {
165 Diag(ExtraNSs[0].NamespaceLoc,
166 diag::warn_cxx14_compat_nested_namespace_definition);
167 if (FirstNestedInlineLoc.isValid())
168 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
170 TentativeParsingAction TPA(*this);
171 SkipUntil(tok::r_brace, StopBeforeMatch);
172 Token rBraceToken = Tok;
175 if (!rBraceToken.is(tok::r_brace)) {
176 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
177 << SourceRange(ExtraNSs.front().NamespaceLoc,
178 ExtraNSs.back().IdentLoc);
180 std::string NamespaceFix;
181 for (const auto &ExtraNS : ExtraNSs) {
182 NamespaceFix += " { ";
183 if (ExtraNS.InlineLoc.isValid())
184 NamespaceFix += "inline ";
185 NamespaceFix += "namespace ";
186 NamespaceFix += ExtraNS.Ident->getName();
190 for (unsigned i = 0, e = ExtraNSs.size(); i != e; ++i)
193 Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
194 << FixItHint::CreateReplacement(
195 SourceRange(ExtraNSs.front().NamespaceLoc,
196 ExtraNSs.back().IdentLoc),
198 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
201 // Warn about nested inline namespaces.
202 if (FirstNestedInlineLoc.isValid())
203 Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
206 // If we're still good, complain about inline namespaces in non-C++0x now.
207 if (InlineLoc.isValid())
208 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
209 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
211 // Enter a scope for the namespace.
212 ParseScope NamespaceScope(this, Scope::DeclScope);
214 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
215 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
216 getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
217 T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
219 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
220 NamespaceLoc, "parsing namespace");
222 // Parse the contents of the namespace. This includes parsing recovery on
223 // any improperly nested namespaces.
224 ParseInnerNamespace(ExtraNSs, 0, InlineLoc, attrs, T);
226 // Leave the namespace scope.
227 NamespaceScope.Exit();
229 DeclEnd = T.getCloseLocation();
230 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
232 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
233 ImplicitUsingDirectiveDecl);
236 /// ParseInnerNamespace - Parse the contents of a namespace.
237 void Parser::ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
238 unsigned int index, SourceLocation &InlineLoc,
239 ParsedAttributes &attrs,
240 BalancedDelimiterTracker &Tracker) {
241 if (index == InnerNSs.size()) {
242 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
243 Tok.isNot(tok::eof)) {
244 ParsedAttributesWithRange attrs(AttrFactory);
245 MaybeParseCXX11Attributes(attrs);
246 ParseExternalDeclaration(attrs);
249 // The caller is what called check -- we are simply calling
251 Tracker.consumeClose();
256 // Handle a nested namespace definition.
257 // FIXME: Preserve the source information through to the AST rather than
258 // desugaring it here.
259 ParseScope NamespaceScope(this, Scope::DeclScope);
260 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
261 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
262 getCurScope(), InnerNSs[index].InlineLoc, InnerNSs[index].NamespaceLoc,
263 InnerNSs[index].IdentLoc, InnerNSs[index].Ident,
264 Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
265 assert(!ImplicitUsingDirectiveDecl &&
266 "nested namespace definition cannot define anonymous namespace");
268 ParseInnerNamespace(InnerNSs, ++index, InlineLoc, attrs, Tracker);
270 NamespaceScope.Exit();
271 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
274 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
275 /// alias definition.
277 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
278 SourceLocation AliasLoc,
279 IdentifierInfo *Alias,
280 SourceLocation &DeclEnd) {
281 assert(Tok.is(tok::equal) && "Not equal token");
283 ConsumeToken(); // eat the '='.
285 if (Tok.is(tok::code_completion)) {
286 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
292 // Parse (optional) nested-name-specifier.
293 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
294 /*MayBePseudoDestructor=*/nullptr,
295 /*IsTypename=*/false,
297 /*OnlyNamespace=*/true);
299 if (Tok.isNot(tok::identifier)) {
300 Diag(Tok, diag::err_expected_namespace_name);
301 // Skip to end of the definition and eat the ';'.
302 SkipUntil(tok::semi);
306 if (SS.isInvalid()) {
307 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
308 // Skip to end of the definition and eat the ';'.
309 SkipUntil(tok::semi);
314 IdentifierInfo *Ident = Tok.getIdentifierInfo();
315 SourceLocation IdentLoc = ConsumeToken();
318 DeclEnd = Tok.getLocation();
319 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
320 SkipUntil(tok::semi);
322 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
323 Alias, SS, IdentLoc, Ident);
326 /// ParseLinkage - We know that the current token is a string_literal
327 /// and just before that, that extern was seen.
329 /// linkage-specification: [C++ 7.5p2: dcl.link]
330 /// 'extern' string-literal '{' declaration-seq[opt] '}'
331 /// 'extern' string-literal declaration
333 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
334 assert(isTokenStringLiteral() && "Not a string literal!");
335 ExprResult Lang = ParseStringLiteralExpression(false);
337 ParseScope LinkageScope(this, Scope::DeclScope);
341 : Actions.ActOnStartLinkageSpecification(
342 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
343 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
345 ParsedAttributesWithRange attrs(AttrFactory);
346 MaybeParseCXX11Attributes(attrs);
348 if (Tok.isNot(tok::l_brace)) {
349 // Reset the source range in DS, as the leading "extern"
350 // does not really belong to the inner declaration ...
351 DS.SetRangeStart(SourceLocation());
352 DS.SetRangeEnd(SourceLocation());
353 // ... but anyway remember that such an "extern" was seen.
354 DS.setExternInLinkageSpec(true);
355 ParseExternalDeclaration(attrs, &DS);
356 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
357 getCurScope(), LinkageSpec, SourceLocation())
363 ProhibitAttributes(attrs);
365 BalancedDelimiterTracker T(*this, tok::l_brace);
368 unsigned NestedModules = 0;
370 switch (Tok.getKind()) {
371 case tok::annot_module_begin:
376 case tok::annot_module_end:
383 case tok::annot_module_include:
395 ParsedAttributesWithRange attrs(AttrFactory);
396 MaybeParseCXX11Attributes(attrs);
397 ParseExternalDeclaration(attrs);
405 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
406 getCurScope(), LinkageSpec, T.getCloseLocation())
410 /// Parse a C++ Modules TS export-declaration.
412 /// export-declaration:
413 /// 'export' declaration
414 /// 'export' '{' declaration-seq[opt] '}'
416 Decl *Parser::ParseExportDeclaration() {
417 assert(Tok.is(tok::kw_export));
418 SourceLocation ExportLoc = ConsumeToken();
420 ParseScope ExportScope(this, Scope::DeclScope);
421 Decl *ExportDecl = Actions.ActOnStartExportDecl(
422 getCurScope(), ExportLoc,
423 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
425 if (Tok.isNot(tok::l_brace)) {
426 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
427 ParsedAttributesWithRange Attrs(AttrFactory);
428 MaybeParseCXX11Attributes(Attrs);
429 MaybeParseMicrosoftAttributes(Attrs);
430 ParseExternalDeclaration(Attrs);
431 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
435 BalancedDelimiterTracker T(*this, tok::l_brace);
438 // The Modules TS draft says "An export-declaration shall declare at least one
439 // entity", but the intent is that it shall contain at least one declaration.
440 if (Tok.is(tok::r_brace))
441 Diag(ExportLoc, diag::err_export_empty)
442 << SourceRange(ExportLoc, Tok.getLocation());
444 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
445 Tok.isNot(tok::eof)) {
446 ParsedAttributesWithRange Attrs(AttrFactory);
447 MaybeParseCXX11Attributes(Attrs);
448 MaybeParseMicrosoftAttributes(Attrs);
449 ParseExternalDeclaration(Attrs);
453 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
454 T.getCloseLocation());
457 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
458 /// using-directive. Assumes that current token is 'using'.
459 Parser::DeclGroupPtrTy
460 Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
461 const ParsedTemplateInfo &TemplateInfo,
462 SourceLocation &DeclEnd,
463 ParsedAttributesWithRange &attrs) {
464 assert(Tok.is(tok::kw_using) && "Not using token");
465 ObjCDeclContextSwitch ObjCDC(*this);
468 SourceLocation UsingLoc = ConsumeToken();
470 if (Tok.is(tok::code_completion)) {
471 Actions.CodeCompleteUsing(getCurScope());
476 // 'using namespace' means this is a using-directive.
477 if (Tok.is(tok::kw_namespace)) {
478 // Template parameters are always an error here.
479 if (TemplateInfo.Kind) {
480 SourceRange R = TemplateInfo.getSourceRange();
481 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
482 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
485 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
486 return Actions.ConvertDeclToDeclGroup(UsingDir);
489 // Otherwise, it must be a using-declaration or an alias-declaration.
491 // Using declarations can't have attributes.
492 ProhibitAttributes(attrs);
494 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
498 /// ParseUsingDirective - Parse C++ using-directive, assumes
499 /// that current token is 'namespace' and 'using' was already parsed.
501 /// using-directive: [C++ 7.3.p4: namespace.udir]
502 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
504 /// [GNU] using-directive:
505 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
506 /// namespace-name attributes[opt] ;
508 Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
509 SourceLocation UsingLoc,
510 SourceLocation &DeclEnd,
511 ParsedAttributes &attrs) {
512 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
515 SourceLocation NamespcLoc = ConsumeToken();
517 if (Tok.is(tok::code_completion)) {
518 Actions.CodeCompleteUsingDirective(getCurScope());
524 // Parse (optional) nested-name-specifier.
525 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
526 /*MayBePseudoDestructor=*/nullptr,
527 /*IsTypename=*/false,
529 /*OnlyNamespace=*/true);
531 IdentifierInfo *NamespcName = nullptr;
532 SourceLocation IdentLoc = SourceLocation();
534 // Parse namespace-name.
535 if (Tok.isNot(tok::identifier)) {
536 Diag(Tok, diag::err_expected_namespace_name);
537 // If there was invalid namespace name, skip to end of decl, and eat ';'.
538 SkipUntil(tok::semi);
539 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
543 if (SS.isInvalid()) {
544 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
545 // Skip to end of the definition and eat the ';'.
546 SkipUntil(tok::semi);
551 NamespcName = Tok.getIdentifierInfo();
552 IdentLoc = ConsumeToken();
554 // Parse (optional) attributes (most likely GNU strong-using extension).
555 bool GNUAttr = false;
556 if (Tok.is(tok::kw___attribute)) {
558 ParseGNUAttributes(attrs);
562 DeclEnd = Tok.getLocation();
563 if (ExpectAndConsume(tok::semi,
564 GNUAttr ? diag::err_expected_semi_after_attribute_list
565 : diag::err_expected_semi_after_namespace_name))
566 SkipUntil(tok::semi);
568 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
569 IdentLoc, NamespcName, attrs);
572 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
574 /// using-declarator:
575 /// 'typename'[opt] nested-name-specifier unqualified-id
577 bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
578 UsingDeclarator &D) {
581 // Ignore optional 'typename'.
582 // FIXME: This is wrong; we should parse this as a typename-specifier.
583 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
585 if (Tok.is(tok::kw___super)) {
586 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
590 // Parse nested-name-specifier.
591 IdentifierInfo *LastII = nullptr;
592 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
593 /*MayBePseudoDtor=*/nullptr,
594 /*IsTypename=*/false,
596 if (D.SS.isInvalid())
599 // Parse the unqualified-id. We allow parsing of both constructor and
600 // destructor names and allow the action module to diagnose any semantic
603 // C++11 [class.qual]p2:
604 // [...] in a using-declaration that is a member-declaration, if the name
605 // specified after the nested-name-specifier is the same as the identifier
606 // or the simple-template-id's template-name in the last component of the
607 // nested-name-specifier, the name is [...] considered to name the
609 if (getLangOpts().CPlusPlus11 &&
610 Context == DeclaratorContext::MemberContext &&
611 Tok.is(tok::identifier) &&
612 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
613 NextToken().is(tok::ellipsis)) &&
614 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
615 !D.SS.getScopeRep()->getAsNamespace() &&
616 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
617 SourceLocation IdLoc = ConsumeToken();
619 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
620 D.Name.setConstructorName(Type, IdLoc, IdLoc);
622 if (ParseUnqualifiedId(
623 D.SS, /*EnteringContext=*/false,
624 /*AllowDestructorName=*/true,
625 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
626 NextToken().is(tok::equal)),
627 /*AllowDeductionGuide=*/false,
628 nullptr, nullptr, D.Name))
632 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
633 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
634 diag::warn_cxx17_compat_using_declaration_pack :
635 diag::ext_using_declaration_pack);
640 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
641 /// Assumes that 'using' was already seen.
643 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
644 /// 'using' using-declarator-list[opt] ;
646 /// using-declarator-list: [C++1z]
647 /// using-declarator '...'[opt]
648 /// using-declarator-list ',' using-declarator '...'[opt]
650 /// using-declarator-list: [C++98-14]
653 /// alias-declaration: C++11 [dcl.dcl]p1
654 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
656 Parser::DeclGroupPtrTy
657 Parser::ParseUsingDeclaration(DeclaratorContext Context,
658 const ParsedTemplateInfo &TemplateInfo,
659 SourceLocation UsingLoc, SourceLocation &DeclEnd,
660 AccessSpecifier AS) {
661 // Check for misplaced attributes before the identifier in an
662 // alias-declaration.
663 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
664 MaybeParseCXX11Attributes(MisplacedAttrs);
667 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
669 ParsedAttributesWithRange Attrs(AttrFactory);
670 MaybeParseGNUAttributes(Attrs);
671 MaybeParseCXX11Attributes(Attrs);
673 // Maybe this is an alias-declaration.
674 if (Tok.is(tok::equal)) {
675 if (InvalidDeclarator) {
676 SkipUntil(tok::semi);
680 // If we had any misplaced attributes from earlier, this is where they
681 // should have been written.
682 if (MisplacedAttrs.Range.isValid()) {
683 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
684 << FixItHint::CreateInsertionFromRange(
686 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
687 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
688 Attrs.takeAllFrom(MisplacedAttrs);
691 Decl *DeclFromDeclSpec = nullptr;
692 Decl *AD = ParseAliasDeclarationAfterDeclarator(
693 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
694 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
697 // C++11 attributes are not allowed on a using-declaration, but GNU ones
699 ProhibitAttributes(MisplacedAttrs);
700 ProhibitAttributes(Attrs);
702 // Diagnose an attempt to declare a templated using-declaration.
703 // In C++11, alias-declarations can be templates:
704 // template <...> using id = type;
705 if (TemplateInfo.Kind) {
706 SourceRange R = TemplateInfo.getSourceRange();
707 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
708 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
710 // Unfortunately, we have to bail out instead of recovering by
711 // ignoring the parameters, just in case the nested name specifier
712 // depends on the parameters.
716 SmallVector<Decl *, 8> DeclsInGroup;
718 // Parse (optional) attributes (most likely GNU strong-using extension).
719 MaybeParseGNUAttributes(Attrs);
721 if (InvalidDeclarator)
722 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
724 // "typename" keyword is allowed for identifiers only,
725 // because it may be a type definition.
726 if (D.TypenameLoc.isValid() &&
727 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
728 Diag(D.Name.getSourceRange().getBegin(),
729 diag::err_typename_identifiers_only)
730 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
731 // Proceed parsing, but discard the typename keyword.
732 D.TypenameLoc = SourceLocation();
735 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
736 D.TypenameLoc, D.SS, D.Name,
737 D.EllipsisLoc, Attrs);
739 DeclsInGroup.push_back(UD);
742 if (!TryConsumeToken(tok::comma))
745 // Parse another using-declarator.
747 InvalidDeclarator = ParseUsingDeclarator(Context, D);
750 if (DeclsInGroup.size() > 1)
751 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
752 diag::warn_cxx17_compat_multi_using_declaration :
753 diag::ext_multi_using_declaration);
756 DeclEnd = Tok.getLocation();
757 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
758 !Attrs.empty() ? "attributes list"
759 : "using declaration"))
760 SkipUntil(tok::semi);
762 return Actions.BuildDeclaratorGroup(DeclsInGroup);
765 Decl *Parser::ParseAliasDeclarationAfterDeclarator(
766 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
767 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
768 ParsedAttributes &Attrs, Decl **OwnedType) {
769 if (ExpectAndConsume(tok::equal)) {
770 SkipUntil(tok::semi);
774 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
775 diag::warn_cxx98_compat_alias_declaration :
776 diag::ext_alias_declaration);
778 // Type alias templates cannot be specialized.
780 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
781 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
783 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
785 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
787 if (SpecKind != -1) {
790 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
791 D.Name.TemplateId->RAngleLoc);
793 Range = TemplateInfo.getSourceRange();
794 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
795 << SpecKind << Range;
796 SkipUntil(tok::semi);
800 // Name must be an identifier.
801 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
802 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
803 // No removal fixit: can't recover from this.
804 SkipUntil(tok::semi);
806 } else if (D.TypenameLoc.isValid())
807 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
808 << FixItHint::CreateRemoval(SourceRange(
810 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
811 else if (D.SS.isNotEmpty())
812 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
813 << FixItHint::CreateRemoval(D.SS.getRange());
814 if (D.EllipsisLoc.isValid())
815 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
816 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
818 Decl *DeclFromDeclSpec = nullptr;
819 TypeResult TypeAlias = ParseTypeName(
821 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
822 : DeclaratorContext::AliasDeclContext,
823 AS, &DeclFromDeclSpec, &Attrs);
825 *OwnedType = DeclFromDeclSpec;
828 DeclEnd = Tok.getLocation();
829 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
830 !Attrs.empty() ? "attributes list"
831 : "alias declaration"))
832 SkipUntil(tok::semi);
834 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
835 MultiTemplateParamsArg TemplateParamsArg(
836 TemplateParams ? TemplateParams->data() : nullptr,
837 TemplateParams ? TemplateParams->size() : 0);
838 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
839 UsingLoc, D.Name, Attrs, TypeAlias,
843 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
845 /// [C++0x] static_assert-declaration:
846 /// static_assert ( constant-expression , string-literal ) ;
848 /// [C11] static_assert-declaration:
849 /// _Static_assert ( constant-expression , string-literal ) ;
851 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
852 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
853 "Not a static_assert declaration");
855 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
856 Diag(Tok, diag::ext_c11_static_assert);
857 if (Tok.is(tok::kw_static_assert))
858 Diag(Tok, diag::warn_cxx98_compat_static_assert);
860 SourceLocation StaticAssertLoc = ConsumeToken();
862 BalancedDelimiterTracker T(*this, tok::l_paren);
863 if (T.consumeOpen()) {
864 Diag(Tok, diag::err_expected) << tok::l_paren;
869 EnterExpressionEvaluationContext ConstantEvaluated(
870 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
871 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
872 if (AssertExpr.isInvalid()) {
877 ExprResult AssertMessage;
878 if (Tok.is(tok::r_paren)) {
879 Diag(Tok, getLangOpts().CPlusPlus17
880 ? diag::warn_cxx14_compat_static_assert_no_message
881 : diag::ext_static_assert_no_message)
882 << (getLangOpts().CPlusPlus17
884 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
886 if (ExpectAndConsume(tok::comma)) {
887 SkipUntil(tok::semi);
891 if (!isTokenStringLiteral()) {
892 Diag(Tok, diag::err_expected_string_literal)
893 << /*Source='static_assert'*/1;
898 AssertMessage = ParseStringLiteralExpression();
899 if (AssertMessage.isInvalid()) {
907 DeclEnd = Tok.getLocation();
908 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
910 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
913 T.getCloseLocation());
916 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
918 /// 'decltype' ( expression )
919 /// 'decltype' ( 'auto' ) [C++1y]
921 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
922 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
923 && "Not a decltype specifier");
926 SourceLocation StartLoc = Tok.getLocation();
927 SourceLocation EndLoc;
929 if (Tok.is(tok::annot_decltype)) {
930 Result = getExprAnnotation(Tok);
931 EndLoc = Tok.getAnnotationEndLoc();
932 ConsumeAnnotationToken();
933 if (Result.isInvalid()) {
934 DS.SetTypeSpecError();
938 if (Tok.getIdentifierInfo()->isStr("decltype"))
939 Diag(Tok, diag::warn_cxx98_compat_decltype);
943 BalancedDelimiterTracker T(*this, tok::l_paren);
944 if (T.expectAndConsume(diag::err_expected_lparen_after,
945 "decltype", tok::r_paren)) {
946 DS.SetTypeSpecError();
947 return T.getOpenLocation() == Tok.getLocation() ?
948 StartLoc : T.getOpenLocation();
951 // Check for C++1y 'decltype(auto)'.
952 if (Tok.is(tok::kw_auto)) {
953 // No need to disambiguate here: an expression can't start with 'auto',
954 // because the typename-specifier in a function-style cast operation can't
956 Diag(Tok.getLocation(),
957 getLangOpts().CPlusPlus14
958 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
959 : diag::ext_decltype_auto_type_specifier);
962 // Parse the expression
964 // C++11 [dcl.type.simple]p4:
965 // The operand of the decltype specifier is an unevaluated operand.
966 EnterExpressionEvaluationContext Unevaluated(
967 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
968 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
970 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
971 return E->hasPlaceholderType() ? ExprError() : E;
973 if (Result.isInvalid()) {
974 DS.SetTypeSpecError();
975 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
976 EndLoc = ConsumeParen();
978 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
979 // Backtrack to get the location of the last token before the semi.
980 PP.RevertCachedTokens(2);
981 ConsumeToken(); // the semi.
982 EndLoc = ConsumeAnyToken();
983 assert(Tok.is(tok::semi));
985 EndLoc = Tok.getLocation();
991 Result = Actions.ActOnDecltypeExpression(Result.get());
996 if (T.getCloseLocation().isInvalid()) {
997 DS.SetTypeSpecError();
998 // FIXME: this should return the location of the last token
999 // that was consumed (by "consumeClose()")
1000 return T.getCloseLocation();
1003 if (Result.isInvalid()) {
1004 DS.SetTypeSpecError();
1005 return T.getCloseLocation();
1008 EndLoc = T.getCloseLocation();
1010 assert(!Result.isInvalid());
1012 const char *PrevSpec = nullptr;
1014 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1015 // Check for duplicate type specifiers (e.g. "int decltype(a)").
1017 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
1018 DiagID, Result.get(), Policy)
1019 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
1021 Diag(StartLoc, DiagID) << PrevSpec;
1022 DS.SetTypeSpecError();
1027 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1028 SourceLocation StartLoc,
1029 SourceLocation EndLoc) {
1030 // make sure we have a token we can turn into an annotation token
1031 if (PP.isBacktrackEnabled())
1032 PP.RevertCachedTokens(1);
1036 Tok.setKind(tok::annot_decltype);
1037 setExprAnnotation(Tok,
1038 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1039 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1041 Tok.setAnnotationEndLoc(EndLoc);
1042 Tok.setLocation(StartLoc);
1043 PP.AnnotateCachedTokens(Tok);
1046 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1047 assert(Tok.is(tok::kw___underlying_type) &&
1048 "Not an underlying type specifier");
1050 SourceLocation StartLoc = ConsumeToken();
1051 BalancedDelimiterTracker T(*this, tok::l_paren);
1052 if (T.expectAndConsume(diag::err_expected_lparen_after,
1053 "__underlying_type", tok::r_paren)) {
1057 TypeResult Result = ParseTypeName();
1058 if (Result.isInvalid()) {
1059 SkipUntil(tok::r_paren, StopAtSemi);
1065 if (T.getCloseLocation().isInvalid())
1068 const char *PrevSpec = nullptr;
1070 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
1071 DiagID, Result.get(),
1072 Actions.getASTContext().getPrintingPolicy()))
1073 Diag(StartLoc, DiagID) << PrevSpec;
1074 DS.setTypeofParensRange(T.getRange());
1077 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1078 /// class name or decltype-specifier. Note that we only check that the result
1079 /// names a type; semantic analysis will need to verify that the type names a
1080 /// class. The result is either a type or null, depending on whether a type
1083 /// base-type-specifier: [C++11 class.derived]
1084 /// class-or-decltype
1085 /// class-or-decltype: [C++11 class.derived]
1086 /// nested-name-specifier[opt] class-name
1087 /// decltype-specifier
1088 /// class-name: [C++ class.name]
1090 /// simple-template-id
1092 /// In C++98, instead of base-type-specifier, we have:
1094 /// ::[opt] nested-name-specifier[opt] class-name
1095 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1096 SourceLocation &EndLocation) {
1097 // Ignore attempts to use typename
1098 if (Tok.is(tok::kw_typename)) {
1099 Diag(Tok, diag::err_expected_class_name_not_template)
1100 << FixItHint::CreateRemoval(Tok.getLocation());
1104 // Parse optional nested-name-specifier
1106 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
1108 BaseLoc = Tok.getLocation();
1110 // Parse decltype-specifier
1111 // tok == kw_decltype is just error recovery, it can only happen when SS
1113 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
1114 if (SS.isNotEmpty())
1115 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1116 << FixItHint::CreateRemoval(SS.getRange());
1117 // Fake up a Declarator to use with ActOnTypeName.
1118 DeclSpec DS(AttrFactory);
1120 EndLocation = ParseDecltypeSpecifier(DS);
1122 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1123 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1126 // Check whether we have a template-id that names a type.
1127 if (Tok.is(tok::annot_template_id)) {
1128 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1129 if (TemplateId->Kind == TNK_Type_template ||
1130 TemplateId->Kind == TNK_Dependent_template_name) {
1131 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1133 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1134 ParsedType Type = getTypeAnnotation(Tok);
1135 EndLocation = Tok.getAnnotationEndLoc();
1136 ConsumeAnnotationToken();
1143 // Fall through to produce an error below.
1146 if (Tok.isNot(tok::identifier)) {
1147 Diag(Tok, diag::err_expected_class_name);
1151 IdentifierInfo *Id = Tok.getIdentifierInfo();
1152 SourceLocation IdLoc = ConsumeToken();
1154 if (Tok.is(tok::less)) {
1155 // It looks the user intended to write a template-id here, but the
1156 // template-name was wrong. Try to fix that.
1157 TemplateNameKind TNK = TNK_Type_template;
1158 TemplateTy Template;
1159 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
1160 &SS, Template, TNK)) {
1161 Diag(IdLoc, diag::err_unknown_template_name)
1166 TemplateArgList TemplateArgs;
1167 SourceLocation LAngleLoc, RAngleLoc;
1168 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1173 // Form the template name
1174 UnqualifiedId TemplateName;
1175 TemplateName.setIdentifier(Id, IdLoc);
1177 // Parse the full template-id, then turn it into a type.
1178 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1181 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1182 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1184 // If we didn't end up with a typename token, there's nothing more we
1186 if (Tok.isNot(tok::annot_typename))
1189 // Retrieve the type from the annotation token, consume that token, and
1191 EndLocation = Tok.getAnnotationEndLoc();
1192 ParsedType Type = getTypeAnnotation(Tok);
1193 ConsumeAnnotationToken();
1197 // We have an identifier; check whether it is actually a type.
1198 IdentifierInfo *CorrectedII = nullptr;
1199 ParsedType Type = Actions.getTypeName(
1200 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
1201 /*IsCtorOrDtorName=*/false,
1202 /*NonTrivialTypeSourceInfo=*/true,
1203 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
1205 Diag(IdLoc, diag::err_expected_class_name);
1209 // Consume the identifier.
1210 EndLocation = IdLoc;
1212 // Fake up a Declarator to use with ActOnTypeName.
1213 DeclSpec DS(AttrFactory);
1214 DS.SetRangeStart(IdLoc);
1215 DS.SetRangeEnd(EndLocation);
1216 DS.getTypeSpecScope() = SS;
1218 const char *PrevSpec = nullptr;
1220 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1221 Actions.getASTContext().getPrintingPolicy());
1223 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1224 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1227 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1228 while (Tok.isOneOf(tok::kw___single_inheritance,
1229 tok::kw___multiple_inheritance,
1230 tok::kw___virtual_inheritance)) {
1231 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1232 SourceLocation AttrNameLoc = ConsumeToken();
1233 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1234 ParsedAttr::AS_Keyword);
1238 /// Determine whether the following tokens are valid after a type-specifier
1239 /// which could be a standalone declaration. This will conservatively return
1240 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1241 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1242 // This switch enumerates the valid "follow" set for type-specifiers.
1243 switch (Tok.getKind()) {
1245 case tok::semi: // struct foo {...} ;
1246 case tok::star: // struct foo {...} * P;
1247 case tok::amp: // struct foo {...} & R = ...
1248 case tok::ampamp: // struct foo {...} && R = ...
1249 case tok::identifier: // struct foo {...} V ;
1250 case tok::r_paren: //(struct foo {...} ) {4}
1251 case tok::annot_cxxscope: // struct foo {...} a:: b;
1252 case tok::annot_typename: // struct foo {...} a ::b;
1253 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1254 case tok::l_paren: // struct foo {...} ( x);
1255 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1256 case tok::kw_operator: // struct foo operator ++() {...}
1257 case tok::kw___declspec: // struct foo {...} __declspec(...)
1258 case tok::l_square: // void f(struct f [ 3])
1259 case tok::ellipsis: // void f(struct f ... [Ns])
1260 // FIXME: we should emit semantic diagnostic when declaration
1261 // attribute is in type attribute position.
1262 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1263 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1264 // struct foo {...} _Pragma(section(...));
1265 case tok::annot_pragma_ms_pragma:
1266 // struct foo {...} _Pragma(vtordisp(pop));
1267 case tok::annot_pragma_ms_vtordisp:
1268 // struct foo {...} _Pragma(pointers_to_members(...));
1269 case tok::annot_pragma_ms_pointers_to_members:
1272 return CouldBeBitfield; // enum E { ... } : 2;
1273 // Microsoft compatibility
1274 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1275 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1276 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1277 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1278 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1279 // We will diagnose these calling-convention specifiers on non-function
1280 // declarations later, so claim they are valid after a type specifier.
1281 return getLangOpts().MicrosoftExt;
1283 case tok::kw_const: // struct foo {...} const x;
1284 case tok::kw_volatile: // struct foo {...} volatile x;
1285 case tok::kw_restrict: // struct foo {...} restrict x;
1286 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1287 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1288 // Function specifiers
1289 // Note, no 'explicit'. An explicit function must be either a conversion
1290 // operator or a constructor. Either way, it can't have a return type.
1291 case tok::kw_inline: // struct foo inline f();
1292 case tok::kw_virtual: // struct foo virtual f();
1293 case tok::kw_friend: // struct foo friend f();
1294 // Storage-class specifiers
1295 case tok::kw_static: // struct foo {...} static x;
1296 case tok::kw_extern: // struct foo {...} extern x;
1297 case tok::kw_typedef: // struct foo {...} typedef x;
1298 case tok::kw_register: // struct foo {...} register x;
1299 case tok::kw_auto: // struct foo {...} auto x;
1300 case tok::kw_mutable: // struct foo {...} mutable x;
1301 case tok::kw_thread_local: // struct foo {...} thread_local x;
1302 case tok::kw_constexpr: // struct foo {...} constexpr x;
1303 // As shown above, type qualifiers and storage class specifiers absolutely
1304 // can occur after class specifiers according to the grammar. However,
1305 // almost no one actually writes code like this. If we see one of these,
1306 // it is much more likely that someone missed a semi colon and the
1307 // type/storage class specifier we're seeing is part of the *next*
1308 // intended declaration, as in:
1310 // struct foo { ... }
1313 // We'd really like to emit a missing semicolon error instead of emitting
1314 // an error on the 'int' saying that you can't have two type specifiers in
1315 // the same declaration of X. Because of this, we look ahead past this
1316 // token to see if it's a type specifier. If so, we know the code is
1317 // otherwise invalid, so we can produce the expected semi error.
1318 if (!isKnownToBeTypeSpecifier(NextToken()))
1321 case tok::r_brace: // struct bar { struct foo {...} }
1322 // Missing ';' at end of struct is accepted as an extension in C mode.
1323 if (!getLangOpts().CPlusPlus)
1327 // template<class T = class X>
1328 return getLangOpts().CPlusPlus;
1333 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1334 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1335 /// until we reach the start of a definition or see a token that
1336 /// cannot start a definition.
1338 /// class-specifier: [C++ class]
1339 /// class-head '{' member-specification[opt] '}'
1340 /// class-head '{' member-specification[opt] '}' attributes[opt]
1342 /// class-key identifier[opt] base-clause[opt]
1343 /// class-key nested-name-specifier identifier base-clause[opt]
1344 /// class-key nested-name-specifier[opt] simple-template-id
1345 /// base-clause[opt]
1346 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1347 /// [GNU] class-key attributes[opt] nested-name-specifier
1348 /// identifier base-clause[opt]
1349 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1350 /// simple-template-id base-clause[opt]
1356 /// elaborated-type-specifier: [C++ dcl.type.elab]
1357 /// class-key ::[opt] nested-name-specifier[opt] identifier
1358 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1359 /// simple-template-id
1361 /// Note that the C++ class-specifier and elaborated-type-specifier,
1362 /// together, subsume the C99 struct-or-union-specifier:
1364 /// struct-or-union-specifier: [C99 6.7.2.1]
1365 /// struct-or-union identifier[opt] '{' struct-contents '}'
1366 /// struct-or-union identifier
1367 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1368 /// '}' attributes[opt]
1369 /// [GNU] struct-or-union attributes[opt] identifier
1370 /// struct-or-union:
1373 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1374 SourceLocation StartLoc, DeclSpec &DS,
1375 const ParsedTemplateInfo &TemplateInfo,
1377 bool EnteringContext, DeclSpecContext DSC,
1378 ParsedAttributesWithRange &Attributes) {
1379 DeclSpec::TST TagType;
1380 if (TagTokKind == tok::kw_struct)
1381 TagType = DeclSpec::TST_struct;
1382 else if (TagTokKind == tok::kw___interface)
1383 TagType = DeclSpec::TST_interface;
1384 else if (TagTokKind == tok::kw_class)
1385 TagType = DeclSpec::TST_class;
1387 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1388 TagType = DeclSpec::TST_union;
1391 if (Tok.is(tok::code_completion)) {
1392 // Code completion for a struct, class, or union name.
1393 Actions.CodeCompleteTag(getCurScope(), TagType);
1394 return cutOffParsing();
1397 // C++03 [temp.explicit] 14.7.2/8:
1398 // The usual access checking rules do not apply to names used to specify
1399 // explicit instantiations.
1401 // As an extension we do not perform access checking on the names used to
1402 // specify explicit specializations either. This is important to allow
1403 // specializing traits classes for private types.
1405 // Note that we don't suppress if this turns out to be an elaborated
1407 bool shouldDelayDiagsInTag =
1408 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1409 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1410 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1412 ParsedAttributesWithRange attrs(AttrFactory);
1413 // If attributes exist after tag, parse them.
1414 MaybeParseGNUAttributes(attrs);
1415 MaybeParseMicrosoftDeclSpecs(attrs);
1417 // Parse inheritance specifiers.
1418 if (Tok.isOneOf(tok::kw___single_inheritance,
1419 tok::kw___multiple_inheritance,
1420 tok::kw___virtual_inheritance))
1421 ParseMicrosoftInheritanceClassAttributes(attrs);
1423 // If C++0x attributes exist here, parse them.
1424 // FIXME: Are we consistent with the ordering of parsing of different
1425 // styles of attributes?
1426 MaybeParseCXX11Attributes(attrs);
1428 // Source location used by FIXIT to insert misplaced
1430 SourceLocation AttrFixitLoc = Tok.getLocation();
1432 if (TagType == DeclSpec::TST_struct &&
1433 Tok.isNot(tok::identifier) &&
1434 !Tok.isAnnotation() &&
1435 Tok.getIdentifierInfo() &&
1436 Tok.isOneOf(tok::kw___is_abstract,
1437 tok::kw___is_aggregate,
1438 tok::kw___is_arithmetic,
1440 tok::kw___is_assignable,
1441 tok::kw___is_base_of,
1443 tok::kw___is_complete_type,
1444 tok::kw___is_compound,
1446 tok::kw___is_constructible,
1447 tok::kw___is_convertible,
1448 tok::kw___is_convertible_to,
1449 tok::kw___is_destructible,
1452 tok::kw___is_floating_point,
1454 tok::kw___is_function,
1455 tok::kw___is_fundamental,
1456 tok::kw___is_integral,
1457 tok::kw___is_interface_class,
1458 tok::kw___is_literal,
1459 tok::kw___is_lvalue_expr,
1460 tok::kw___is_lvalue_reference,
1461 tok::kw___is_member_function_pointer,
1462 tok::kw___is_member_object_pointer,
1463 tok::kw___is_member_pointer,
1464 tok::kw___is_nothrow_assignable,
1465 tok::kw___is_nothrow_constructible,
1466 tok::kw___is_nothrow_destructible,
1467 tok::kw___is_object,
1469 tok::kw___is_pointer,
1470 tok::kw___is_polymorphic,
1471 tok::kw___is_reference,
1472 tok::kw___is_rvalue_expr,
1473 tok::kw___is_rvalue_reference,
1475 tok::kw___is_scalar,
1476 tok::kw___is_sealed,
1477 tok::kw___is_signed,
1478 tok::kw___is_standard_layout,
1479 tok::kw___is_trivial,
1480 tok::kw___is_trivially_assignable,
1481 tok::kw___is_trivially_constructible,
1482 tok::kw___is_trivially_copyable,
1484 tok::kw___is_unsigned,
1486 tok::kw___is_volatile))
1487 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1488 // name of struct templates, but some are keywords in GCC >= 4.3
1489 // and Clang. Therefore, when we see the token sequence "struct
1490 // X", make X into a normal identifier rather than a keyword, to
1491 // allow libstdc++ 4.2 and libc++ to work properly.
1492 TryKeywordIdentFallback(true);
1494 struct PreserveAtomicIdentifierInfoRAII {
1495 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1496 : AtomicII(nullptr) {
1499 assert(Tok.is(tok::kw__Atomic));
1500 AtomicII = Tok.getIdentifierInfo();
1501 AtomicII->revertTokenIDToIdentifier();
1502 Tok.setKind(tok::identifier);
1504 ~PreserveAtomicIdentifierInfoRAII() {
1507 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1509 IdentifierInfo *AtomicII;
1512 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1513 // implementation for VS2013 uses _Atomic as an identifier for one of the
1514 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1515 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1516 // use '_Atomic' in its own header files.
1517 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1518 Tok.is(tok::kw__Atomic) &&
1519 TagType == DeclSpec::TST_struct;
1520 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1521 Tok, ShouldChangeAtomicToIdentifier);
1523 // Parse the (optional) nested-name-specifier.
1524 CXXScopeSpec &SS = DS.getTypeSpecScope();
1525 if (getLangOpts().CPlusPlus) {
1526 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1527 // is a base-specifier-list.
1528 ColonProtectionRAIIObject X(*this);
1531 bool HasValidSpec = true;
1532 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
1533 DS.SetTypeSpecError();
1534 HasValidSpec = false;
1537 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1538 Diag(Tok, diag::err_expected) << tok::identifier;
1539 HasValidSpec = false;
1545 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1547 // Parse the (optional) class name or simple-template-id.
1548 IdentifierInfo *Name = nullptr;
1549 SourceLocation NameLoc;
1550 TemplateIdAnnotation *TemplateId = nullptr;
1551 if (Tok.is(tok::identifier)) {
1552 Name = Tok.getIdentifierInfo();
1553 NameLoc = ConsumeToken();
1555 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1556 // The name was supposed to refer to a template, but didn't.
1557 // Eat the template argument list and try to continue parsing this as
1558 // a class (or template thereof).
1559 TemplateArgList TemplateArgs;
1560 SourceLocation LAngleLoc, RAngleLoc;
1561 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1563 // We couldn't parse the template argument list at all, so don't
1564 // try to give any location information for the list.
1565 LAngleLoc = RAngleLoc = SourceLocation();
1568 Diag(NameLoc, diag::err_explicit_spec_non_template)
1569 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1570 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1572 // Strip off the last template parameter list if it was empty, since
1573 // we've removed its template argument list.
1574 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1575 if (TemplateParams->size() > 1) {
1576 TemplateParams->pop_back();
1578 TemplateParams = nullptr;
1579 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1580 = ParsedTemplateInfo::NonTemplate;
1582 } else if (TemplateInfo.Kind
1583 == ParsedTemplateInfo::ExplicitInstantiation) {
1584 // Pretend this is just a forward declaration.
1585 TemplateParams = nullptr;
1586 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1587 = ParsedTemplateInfo::NonTemplate;
1588 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1590 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1594 } else if (Tok.is(tok::annot_template_id)) {
1595 TemplateId = takeTemplateIdAnnotation(Tok);
1596 NameLoc = ConsumeAnnotationToken();
1598 if (TemplateId->Kind != TNK_Type_template &&
1599 TemplateId->Kind != TNK_Dependent_template_name) {
1600 // The template-name in the simple-template-id refers to
1601 // something other than a class template. Give an appropriate
1602 // error message and skip to the ';'.
1603 SourceRange Range(NameLoc);
1604 if (SS.isNotEmpty())
1605 Range.setBegin(SS.getBeginLoc());
1607 // FIXME: Name may be null here.
1608 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1609 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1611 DS.SetTypeSpecError();
1612 SkipUntil(tok::semi, StopBeforeMatch);
1617 // There are four options here.
1618 // - If we are in a trailing return type, this is always just a reference,
1619 // and we must not try to parse a definition. For instance,
1620 // [] () -> struct S { };
1621 // does not define a type.
1622 // - If we have 'struct foo {...', 'struct foo :...',
1623 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1624 // - If we have 'struct foo;', then this is either a forward declaration
1625 // or a friend declaration, which have to be treated differently.
1626 // - Otherwise we have something like 'struct foo xyz', a reference.
1628 // We also detect these erroneous cases to provide better diagnostic for
1629 // C++11 attributes parsing.
1630 // - attributes follow class name:
1631 // struct foo [[]] {};
1632 // - attributes appear before or after 'final':
1633 // struct foo [[]] final [[]] {};
1635 // However, in type-specifier-seq's, things look like declarations but are
1636 // just references, e.g.
1639 // &T::operator struct s;
1640 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1641 // DeclSpecContext::DSC_alias_declaration.
1643 // If there are attributes after class name, parse them.
1644 MaybeParseCXX11Attributes(Attributes);
1646 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1647 Sema::TagUseKind TUK;
1648 if (DSC == DeclSpecContext::DSC_trailing)
1649 TUK = Sema::TUK_Reference;
1650 else if (Tok.is(tok::l_brace) ||
1651 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1652 (isCXX11FinalKeyword() &&
1653 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1654 if (DS.isFriendSpecified()) {
1655 // C++ [class.friend]p2:
1656 // A class shall not be defined in a friend declaration.
1657 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1658 << SourceRange(DS.getFriendSpecLoc());
1660 // Skip everything up to the semicolon, so that this looks like a proper
1661 // friend class (or template thereof) declaration.
1662 SkipUntil(tok::semi, StopBeforeMatch);
1663 TUK = Sema::TUK_Friend;
1665 // Okay, this is a class definition.
1666 TUK = Sema::TUK_Definition;
1668 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1669 NextToken().is(tok::kw_alignas))) {
1670 // We can't tell if this is a definition or reference
1671 // until we skipped the 'final' and C++11 attribute specifiers.
1672 TentativeParsingAction PA(*this);
1674 // Skip the 'final' keyword.
1677 // Skip C++11 attribute specifiers.
1679 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1681 if (!SkipUntil(tok::r_square, StopAtSemi))
1683 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1686 if (!SkipUntil(tok::r_paren, StopAtSemi))
1693 if (Tok.isOneOf(tok::l_brace, tok::colon))
1694 TUK = Sema::TUK_Definition;
1696 TUK = Sema::TUK_Reference;
1699 } else if (!isTypeSpecifier(DSC) &&
1700 (Tok.is(tok::semi) ||
1701 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1702 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1703 if (Tok.isNot(tok::semi)) {
1704 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1705 // A semicolon was missing after this declaration. Diagnose and recover.
1706 ExpectAndConsume(tok::semi, diag::err_expected_after,
1707 DeclSpec::getSpecifierName(TagType, PPol));
1709 Tok.setKind(tok::semi);
1712 TUK = Sema::TUK_Reference;
1714 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1715 // to caller to handle.
1716 if (TUK != Sema::TUK_Reference) {
1717 // If this is not a reference, then the only possible
1718 // valid place for C++11 attributes to appear here
1719 // is between class-key and class-name. If there are
1720 // any attributes after class-name, we try a fixit to move
1721 // them to the right place.
1722 SourceRange AttrRange = Attributes.Range;
1723 if (AttrRange.isValid()) {
1724 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1726 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1727 CharSourceRange(AttrRange, true))
1728 << FixItHint::CreateRemoval(AttrRange);
1730 // Recover by adding misplaced attributes to the attribute list
1731 // of the class so they can be applied on the class later.
1732 attrs.takeAllFrom(Attributes);
1736 // If this is an elaborated type specifier, and we delayed
1737 // diagnostics before, just merge them into the current pool.
1738 if (shouldDelayDiagsInTag) {
1739 diagsFromTag.done();
1740 if (TUK == Sema::TUK_Reference)
1741 diagsFromTag.redelay();
1744 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1745 TUK != Sema::TUK_Definition)) {
1746 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1747 // We have a declaration or reference to an anonymous class.
1748 Diag(StartLoc, diag::err_anon_type_definition)
1749 << DeclSpec::getSpecifierName(TagType, Policy);
1752 // If we are parsing a definition and stop at a base-clause, continue on
1753 // until the semicolon. Continuing from the comma will just trick us into
1754 // thinking we are seeing a variable declaration.
1755 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1756 SkipUntil(tok::semi, StopBeforeMatch);
1758 SkipUntil(tok::comma, StopAtSemi);
1762 // Create the tag portion of the class or class template.
1763 DeclResult TagOrTempResult = true; // invalid
1764 TypeResult TypeResult = true; // invalid
1767 Sema::SkipBodyInfo SkipBody;
1769 // Explicit specialization, class template partial specialization,
1770 // or explicit instantiation.
1771 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1772 TemplateId->NumArgs);
1773 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1774 TUK == Sema::TUK_Declaration) {
1775 // This is an explicit instantiation of a class template.
1776 ProhibitAttributes(attrs);
1778 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1779 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1780 TagType, StartLoc, SS, TemplateId->Template,
1781 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1782 TemplateId->RAngleLoc, attrs);
1784 // Friend template-ids are treated as references unless
1785 // they have template headers, in which case they're ill-formed
1786 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1787 // We diagnose this error in ActOnClassTemplateSpecialization.
1788 } else if (TUK == Sema::TUK_Reference ||
1789 (TUK == Sema::TUK_Friend &&
1790 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1791 ProhibitAttributes(attrs);
1792 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1794 TemplateId->TemplateKWLoc,
1795 TemplateId->Template,
1796 TemplateId->TemplateNameLoc,
1797 TemplateId->LAngleLoc,
1799 TemplateId->RAngleLoc);
1801 // This is an explicit specialization or a class template
1802 // partial specialization.
1803 TemplateParameterLists FakedParamLists;
1804 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1805 // This looks like an explicit instantiation, because we have
1808 // template class Foo<X>
1810 // but it actually has a definition. Most likely, this was
1811 // meant to be an explicit specialization, but the user forgot
1812 // the '<>' after 'template'.
1813 // It this is friend declaration however, since it cannot have a
1814 // template header, it is most likely that the user meant to
1815 // remove the 'template' keyword.
1816 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1817 "Expected a definition here");
1819 if (TUK == Sema::TUK_Friend) {
1820 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1821 TemplateParams = nullptr;
1823 SourceLocation LAngleLoc =
1824 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1825 Diag(TemplateId->TemplateNameLoc,
1826 diag::err_explicit_instantiation_with_definition)
1827 << SourceRange(TemplateInfo.TemplateLoc)
1828 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1830 // Create a fake template parameter list that contains only
1831 // "template<>", so that we treat this construct as a class
1832 // template specialization.
1833 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1834 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1835 LAngleLoc, nullptr));
1836 TemplateParams = &FakedParamLists;
1840 // Build the class template specialization.
1841 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1842 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1844 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1846 TemplateParams ? TemplateParams->size() : 0),
1849 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1850 TUK == Sema::TUK_Declaration) {
1851 // Explicit instantiation of a member of a class template
1852 // specialization, e.g.,
1854 // template struct Outer<int>::Inner;
1856 ProhibitAttributes(attrs);
1858 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1859 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1860 TagType, StartLoc, SS, Name, NameLoc, attrs);
1861 } else if (TUK == Sema::TUK_Friend &&
1862 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1863 ProhibitAttributes(attrs);
1865 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1866 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1868 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1869 TemplateParams ? TemplateParams->size() : 0));
1871 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1872 ProhibitAttributes(attrs);
1874 if (TUK == Sema::TUK_Definition &&
1875 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1876 // If the declarator-id is not a template-id, issue a diagnostic and
1877 // recover by ignoring the 'template' keyword.
1878 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1879 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1880 TemplateParams = nullptr;
1883 bool IsDependent = false;
1885 // Don't pass down template parameter lists if this is just a tag
1886 // reference. For example, we don't need the template parameters here:
1887 // template <class T> class A *makeA(T t);
1888 MultiTemplateParamsArg TParams;
1889 if (TUK != Sema::TUK_Reference && TemplateParams)
1891 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1893 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
1895 // Declaration or definition of a class type
1896 TagOrTempResult = Actions.ActOnTag(
1897 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1898 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1899 SourceLocation(), false, clang::TypeResult(),
1900 DSC == DeclSpecContext::DSC_type_specifier,
1901 DSC == DeclSpecContext::DSC_template_param ||
1902 DSC == DeclSpecContext::DSC_template_type_arg,
1905 // If ActOnTag said the type was dependent, try again with the
1906 // less common call.
1908 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1909 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1910 SS, Name, StartLoc, NameLoc);
1914 // If there is a body, parse it and inform the actions module.
1915 if (TUK == Sema::TUK_Definition) {
1916 assert(Tok.is(tok::l_brace) ||
1917 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1918 isCXX11FinalKeyword());
1919 if (SkipBody.ShouldSkip)
1920 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1921 TagOrTempResult.get());
1922 else if (getLangOpts().CPlusPlus)
1923 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1924 TagOrTempResult.get());
1927 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1928 // Parse the definition body.
1929 ParseStructUnionBody(StartLoc, TagType, D);
1930 if (SkipBody.CheckSameAsPrevious &&
1931 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1933 DS.SetTypeSpecError();
1939 if (!TagOrTempResult.isInvalid())
1940 // Delayed processing of attributes.
1941 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
1943 const char *PrevSpec = nullptr;
1946 if (!TypeResult.isInvalid()) {
1947 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1948 NameLoc.isValid() ? NameLoc : StartLoc,
1949 PrevSpec, DiagID, TypeResult.get(), Policy);
1950 } else if (!TagOrTempResult.isInvalid()) {
1951 Result = DS.SetTypeSpecType(TagType, StartLoc,
1952 NameLoc.isValid() ? NameLoc : StartLoc,
1953 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1956 DS.SetTypeSpecError();
1961 Diag(StartLoc, DiagID) << PrevSpec;
1963 // At this point, we've successfully parsed a class-specifier in 'definition'
1964 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1965 // going to look at what comes after it to improve error recovery. If an
1966 // impossible token occurs next, we assume that the programmer forgot a ; at
1967 // the end of the declaration and recover that way.
1969 // Also enforce C++ [temp]p3:
1970 // In a template-declaration which defines a class, no declarator
1973 // After a type-specifier, we don't expect a semicolon. This only happens in
1974 // C, since definitions are not permitted in this context in C++.
1975 if (TUK == Sema::TUK_Definition &&
1976 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1977 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1978 if (Tok.isNot(tok::semi)) {
1979 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1980 ExpectAndConsume(tok::semi, diag::err_expected_after,
1981 DeclSpec::getSpecifierName(TagType, PPol));
1982 // Push this token back into the preprocessor and change our current token
1983 // to ';' so that the rest of the code recovers as though there were an
1984 // ';' after the definition.
1986 Tok.setKind(tok::semi);
1991 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1993 /// base-clause : [C++ class.derived]
1994 /// ':' base-specifier-list
1995 /// base-specifier-list:
1996 /// base-specifier '...'[opt]
1997 /// base-specifier-list ',' base-specifier '...'[opt]
1998 void Parser::ParseBaseClause(Decl *ClassDecl) {
1999 assert(Tok.is(tok::colon) && "Not a base clause");
2002 // Build up an array of parsed base specifiers.
2003 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
2006 // Parse a base-specifier.
2007 BaseResult Result = ParseBaseSpecifier(ClassDecl);
2008 if (Result.isInvalid()) {
2009 // Skip the rest of this base specifier, up until the comma or
2011 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2013 // Add this to our array of base specifiers.
2014 BaseInfo.push_back(Result.get());
2017 // If the next token is a comma, consume it and keep reading
2019 if (!TryConsumeToken(tok::comma))
2023 // Attach the base specifiers
2024 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2027 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2028 /// one entry in the base class list of a class specifier, for example:
2029 /// class foo : public bar, virtual private baz {
2030 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2032 /// base-specifier: [C++ class.derived]
2033 /// attribute-specifier-seq[opt] base-type-specifier
2034 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2035 /// base-type-specifier
2036 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2037 /// base-type-specifier
2038 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2039 bool IsVirtual = false;
2040 SourceLocation StartLoc = Tok.getLocation();
2042 ParsedAttributesWithRange Attributes(AttrFactory);
2043 MaybeParseCXX11Attributes(Attributes);
2045 // Parse the 'virtual' keyword.
2046 if (TryConsumeToken(tok::kw_virtual))
2049 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2051 // Parse an (optional) access specifier.
2052 AccessSpecifier Access = getAccessSpecifierIfPresent();
2053 if (Access != AS_none)
2056 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2058 // Parse the 'virtual' keyword (again!), in case it came after the
2059 // access specifier.
2060 if (Tok.is(tok::kw_virtual)) {
2061 SourceLocation VirtualLoc = ConsumeToken();
2063 // Complain about duplicate 'virtual'
2064 Diag(VirtualLoc, diag::err_dup_virtual)
2065 << FixItHint::CreateRemoval(VirtualLoc);
2071 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2073 // Parse the class-name.
2075 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2076 // implementation for VS2013 uses _Atomic as an identifier for one of the
2077 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2078 // parsing the class-name for a base specifier.
2079 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2080 NextToken().is(tok::less))
2081 Tok.setKind(tok::identifier);
2083 SourceLocation EndLocation;
2084 SourceLocation BaseLoc;
2085 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2086 if (BaseType.isInvalid())
2089 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2090 // actually part of the base-specifier-list grammar productions, but we
2091 // parse it here for convenience.
2092 SourceLocation EllipsisLoc;
2093 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2095 // Find the complete source range for the base-specifier.
2096 SourceRange Range(StartLoc, EndLocation);
2098 // Notify semantic analysis that we have parsed a complete
2100 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2101 Access, BaseType.get(), BaseLoc,
2105 /// getAccessSpecifierIfPresent - Determine whether the next token is
2106 /// a C++ access-specifier.
2108 /// access-specifier: [C++ class.derived]
2112 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2113 switch (Tok.getKind()) {
2114 default: return AS_none;
2115 case tok::kw_private: return AS_private;
2116 case tok::kw_protected: return AS_protected;
2117 case tok::kw_public: return AS_public;
2121 /// If the given declarator has any parts for which parsing has to be
2122 /// delayed, e.g., default arguments or an exception-specification, create a
2123 /// late-parsed method declaration record to handle the parsing at the end of
2124 /// the class definition.
2125 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2127 DeclaratorChunk::FunctionTypeInfo &FTI
2128 = DeclaratorInfo.getFunctionTypeInfo();
2129 // If there was a late-parsed exception-specification, we'll need a
2131 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2133 if (!NeedLateParse) {
2134 // Look ahead to see if there are any default args
2135 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2136 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2137 if (Param->hasUnparsedDefaultArg()) {
2138 NeedLateParse = true;
2144 if (NeedLateParse) {
2145 // Push this method onto the stack of late-parsed method
2147 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2148 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2149 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2151 // Stash the exception-specification tokens in the late-pased method.
2152 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2153 FTI.ExceptionSpecTokens = nullptr;
2155 // Push tokens for each parameter. Those that do not have
2156 // defaults will be NULL.
2157 LateMethod->DefaultArgs.reserve(FTI.NumParams);
2158 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2159 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2160 FTI.Params[ParamIdx].Param,
2161 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2165 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2172 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2173 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2174 return VirtSpecifiers::VS_None;
2176 IdentifierInfo *II = Tok.getIdentifierInfo();
2178 // Initialize the contextual keywords.
2180 Ident_final = &PP.getIdentifierTable().get("final");
2181 if (getLangOpts().GNUKeywords)
2182 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2183 if (getLangOpts().MicrosoftExt)
2184 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2185 Ident_override = &PP.getIdentifierTable().get("override");
2188 if (II == Ident_override)
2189 return VirtSpecifiers::VS_Override;
2191 if (II == Ident_sealed)
2192 return VirtSpecifiers::VS_Sealed;
2194 if (II == Ident_final)
2195 return VirtSpecifiers::VS_Final;
2197 if (II == Ident_GNU_final)
2198 return VirtSpecifiers::VS_GNU_Final;
2200 return VirtSpecifiers::VS_None;
2203 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2205 /// virt-specifier-seq:
2207 /// virt-specifier-seq virt-specifier
2208 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2210 SourceLocation FriendLoc) {
2212 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2213 if (Specifier == VirtSpecifiers::VS_None)
2216 if (FriendLoc.isValid()) {
2217 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2218 << VirtSpecifiers::getSpecifierName(Specifier)
2219 << FixItHint::CreateRemoval(Tok.getLocation())
2220 << SourceRange(FriendLoc, FriendLoc);
2225 // C++ [class.mem]p8:
2226 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2227 const char *PrevSpec = nullptr;
2228 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2229 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2231 << FixItHint::CreateRemoval(Tok.getLocation());
2233 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2234 Specifier == VirtSpecifiers::VS_Sealed)) {
2235 Diag(Tok.getLocation(), diag::err_override_control_interface)
2236 << VirtSpecifiers::getSpecifierName(Specifier);
2237 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2238 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2239 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2240 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2242 Diag(Tok.getLocation(),
2243 getLangOpts().CPlusPlus11
2244 ? diag::warn_cxx98_compat_override_control_keyword
2245 : diag::ext_override_control_keyword)
2246 << VirtSpecifiers::getSpecifierName(Specifier);
2252 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2253 /// 'final' or Microsoft 'sealed' contextual keyword.
2254 bool Parser::isCXX11FinalKeyword() const {
2255 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2256 return Specifier == VirtSpecifiers::VS_Final ||
2257 Specifier == VirtSpecifiers::VS_GNU_Final ||
2258 Specifier == VirtSpecifiers::VS_Sealed;
2261 /// Parse a C++ member-declarator up to, but not including, the optional
2262 /// brace-or-equal-initializer or pure-specifier.
2263 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2264 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2265 LateParsedAttrList &LateParsedAttrs) {
2266 // member-declarator:
2267 // declarator pure-specifier[opt]
2268 // declarator brace-or-equal-initializer[opt]
2269 // identifier[opt] ':' constant-expression
2270 if (Tok.isNot(tok::colon))
2271 ParseDeclarator(DeclaratorInfo);
2273 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2275 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2276 assert(DeclaratorInfo.isPastIdentifier() &&
2277 "don't know where identifier would go yet?");
2278 BitfieldSize = ParseConstantExpression();
2279 if (BitfieldSize.isInvalid())
2280 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2282 ParseOptionalCXX11VirtSpecifierSeq(
2283 VS, getCurrentClass().IsInterface,
2284 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2286 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2289 // If a simple-asm-expr is present, parse it.
2290 if (Tok.is(tok::kw_asm)) {
2292 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2293 if (AsmLabel.isInvalid())
2294 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2296 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2297 DeclaratorInfo.SetRangeEnd(Loc);
2300 // If attributes exist after the declarator, but before an '{', parse them.
2301 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2303 // For compatibility with code written to older Clang, also accept a
2304 // virt-specifier *after* the GNU attributes.
2305 if (BitfieldSize.isUnset() && VS.isUnset()) {
2306 ParseOptionalCXX11VirtSpecifierSeq(
2307 VS, getCurrentClass().IsInterface,
2308 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2309 if (!VS.isUnset()) {
2310 // If we saw any GNU-style attributes that are known to GCC followed by a
2311 // virt-specifier, issue a GCC-compat warning.
2312 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
2313 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2314 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2316 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2320 // If this has neither a name nor a bit width, something has gone seriously
2321 // wrong. Skip until the semi-colon or }.
2322 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2323 // If so, skip until the semi-colon or a }.
2324 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2330 /// Look for declaration specifiers possibly occurring after C++11
2331 /// virt-specifier-seq and diagnose them.
2332 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2334 VirtSpecifiers &VS) {
2335 DeclSpec DS(AttrFactory);
2337 // GNU-style and C++11 attributes are not allowed here, but they will be
2338 // handled by the caller. Diagnose everything else.
2339 ParseTypeQualifierListOpt(
2340 DS, AR_NoAttributesParsed, false,
2341 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2342 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2344 D.ExtendWithDeclSpec(DS);
2346 if (D.isFunctionDeclarator()) {
2347 auto &Function = D.getFunctionTypeInfo();
2348 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2349 auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
2350 SourceLocation SpecLoc) {
2351 FixItHint Insertion;
2352 auto &MQ = Function.getOrCreateMethodQualifiers();
2353 if (!(MQ.getTypeQualifiers() & TypeQual)) {
2354 std::string Name(FixItName.data());
2356 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2357 MQ.SetTypeQual(TypeQual, SpecLoc);
2359 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2361 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2362 << FixItHint::CreateRemoval(SpecLoc) << Insertion;
2364 DS.forEachQualifier(DeclSpecCheck);
2367 // Parse ref-qualifiers.
2368 bool RefQualifierIsLValueRef = true;
2369 SourceLocation RefQualifierLoc;
2370 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2371 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2372 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2373 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2374 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2376 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2377 << (RefQualifierIsLValueRef ? "&" : "&&")
2378 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2379 << FixItHint::CreateRemoval(RefQualifierLoc)
2381 D.SetRangeEnd(RefQualifierLoc);
2386 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2388 /// member-declaration:
2389 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2390 /// function-definition ';'[opt]
2391 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2392 /// using-declaration [TODO]
2393 /// [C++0x] static_assert-declaration
2394 /// template-declaration
2395 /// [GNU] '__extension__' member-declaration
2397 /// member-declarator-list:
2398 /// member-declarator
2399 /// member-declarator-list ',' member-declarator
2401 /// member-declarator:
2402 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2403 /// declarator constant-initializer[opt]
2404 /// [C++11] declarator brace-or-equal-initializer[opt]
2405 /// identifier[opt] ':' constant-expression
2407 /// virt-specifier-seq:
2409 /// virt-specifier-seq virt-specifier
2419 /// constant-initializer:
2420 /// '=' constant-expression
2422 Parser::DeclGroupPtrTy
2423 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2424 ParsedAttributes &AccessAttrs,
2425 const ParsedTemplateInfo &TemplateInfo,
2426 ParsingDeclRAIIObject *TemplateDiags) {
2427 if (Tok.is(tok::at)) {
2428 if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
2429 Diag(Tok, diag::err_at_defs_cxx);
2431 Diag(Tok, diag::err_at_in_class);
2434 SkipUntil(tok::r_brace, StopAtSemi);
2438 // Turn on colon protection early, while parsing declspec, although there is
2439 // nothing to protect there. It prevents from false errors if error recovery
2440 // incorrectly determines where the declspec ends, as in the example:
2441 // struct A { enum class B { C }; };
2443 // struct D { A::B : C; };
2444 ColonProtectionRAIIObject X(*this);
2446 // Access declarations.
2447 bool MalformedTypeSpec = false;
2448 if (!TemplateInfo.Kind &&
2449 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2450 if (TryAnnotateCXXScopeToken())
2451 MalformedTypeSpec = true;
2454 if (Tok.isNot(tok::annot_cxxscope))
2455 isAccessDecl = false;
2456 else if (NextToken().is(tok::identifier))
2457 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2459 isAccessDecl = NextToken().is(tok::kw_operator);
2462 // Collect the scope specifier token we annotated earlier.
2464 ParseOptionalCXXScopeSpecifier(SS, nullptr,
2465 /*EnteringContext=*/false);
2467 if (SS.isInvalid()) {
2468 SkipUntil(tok::semi);
2472 // Try to parse an unqualified-id.
2473 SourceLocation TemplateKWLoc;
2475 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2476 &TemplateKWLoc, Name)) {
2477 SkipUntil(tok::semi);
2481 // TODO: recover from mistakenly-qualified operator declarations.
2482 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2483 "access declaration")) {
2484 SkipUntil(tok::semi);
2488 // FIXME: We should do something with the 'template' keyword here.
2489 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2490 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2491 /*TypenameLoc*/ SourceLocation(), SS, Name,
2492 /*EllipsisLoc*/ SourceLocation(),
2493 /*AttrList*/ ParsedAttributesView())));
2497 // static_assert-declaration. A templated static_assert declaration is
2498 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2499 if (!TemplateInfo.Kind &&
2500 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2501 SourceLocation DeclEnd;
2502 return DeclGroupPtrTy::make(
2503 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2506 if (Tok.is(tok::kw_template)) {
2507 assert(!TemplateInfo.TemplateParams &&
2508 "Nested template improperly parsed?");
2509 ObjCDeclContextSwitch ObjCDC(*this);
2510 SourceLocation DeclEnd;
2511 return DeclGroupPtrTy::make(
2512 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2513 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
2516 // Handle: member-declaration ::= '__extension__' member-declaration
2517 if (Tok.is(tok::kw___extension__)) {
2518 // __extension__ silences extension warnings in the subexpression.
2519 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2521 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2522 TemplateInfo, TemplateDiags);
2525 ParsedAttributesWithRange attrs(AttrFactory);
2526 ParsedAttributesViewWithRange FnAttrs;
2527 // Optional C++11 attribute-specifier
2528 MaybeParseCXX11Attributes(attrs);
2529 // We need to keep these attributes for future diagnostic
2530 // before they are taken over by declaration specifier.
2531 FnAttrs.addAll(attrs.begin(), attrs.end());
2532 FnAttrs.Range = attrs.Range;
2534 MaybeParseMicrosoftAttributes(attrs);
2536 if (Tok.is(tok::kw_using)) {
2537 ProhibitAttributes(attrs);
2540 SourceLocation UsingLoc = ConsumeToken();
2542 if (Tok.is(tok::kw_namespace)) {
2543 Diag(UsingLoc, diag::err_using_namespace_in_class);
2544 SkipUntil(tok::semi, StopBeforeMatch);
2547 SourceLocation DeclEnd;
2548 // Otherwise, it must be a using-declaration or an alias-declaration.
2549 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
2550 UsingLoc, DeclEnd, AS);
2553 // Hold late-parsed attributes so we can attach a Decl to them later.
2554 LateParsedAttrList CommonLateParsedAttrs;
2556 // decl-specifier-seq:
2557 // Parse the common declaration-specifiers piece.
2558 ParsingDeclSpec DS(*this, TemplateDiags);
2559 DS.takeAttributesFrom(attrs);
2560 if (MalformedTypeSpec)
2561 DS.SetTypeSpecError();
2563 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2564 &CommonLateParsedAttrs);
2566 // Turn off colon protection that was set for declspec.
2569 // If we had a free-standing type definition with a missing semicolon, we
2570 // may get this far before the problem becomes obvious.
2571 if (DS.hasTagDefinition() &&
2572 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2573 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
2574 &CommonLateParsedAttrs))
2577 MultiTemplateParamsArg TemplateParams(
2578 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2580 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2582 if (TryConsumeToken(tok::semi)) {
2583 if (DS.isFriendSpecified())
2584 ProhibitAttributes(FnAttrs);
2586 RecordDecl *AnonRecord = nullptr;
2587 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2588 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2589 DS.complete(TheDecl);
2591 Decl* decls[] = {AnonRecord, TheDecl};
2592 return Actions.BuildDeclaratorGroup(decls);
2594 return Actions.ConvertDeclToDeclGroup(TheDecl);
2597 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
2600 // Hold late-parsed attributes so we can attach a Decl to them later.
2601 LateParsedAttrList LateParsedAttrs;
2603 SourceLocation EqualLoc;
2604 SourceLocation PureSpecLoc;
2606 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2607 if (Tok.isNot(tok::equal))
2610 auto &Zero = NextToken();
2611 SmallString<8> Buffer;
2612 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2613 PP.getSpelling(Zero, Buffer) != "0")
2616 auto &After = GetLookAheadToken(2);
2617 if (!After.isOneOf(tok::semi, tok::comma) &&
2618 !(AllowDefinition &&
2619 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2622 EqualLoc = ConsumeToken();
2623 PureSpecLoc = ConsumeToken();
2627 SmallVector<Decl *, 8> DeclsInGroup;
2628 ExprResult BitfieldSize;
2629 bool ExpectSemi = true;
2631 // Parse the first declarator.
2632 if (ParseCXXMemberDeclaratorBeforeInitializer(
2633 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2634 TryConsumeToken(tok::semi);
2638 // Check for a member function definition.
2639 if (BitfieldSize.isUnset()) {
2640 // MSVC permits pure specifier on inline functions defined at class scope.
2641 // Hence check for =0 before checking for function definition.
2642 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2643 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2645 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2646 // function-definition:
2648 // In C++11, a non-function declarator followed by an open brace is a
2649 // braced-init-list for an in-class member initialization, not an
2650 // erroneous function definition.
2651 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2652 DefinitionKind = FDK_Definition;
2653 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2654 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2655 DefinitionKind = FDK_Definition;
2656 } else if (Tok.is(tok::equal)) {
2657 const Token &KW = NextToken();
2658 if (KW.is(tok::kw_default))
2659 DefinitionKind = FDK_Defaulted;
2660 else if (KW.is(tok::kw_delete))
2661 DefinitionKind = FDK_Deleted;
2664 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2666 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2667 // to a friend declaration, that declaration shall be a definition.
2668 if (DeclaratorInfo.isFunctionDeclarator() &&
2669 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2670 // Diagnose attributes that appear before decl specifier:
2671 // [[]] friend int foo();
2672 ProhibitAttributes(FnAttrs);
2675 if (DefinitionKind != FDK_Declaration) {
2676 if (!DeclaratorInfo.isFunctionDeclarator()) {
2677 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2679 SkipUntil(tok::r_brace);
2681 // Consume the optional ';'
2682 TryConsumeToken(tok::semi);
2687 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2688 Diag(DeclaratorInfo.getIdentifierLoc(),
2689 diag::err_function_declared_typedef);
2691 // Recover by treating the 'typedef' as spurious.
2692 DS.ClearStorageClassSpecs();
2696 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2700 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2701 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2703 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2704 LateParsedAttrs[i]->addDecl(FunDecl);
2707 LateParsedAttrs.clear();
2709 // Consume the ';' - it's optional unless we have a delete or default
2710 if (Tok.is(tok::semi))
2711 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2713 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2717 // member-declarator-list:
2718 // member-declarator
2719 // member-declarator-list ',' member-declarator
2722 InClassInitStyle HasInClassInit = ICIS_NoInit;
2723 bool HasStaticInitializer = false;
2724 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2725 if (DeclaratorInfo.isDeclarationOfFunction()) {
2726 // It's a pure-specifier.
2727 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2728 // Parse it as an expression so that Sema can diagnose it.
2729 HasStaticInitializer = true;
2730 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2731 DeclSpec::SCS_static &&
2732 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2733 DeclSpec::SCS_typedef &&
2734 !DS.isFriendSpecified()) {
2735 // It's a default member initializer.
2736 if (BitfieldSize.get())
2737 Diag(Tok, getLangOpts().CPlusPlus2a
2738 ? diag::warn_cxx17_compat_bitfield_member_init
2739 : diag::ext_bitfield_member_init);
2740 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2742 HasStaticInitializer = true;
2746 // NOTE: If Sema is the Action module and declarator is an instance field,
2747 // this call will *not* return the created decl; It will return null.
2748 // See Sema::ActOnCXXMemberDeclarator for details.
2750 NamedDecl *ThisDecl = nullptr;
2751 if (DS.isFriendSpecified()) {
2752 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2753 // to a friend declaration, that declaration shall be a definition.
2755 // Diagnose attributes that appear in a friend member function declarator:
2756 // friend int foo [[]] ();
2757 SmallVector<SourceRange, 4> Ranges;
2758 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2759 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2760 E = Ranges.end(); I != E; ++I)
2761 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2763 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2766 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2770 VS, HasInClassInit);
2772 if (VarTemplateDecl *VT =
2773 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2774 // Re-direct this decl to refer to the templated decl so that we can
2776 ThisDecl = VT->getTemplatedDecl();
2779 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2782 // Error recovery might have converted a non-static member into a static
2784 if (HasInClassInit != ICIS_NoInit &&
2785 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2786 DeclSpec::SCS_static) {
2787 HasInClassInit = ICIS_NoInit;
2788 HasStaticInitializer = true;
2791 if (ThisDecl && PureSpecLoc.isValid())
2792 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2794 // Handle the initializer.
2795 if (HasInClassInit != ICIS_NoInit) {
2796 // The initializer was deferred; parse it and cache the tokens.
2797 Diag(Tok, getLangOpts().CPlusPlus11
2798 ? diag::warn_cxx98_compat_nonstatic_member_init
2799 : diag::ext_nonstatic_member_init);
2801 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2802 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2803 // declarator is followed by an initializer.
2805 // A brace-or-equal-initializer for a member-declarator is not an
2806 // initializer in the grammar, so this is ill-formed.
2807 Diag(Tok, diag::err_incomplete_array_member_init);
2808 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2810 // Avoid later warnings about a class member of incomplete type.
2812 ThisDecl->setInvalidDecl();
2814 ParseCXXNonStaticMemberInitializer(ThisDecl);
2815 } else if (HasStaticInitializer) {
2816 // Normal initializer.
2817 ExprResult Init = ParseCXXMemberInitializer(
2818 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2820 if (Init.isInvalid())
2821 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2823 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
2824 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2826 Actions.ActOnUninitializedDecl(ThisDecl);
2829 if (!ThisDecl->isInvalidDecl()) {
2830 // Set the Decl for any late parsed attributes
2831 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2832 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2834 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2835 LateParsedAttrs[i]->addDecl(ThisDecl);
2837 Actions.FinalizeDeclaration(ThisDecl);
2838 DeclsInGroup.push_back(ThisDecl);
2840 if (DeclaratorInfo.isFunctionDeclarator() &&
2841 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2842 DeclSpec::SCS_typedef)
2843 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2845 LateParsedAttrs.clear();
2847 DeclaratorInfo.complete(ThisDecl);
2849 // If we don't have a comma, it is either the end of the list (a ';')
2850 // or an error, bail out.
2851 SourceLocation CommaLoc;
2852 if (!TryConsumeToken(tok::comma, CommaLoc))
2855 if (Tok.isAtStartOfLine() &&
2856 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
2857 // This comma was followed by a line-break and something which can't be
2858 // the start of a declarator. The comma was probably a typo for a
2860 Diag(CommaLoc, diag::err_expected_semi_declaration)
2861 << FixItHint::CreateReplacement(CommaLoc, ";");
2866 // Parse the next declarator.
2867 DeclaratorInfo.clear();
2869 BitfieldSize = ExprResult(/*Invalid=*/false);
2870 EqualLoc = PureSpecLoc = SourceLocation();
2871 DeclaratorInfo.setCommaLoc(CommaLoc);
2873 // GNU attributes are allowed before the second and subsequent declarator.
2874 MaybeParseGNUAttributes(DeclaratorInfo);
2876 if (ParseCXXMemberDeclaratorBeforeInitializer(
2877 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2882 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2883 // Skip to end of block or statement.
2884 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2885 // If we stopped at a ';', eat it.
2886 TryConsumeToken(tok::semi);
2890 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2893 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2894 /// Also detect and reject any attempted defaulted/deleted function definition.
2895 /// The location of the '=', if any, will be placed in EqualLoc.
2897 /// This does not check for a pure-specifier; that's handled elsewhere.
2899 /// brace-or-equal-initializer:
2900 /// '=' initializer-expression
2901 /// braced-init-list
2903 /// initializer-clause:
2904 /// assignment-expression
2905 /// braced-init-list
2907 /// defaulted/deleted function-definition:
2911 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2912 /// be a constant-expression.
2913 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2914 SourceLocation &EqualLoc) {
2915 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2916 && "Data member initializer not starting with '=' or '{'");
2918 EnterExpressionEvaluationContext Context(
2919 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
2920 if (TryConsumeToken(tok::equal, EqualLoc)) {
2921 if (Tok.is(tok::kw_delete)) {
2922 // In principle, an initializer of '= delete p;' is legal, but it will
2923 // never type-check. It's better to diagnose it as an ill-formed expression
2924 // than as an ill-formed deleted non-function member.
2925 // An initializer of '= delete p, foo' will never be parsed, because
2926 // a top-level comma always ends the initializer expression.
2927 const Token &Next = NextToken();
2928 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2930 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2933 Diag(ConsumeToken(), diag::err_deleted_non_function);
2936 } else if (Tok.is(tok::kw_default)) {
2938 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2941 Diag(ConsumeToken(), diag::err_default_special_members);
2945 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2946 Diag(Tok, diag::err_ms_property_initializer) << PD;
2949 return ParseInitializer();
2952 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2953 SourceLocation AttrFixitLoc,
2954 unsigned TagType, Decl *TagDecl) {
2955 // Skip the optional 'final' keyword.
2956 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2957 assert(isCXX11FinalKeyword() && "not a class definition");
2960 // Diagnose any C++11 attributes after 'final' keyword.
2961 // We deliberately discard these attributes.
2962 ParsedAttributesWithRange Attrs(AttrFactory);
2963 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2965 // This can only happen if we had malformed misplaced attributes;
2966 // we only get called if there is a colon or left-brace after the
2968 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2972 // Skip the base clauses. This requires actually parsing them, because
2973 // otherwise we can't be sure where they end (a left brace may appear
2974 // within a template argument).
2975 if (Tok.is(tok::colon)) {
2976 // Enter the scope of the class so that we can correctly parse its bases.
2977 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2978 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2979 TagType == DeclSpec::TST_interface);
2981 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2983 // Parse the bases but don't attach them to the class.
2984 ParseBaseClause(nullptr);
2986 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2988 if (!Tok.is(tok::l_brace)) {
2989 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2990 diag::err_expected_lbrace_after_base_specifiers);
2996 assert(Tok.is(tok::l_brace));
2997 BalancedDelimiterTracker T(*this, tok::l_brace);
3001 // Parse and discard any trailing attributes.
3002 ParsedAttributes Attrs(AttrFactory);
3003 if (Tok.is(tok::kw___attribute))
3004 MaybeParseGNUAttributes(Attrs);
3007 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3008 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3009 DeclSpec::TST TagType, Decl *TagDecl) {
3010 ParenBraceBracketBalancer BalancerRAIIObj(*this);
3012 switch (Tok.getKind()) {
3013 case tok::kw___if_exists:
3014 case tok::kw___if_not_exists:
3015 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
3019 // Check for extraneous top-level semicolon.
3020 ConsumeExtraSemi(InsideStruct, TagType);
3023 // Handle pragmas that can appear as member declarations.
3024 case tok::annot_pragma_vis:
3025 HandlePragmaVisibility();
3027 case tok::annot_pragma_pack:
3030 case tok::annot_pragma_align:
3031 HandlePragmaAlign();
3033 case tok::annot_pragma_ms_pointers_to_members:
3034 HandlePragmaMSPointersToMembers();
3036 case tok::annot_pragma_ms_pragma:
3037 HandlePragmaMSPragma();
3039 case tok::annot_pragma_ms_vtordisp:
3040 HandlePragmaMSVtorDisp();
3042 case tok::annot_pragma_dump:
3046 case tok::kw_namespace:
3047 // If we see a namespace here, a close brace was missing somewhere.
3048 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3051 case tok::kw_public:
3052 case tok::kw_protected:
3053 case tok::kw_private: {
3054 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3055 assert(NewAS != AS_none);
3056 // Current token is a C++ access specifier.
3058 SourceLocation ASLoc = Tok.getLocation();
3059 unsigned TokLength = Tok.getLength();
3061 AccessAttrs.clear();
3062 MaybeParseGNUAttributes(AccessAttrs);
3064 SourceLocation EndLoc;
3065 if (TryConsumeToken(tok::colon, EndLoc)) {
3066 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3067 Diag(EndLoc, diag::err_expected)
3068 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3070 EndLoc = ASLoc.getLocWithOffset(TokLength);
3071 Diag(EndLoc, diag::err_expected)
3072 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3075 // The Microsoft extension __interface does not permit non-public
3076 // access specifiers.
3077 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3078 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3081 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
3082 // found another attribute than only annotations
3083 AccessAttrs.clear();
3089 case tok::annot_pragma_openmp:
3090 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3094 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3098 /// ParseCXXMemberSpecification - Parse the class definition.
3100 /// member-specification:
3101 /// member-declaration member-specification[opt]
3102 /// access-specifier ':' member-specification[opt]
3104 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3105 SourceLocation AttrFixitLoc,
3106 ParsedAttributesWithRange &Attrs,
3107 unsigned TagType, Decl *TagDecl) {
3108 assert((TagType == DeclSpec::TST_struct ||
3109 TagType == DeclSpec::TST_interface ||
3110 TagType == DeclSpec::TST_union ||
3111 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3113 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
3114 "parsing struct/union/class body");
3116 // Determine whether this is a non-nested class. Note that local
3117 // classes are *not* considered to be nested classes.
3118 bool NonNestedClass = true;
3119 if (!ClassStack.empty()) {
3120 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
3121 if (S->isClassScope()) {
3122 // We're inside a class scope, so this is a nested class.
3123 NonNestedClass = false;
3125 // The Microsoft extension __interface does not permit nested classes.
3126 if (getCurrentClass().IsInterface) {
3127 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3129 << (isa<NamedDecl>(TagDecl)
3130 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3136 if ((S->getFlags() & Scope::FnScope))
3137 // If we're in a function or function template then this is a local
3138 // class rather than a nested class.
3143 // Enter a scope for the class.
3144 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3146 // Note that we are parsing a new (potentially-nested) class definition.
3147 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3148 TagType == DeclSpec::TST_interface);
3151 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3153 SourceLocation FinalLoc;
3154 bool IsFinalSpelledSealed = false;
3156 // Parse the optional 'final' keyword.
3157 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3158 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3159 assert((Specifier == VirtSpecifiers::VS_Final ||
3160 Specifier == VirtSpecifiers::VS_GNU_Final ||
3161 Specifier == VirtSpecifiers::VS_Sealed) &&
3162 "not a class definition");
3163 FinalLoc = ConsumeToken();
3164 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
3166 if (TagType == DeclSpec::TST_interface)
3167 Diag(FinalLoc, diag::err_override_control_interface)
3168 << VirtSpecifiers::getSpecifierName(Specifier);
3169 else if (Specifier == VirtSpecifiers::VS_Final)
3170 Diag(FinalLoc, getLangOpts().CPlusPlus11
3171 ? diag::warn_cxx98_compat_override_control_keyword
3172 : diag::ext_override_control_keyword)
3173 << VirtSpecifiers::getSpecifierName(Specifier);
3174 else if (Specifier == VirtSpecifiers::VS_Sealed)
3175 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3176 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3177 Diag(FinalLoc, diag::ext_warn_gnu_final);
3179 // Parse any C++11 attributes after 'final' keyword.
3180 // These attributes are not allowed to appear here,
3181 // and the only possible place for them to appertain
3182 // to the class would be between class-key and class-name.
3183 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3185 // ParseClassSpecifier() does only a superficial check for attributes before
3186 // deciding to call this method. For example, for
3187 // `class C final alignas ([l) {` it will decide that this looks like a
3188 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3189 // attribute parsing code will try to parse the '[' as a constexpr lambda
3190 // and consume enough tokens that the alignas parsing code will eat the
3191 // opening '{'. So bail out if the next token isn't one we expect.
3192 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3194 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3199 if (Tok.is(tok::colon)) {
3200 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3201 Scope::ClassInheritanceScope);
3203 ParseBaseClause(TagDecl);
3204 if (!Tok.is(tok::l_brace)) {
3205 bool SuggestFixIt = false;
3206 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3207 if (Tok.isAtStartOfLine()) {
3208 switch (Tok.getKind()) {
3209 case tok::kw_private:
3210 case tok::kw_protected:
3211 case tok::kw_public:
3212 SuggestFixIt = NextToken().getKind() == tok::colon;
3214 case tok::kw_static_assert:
3217 // base-clause can have simple-template-id; 'template' can't be there
3218 case tok::kw_template:
3219 SuggestFixIt = true;
3221 case tok::identifier:
3222 SuggestFixIt = isConstructorDeclarator(true);
3225 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3229 DiagnosticBuilder LBraceDiag =
3230 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3232 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3233 // Try recovering from missing { after base-clause.
3235 Tok.setKind(tok::l_brace);
3238 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3244 assert(Tok.is(tok::l_brace));
3245 BalancedDelimiterTracker T(*this, tok::l_brace);
3249 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3250 IsFinalSpelledSealed,
3251 T.getOpenLocation());
3253 // C++ 11p3: Members of a class defined with the keyword class are private
3254 // by default. Members of a class defined with the keywords struct or union
3255 // are public by default.
3256 AccessSpecifier CurAS;
3257 if (TagType == DeclSpec::TST_class)
3261 ParsedAttributesWithRange AccessAttrs(AttrFactory);
3264 // While we still have something to read, read the member-declarations.
3265 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3266 Tok.isNot(tok::eof)) {
3267 // Each iteration of this loop reads one member-declaration.
3268 ParseCXXClassMemberDeclarationWithPragmas(
3269 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3273 SkipUntil(tok::r_brace);
3276 // If attributes exist after class contents, parse them.
3277 ParsedAttributes attrs(AttrFactory);
3278 MaybeParseGNUAttributes(attrs);
3281 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3282 T.getOpenLocation(),
3283 T.getCloseLocation(), attrs);
3285 // C++11 [class.mem]p2:
3286 // Within the class member-specification, the class is regarded as complete
3287 // within function bodies, default arguments, exception-specifications, and
3288 // brace-or-equal-initializers for non-static data members (including such
3289 // things in nested classes).
3290 if (TagDecl && NonNestedClass) {
3291 // We are not inside a nested class. This class and its nested classes
3292 // are complete and we can parse the delayed portions of method
3293 // declarations and the lexed inline method definitions, along with any
3294 // delayed attributes.
3295 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3296 ParseLexedAttributes(getCurrentClass());
3297 ParseLexedMethodDeclarations(getCurrentClass());
3299 // We've finished with all pending member declarations.
3300 Actions.ActOnFinishCXXMemberDecls();
3302 ParseLexedMemberInitializers(getCurrentClass());
3303 ParseLexedMethodDefs(getCurrentClass());
3304 PrevTokLocation = SavedPrevTokLocation;
3306 // We've finished parsing everything, including default argument
3308 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3312 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3314 // Leave the class scope.
3319 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3320 assert(Tok.is(tok::kw_namespace));
3322 // FIXME: Suggest where the close brace should have gone by looking
3323 // at indentation changes within the definition body.
3324 Diag(D->getLocation(),
3325 diag::err_missing_end_of_definition) << D;
3326 Diag(Tok.getLocation(),
3327 diag::note_missing_end_of_definition_before) << D;
3329 // Push '};' onto the token stream to recover.
3333 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3334 Tok.setKind(tok::semi);
3337 Tok.setKind(tok::r_brace);
3340 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3341 /// which explicitly initializes the members or base classes of a
3342 /// class (C++ [class.base.init]). For example, the three initializers
3343 /// after the ':' in the Derived constructor below:
3347 /// class Derived : Base {
3351 /// Derived(float f) : Base(), x(17), f(f) { }
3355 /// [C++] ctor-initializer:
3356 /// ':' mem-initializer-list
3358 /// [C++] mem-initializer-list:
3359 /// mem-initializer ...[opt]
3360 /// mem-initializer ...[opt] , mem-initializer-list
3361 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3362 assert(Tok.is(tok::colon) &&
3363 "Constructor initializer always starts with ':'");
3365 // Poison the SEH identifiers so they are flagged as illegal in constructor
3367 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3368 SourceLocation ColonLoc = ConsumeToken();
3370 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3371 bool AnyErrors = false;
3374 if (Tok.is(tok::code_completion)) {
3375 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3377 return cutOffParsing();
3380 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3381 if (!MemInit.isInvalid())
3382 MemInitializers.push_back(MemInit.get());
3386 if (Tok.is(tok::comma))
3388 else if (Tok.is(tok::l_brace))
3390 // If the previous initializer was valid and the next token looks like a
3391 // base or member initializer, assume that we're just missing a comma.
3392 else if (!MemInit.isInvalid() &&
3393 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3394 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3395 Diag(Loc, diag::err_ctor_init_missing_comma)
3396 << FixItHint::CreateInsertion(Loc, ", ");
3398 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3399 if (!MemInit.isInvalid())
3400 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3402 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3407 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3411 /// ParseMemInitializer - Parse a C++ member initializer, which is
3412 /// part of a constructor initializer that explicitly initializes one
3413 /// member or base class (C++ [class.base.init]). See
3414 /// ParseConstructorInitializer for an example.
3416 /// [C++] mem-initializer:
3417 /// mem-initializer-id '(' expression-list[opt] ')'
3418 /// [C++0x] mem-initializer-id braced-init-list
3420 /// [C++] mem-initializer-id:
3421 /// '::'[opt] nested-name-specifier[opt] class-name
3423 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3424 // parse '::'[opt] nested-name-specifier[opt]
3426 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
3429 IdentifierInfo *II = nullptr;
3430 SourceLocation IdLoc = Tok.getLocation();
3432 DeclSpec DS(AttrFactory);
3433 // : template_name<...>
3434 ParsedType TemplateTypeTy;
3436 if (Tok.is(tok::identifier)) {
3437 // Get the identifier. This may be a member name or a class name,
3438 // but we'll let the semantic analysis determine which it is.
3439 II = Tok.getIdentifierInfo();
3441 } else if (Tok.is(tok::annot_decltype)) {
3442 // Get the decltype expression, if there is one.
3443 // Uses of decltype will already have been converted to annot_decltype by
3444 // ParseOptionalCXXScopeSpecifier at this point.
3445 // FIXME: Can we get here with a scope specifier?
3446 ParseDecltypeSpecifier(DS);
3448 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3449 ? takeTemplateIdAnnotation(Tok)
3451 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3452 TemplateId->Kind == TNK_Dependent_template_name)) {
3453 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
3454 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3455 TemplateTypeTy = getTypeAnnotation(Tok);
3456 ConsumeAnnotationToken();
3458 Diag(Tok, diag::err_expected_member_or_base_name);
3464 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3465 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3467 // FIXME: Add support for signature help inside initializer lists.
3468 ExprResult InitList = ParseBraceInitializer();
3469 if (InitList.isInvalid())
3472 SourceLocation EllipsisLoc;
3473 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3475 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3476 TemplateTypeTy, DS, IdLoc,
3477 InitList.get(), EllipsisLoc);
3478 } else if(Tok.is(tok::l_paren)) {
3479 BalancedDelimiterTracker T(*this, tok::l_paren);
3482 // Parse the optional expression-list.
3483 ExprVector ArgExprs;
3484 CommaLocsTy CommaLocs;
3485 if (Tok.isNot(tok::r_paren) &&
3486 ParseExpressionList(ArgExprs, CommaLocs, [&] {
3487 QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
3488 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3489 T.getOpenLocation());
3490 CalledSignatureHelp = true;
3491 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
3493 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
3494 Actions.ProduceCtorInitMemberSignatureHelp(
3495 getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
3496 T.getOpenLocation());
3497 CalledSignatureHelp = true;
3499 SkipUntil(tok::r_paren, StopAtSemi);
3505 SourceLocation EllipsisLoc;
3506 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3508 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3509 TemplateTypeTy, DS, IdLoc,
3510 T.getOpenLocation(), ArgExprs,
3511 T.getCloseLocation(), EllipsisLoc);
3514 if (getLangOpts().CPlusPlus11)
3515 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3517 return Diag(Tok, diag::err_expected) << tok::l_paren;
3520 /// Parse a C++ exception-specification if present (C++0x [except.spec]).
3522 /// exception-specification:
3523 /// dynamic-exception-specification
3524 /// noexcept-specification
3526 /// noexcept-specification:
3528 /// 'noexcept' '(' constant-expression ')'
3529 ExceptionSpecificationType
3530 Parser::tryParseExceptionSpecification(bool Delayed,
3531 SourceRange &SpecificationRange,
3532 SmallVectorImpl<ParsedType> &DynamicExceptions,
3533 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3534 ExprResult &NoexceptExpr,
3535 CachedTokens *&ExceptionSpecTokens) {
3536 ExceptionSpecificationType Result = EST_None;
3537 ExceptionSpecTokens = nullptr;
3539 // Handle delayed parsing of exception-specifications.
3541 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3544 // Consume and cache the starting token.
3545 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3546 Token StartTok = Tok;
3547 SpecificationRange = SourceRange(ConsumeToken());
3550 if (!Tok.is(tok::l_paren)) {
3551 // If this is a bare 'noexcept', we're done.
3553 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3554 NoexceptExpr = nullptr;
3555 return EST_BasicNoexcept;
3558 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3559 return EST_DynamicNone;
3562 // Cache the tokens for the exception-specification.
3563 ExceptionSpecTokens = new CachedTokens;
3564 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3565 ExceptionSpecTokens->push_back(Tok); // '('
3566 SpecificationRange.setEnd(ConsumeParen()); // '('
3568 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3569 /*StopAtSemi=*/true,
3570 /*ConsumeFinalToken=*/true);
3571 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3573 return EST_Unparsed;
3576 // See if there's a dynamic specification.
3577 if (Tok.is(tok::kw_throw)) {
3578 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3580 DynamicExceptionRanges);
3581 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3582 "Produced different number of exception types and ranges.");
3585 // If there's no noexcept specification, we're done.
3586 if (Tok.isNot(tok::kw_noexcept))
3589 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3591 // If we already had a dynamic specification, parse the noexcept for,
3592 // recovery, but emit a diagnostic and don't store the results.
3593 SourceRange NoexceptRange;
3594 ExceptionSpecificationType NoexceptType = EST_None;
3596 SourceLocation KeywordLoc = ConsumeToken();
3597 if (Tok.is(tok::l_paren)) {
3598 // There is an argument.
3599 BalancedDelimiterTracker T(*this, tok::l_paren);
3601 NoexceptExpr = ParseConstantExpression();
3603 if (!NoexceptExpr.isInvalid()) {
3604 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3606 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3608 NoexceptType = EST_BasicNoexcept;
3611 // There is no argument.
3612 NoexceptType = EST_BasicNoexcept;
3613 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3616 if (Result == EST_None) {
3617 SpecificationRange = NoexceptRange;
3618 Result = NoexceptType;
3620 // If there's a dynamic specification after a noexcept specification,
3621 // parse that and ignore the results.
3622 if (Tok.is(tok::kw_throw)) {
3623 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3624 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3625 DynamicExceptionRanges);
3628 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3634 static void diagnoseDynamicExceptionSpecification(
3635 Parser &P, SourceRange Range, bool IsNoexcept) {
3636 if (P.getLangOpts().CPlusPlus11) {
3637 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3638 P.Diag(Range.getBegin(),
3639 P.getLangOpts().CPlusPlus17 && !IsNoexcept
3640 ? diag::ext_dynamic_exception_spec
3641 : diag::warn_exception_spec_deprecated)
3643 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3644 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3648 /// ParseDynamicExceptionSpecification - Parse a C++
3649 /// dynamic-exception-specification (C++ [except.spec]).
3651 /// dynamic-exception-specification:
3652 /// 'throw' '(' type-id-list [opt] ')'
3653 /// [MS] 'throw' '(' '...' ')'
3656 /// type-id ... [opt]
3657 /// type-id-list ',' type-id ... [opt]
3659 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3660 SourceRange &SpecificationRange,
3661 SmallVectorImpl<ParsedType> &Exceptions,
3662 SmallVectorImpl<SourceRange> &Ranges) {
3663 assert(Tok.is(tok::kw_throw) && "expected throw");
3665 SpecificationRange.setBegin(ConsumeToken());
3666 BalancedDelimiterTracker T(*this, tok::l_paren);
3667 if (T.consumeOpen()) {
3668 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3669 SpecificationRange.setEnd(SpecificationRange.getBegin());
3670 return EST_DynamicNone;
3673 // Parse throw(...), a Microsoft extension that means "this function
3674 // can throw anything".
3675 if (Tok.is(tok::ellipsis)) {
3676 SourceLocation EllipsisLoc = ConsumeToken();
3677 if (!getLangOpts().MicrosoftExt)
3678 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3680 SpecificationRange.setEnd(T.getCloseLocation());
3681 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3685 // Parse the sequence of type-ids.
3687 while (Tok.isNot(tok::r_paren)) {
3688 TypeResult Res(ParseTypeName(&Range));
3690 if (Tok.is(tok::ellipsis)) {
3691 // C++0x [temp.variadic]p5:
3692 // - In a dynamic-exception-specification (15.4); the pattern is a
3694 SourceLocation Ellipsis = ConsumeToken();
3695 Range.setEnd(Ellipsis);
3696 if (!Res.isInvalid())
3697 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3700 if (!Res.isInvalid()) {
3701 Exceptions.push_back(Res.get());
3702 Ranges.push_back(Range);
3705 if (!TryConsumeToken(tok::comma))
3710 SpecificationRange.setEnd(T.getCloseLocation());
3711 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3712 Exceptions.empty());
3713 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3716 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3717 /// function declaration.
3718 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3719 bool MayBeFollowedByDirectInit) {
3720 assert(Tok.is(tok::arrow) && "expected arrow");
3724 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3725 ? DeclaratorContext::TrailingReturnVarContext
3726 : DeclaratorContext::TrailingReturnContext);
3729 /// We have just started parsing the definition of a new class,
3730 /// so push that class onto our stack of classes that is currently
3732 Sema::ParsingClassState
3733 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3735 assert((NonNestedClass || !ClassStack.empty()) &&
3736 "Nested class without outer class");
3737 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3738 return Actions.PushParsingClass();
3741 /// Deallocate the given parsed class and all of its nested
3743 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3744 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3745 delete Class->LateParsedDeclarations[I];
3749 /// Pop the top class of the stack of classes that are
3750 /// currently being parsed.
3752 /// This routine should be called when we have finished parsing the
3753 /// definition of a class, but have not yet popped the Scope
3754 /// associated with the class's definition.
3755 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3756 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3758 Actions.PopParsingClass(state);
3760 ParsingClass *Victim = ClassStack.top();
3762 if (Victim->TopLevelClass) {
3763 // Deallocate all of the nested classes of this class,
3764 // recursively: we don't need to keep any of this information.
3765 DeallocateParsedClasses(Victim);
3768 assert(!ClassStack.empty() && "Missing top-level class?");
3770 if (Victim->LateParsedDeclarations.empty()) {
3771 // The victim is a nested class, but we will not need to perform
3772 // any processing after the definition of this class since it has
3773 // no members whose handling was delayed. Therefore, we can just
3774 // remove this nested class.
3775 DeallocateParsedClasses(Victim);
3779 // This nested class has some members that will need to be processed
3780 // after the top-level class is completely defined. Therefore, add
3781 // it to the list of nested classes within its parent.
3782 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3783 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3784 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3787 /// Try to parse an 'identifier' which appears within an attribute-token.
3789 /// \return the parsed identifier on success, and 0 if the next token is not an
3790 /// attribute-token.
3792 /// C++11 [dcl.attr.grammar]p3:
3793 /// If a keyword or an alternative token that satisfies the syntactic
3794 /// requirements of an identifier is contained in an attribute-token,
3795 /// it is considered an identifier.
3796 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3797 switch (Tok.getKind()) {
3799 // Identifiers and keywords have identifier info attached.
3800 if (!Tok.isAnnotation()) {
3801 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3802 Loc = ConsumeToken();
3808 case tok::numeric_constant: {
3809 // If we got a numeric constant, check to see if it comes from a macro that
3810 // corresponds to the predefined __clang__ macro. If it does, warn the user
3811 // and recover by pretending they said _Clang instead.
3812 if (Tok.getLocation().isMacroID()) {
3813 SmallString<8> ExpansionBuf;
3814 SourceLocation ExpansionLoc =
3815 PP.getSourceManager().getExpansionLoc(Tok.getLocation());
3816 StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
3817 if (Spelling == "__clang__") {
3818 SourceRange TokRange(
3820 PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
3821 Diag(Tok, diag::warn_wrong_clang_attr_namespace)
3822 << FixItHint::CreateReplacement(TokRange, "_Clang");
3823 Loc = ConsumeToken();
3824 return &PP.getIdentifierTable().get("_Clang");
3830 case tok::ampamp: // 'and'
3831 case tok::pipe: // 'bitor'
3832 case tok::pipepipe: // 'or'
3833 case tok::caret: // 'xor'
3834 case tok::tilde: // 'compl'
3835 case tok::amp: // 'bitand'
3836 case tok::ampequal: // 'and_eq'
3837 case tok::pipeequal: // 'or_eq'
3838 case tok::caretequal: // 'xor_eq'
3839 case tok::exclaim: // 'not'
3840 case tok::exclaimequal: // 'not_eq'
3841 // Alternative tokens do not have identifier info, but their spelling
3842 // starts with an alphabetical character.
3843 SmallString<8> SpellingBuf;
3844 SourceLocation SpellingLoc =
3845 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3846 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3847 if (isLetter(Spelling[0])) {
3848 Loc = ConsumeToken();
3849 return &PP.getIdentifierTable().get(Spelling);
3855 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3856 IdentifierInfo *ScopeName) {
3857 switch (ParsedAttr::getKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
3858 case ParsedAttr::AT_CarriesDependency:
3859 case ParsedAttr::AT_Deprecated:
3860 case ParsedAttr::AT_FallThrough:
3861 case ParsedAttr::AT_CXX11NoReturn:
3863 case ParsedAttr::AT_WarnUnusedResult:
3864 return !ScopeName && AttrName->getName().equals("nodiscard");
3865 case ParsedAttr::AT_Unused:
3866 return !ScopeName && AttrName->getName().equals("maybe_unused");
3872 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3874 /// [C++11] attribute-argument-clause:
3875 /// '(' balanced-token-seq ')'
3877 /// [C++11] balanced-token-seq:
3879 /// balanced-token-seq balanced-token
3881 /// [C++11] balanced-token:
3882 /// '(' balanced-token-seq ')'
3883 /// '[' balanced-token-seq ']'
3884 /// '{' balanced-token-seq '}'
3885 /// any token but '(', ')', '[', ']', '{', or '}'
3886 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3887 SourceLocation AttrNameLoc,
3888 ParsedAttributes &Attrs,
3889 SourceLocation *EndLoc,
3890 IdentifierInfo *ScopeName,
3891 SourceLocation ScopeLoc) {
3892 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3893 SourceLocation LParenLoc = Tok.getLocation();
3894 const LangOptions &LO = getLangOpts();
3895 ParsedAttr::Syntax Syntax =
3896 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
3898 // If the attribute isn't known, we will not attempt to parse any
3900 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3901 AttrName, getTargetInfo(), getLangOpts())) {
3902 // Eat the left paren, then skip to the ending right paren.
3904 SkipUntil(tok::r_paren);
3908 if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
3909 // GNU-scoped attributes have some special cases to handle GNU-specific
3911 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3912 ScopeLoc, Syntax, nullptr);
3917 // Some Clang-scoped attributes have some special parsing behavior.
3918 if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
3919 NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
3920 ScopeName, ScopeLoc, Syntax);
3923 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3924 ScopeName, ScopeLoc, Syntax);
3926 if (!Attrs.empty() &&
3927 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3928 ParsedAttr &Attr = Attrs.back();
3929 // If the attribute is a standard or built-in attribute and we are
3930 // parsing an argument list, we need to determine whether this attribute
3931 // was allowed to have an argument list (such as [[deprecated]]), and how
3932 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3933 if (Attr.getMaxArgs() && !NumArgs) {
3934 // The attribute was allowed to have arguments, but none were provided
3935 // even though the attribute parsed successfully. This is an error.
3936 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3937 Attr.setInvalid(true);
3938 } else if (!Attr.getMaxArgs()) {
3939 // The attribute parsed successfully, but was not allowed to have any
3940 // arguments. It doesn't matter whether any were provided -- the
3941 // presence of the argument list (even if empty) is diagnosed.
3942 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3944 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3945 Attr.setInvalid(true);
3951 /// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
3953 /// [C++11] attribute-specifier:
3954 /// '[' '[' attribute-list ']' ']'
3955 /// alignment-specifier
3957 /// [C++11] attribute-list:
3959 /// attribute-list ',' attribute[opt]
3961 /// attribute-list ',' attribute '...'
3963 /// [C++11] attribute:
3964 /// attribute-token attribute-argument-clause[opt]
3966 /// [C++11] attribute-token:
3968 /// attribute-scoped-token
3970 /// [C++11] attribute-scoped-token:
3971 /// attribute-namespace '::' identifier
3973 /// [C++11] attribute-namespace:
3975 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3976 SourceLocation *endLoc) {
3977 if (Tok.is(tok::kw_alignas)) {
3978 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3979 ParseAlignmentSpecifier(attrs, endLoc);
3983 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3984 "Not a double square bracket attribute list");
3986 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3991 SourceLocation CommonScopeLoc;
3992 IdentifierInfo *CommonScopeName = nullptr;
3993 if (Tok.is(tok::kw_using)) {
3994 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
3995 ? diag::warn_cxx14_compat_using_attribute_ns
3996 : diag::ext_using_attribute_ns);
3999 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
4000 if (!CommonScopeName) {
4001 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4002 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
4004 if (!TryConsumeToken(tok::colon) && CommonScopeName)
4005 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
4008 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
4010 while (Tok.isNot(tok::r_square)) {
4011 // attribute not present
4012 if (TryConsumeToken(tok::comma))
4015 SourceLocation ScopeLoc, AttrLoc;
4016 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
4018 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4020 // Break out to the "expected ']'" diagnostic.
4024 if (TryConsumeToken(tok::coloncolon)) {
4025 ScopeName = AttrName;
4028 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
4030 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4031 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
4036 if (CommonScopeName) {
4038 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4039 << SourceRange(CommonScopeLoc);
4041 ScopeName = CommonScopeName;
4042 ScopeLoc = CommonScopeLoc;
4046 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
4047 bool AttrParsed = false;
4050 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4051 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
4052 << AttrName << SourceRange(SeenAttrs[AttrName]);
4054 // Parse attribute arguments
4055 if (Tok.is(tok::l_paren))
4056 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4057 ScopeName, ScopeLoc);
4062 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4063 ScopeName, ScopeLoc, nullptr, 0,
4064 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
4066 if (TryConsumeToken(tok::ellipsis))
4067 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4071 if (ExpectAndConsume(tok::r_square))
4072 SkipUntil(tok::r_square);
4074 *endLoc = Tok.getLocation();
4075 if (ExpectAndConsume(tok::r_square))
4076 SkipUntil(tok::r_square);
4079 /// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
4081 /// attribute-specifier-seq:
4082 /// attribute-specifier-seq[opt] attribute-specifier
4083 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
4084 SourceLocation *endLoc) {
4085 assert(standardAttributesAllowed());
4087 SourceLocation StartLoc = Tok.getLocation(), Loc;
4092 ParseCXX11AttributeSpecifier(attrs, endLoc);
4093 } while (isCXX11AttributeSpecifier());
4095 attrs.Range = SourceRange(StartLoc, *endLoc);
4098 void Parser::DiagnoseAndSkipCXX11Attributes() {
4099 // Start and end location of an attribute or an attribute list.
4100 SourceLocation StartLoc = Tok.getLocation();
4101 SourceLocation EndLoc = SkipCXX11Attributes();
4103 if (EndLoc.isValid()) {
4104 SourceRange Range(StartLoc, EndLoc);
4105 Diag(StartLoc, diag::err_attributes_not_allowed)
4110 SourceLocation Parser::SkipCXX11Attributes() {
4111 SourceLocation EndLoc;
4113 if (!isCXX11AttributeSpecifier())
4117 if (Tok.is(tok::l_square)) {
4118 BalancedDelimiterTracker T(*this, tok::l_square);
4121 EndLoc = T.getCloseLocation();
4123 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4125 BalancedDelimiterTracker T(*this, tok::l_paren);
4126 if (!T.consumeOpen())
4128 EndLoc = T.getCloseLocation();
4130 } while (isCXX11AttributeSpecifier());
4135 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4136 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4137 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4138 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4139 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4141 SourceLocation UuidLoc = Tok.getLocation();
4144 // Ignore the left paren location for now.
4145 BalancedDelimiterTracker T(*this, tok::l_paren);
4146 if (T.consumeOpen()) {
4147 Diag(Tok, diag::err_expected) << tok::l_paren;
4151 ArgsVector ArgExprs;
4152 if (Tok.is(tok::string_literal)) {
4153 // Easy case: uuid("...") -- quoted string.
4154 ExprResult StringResult = ParseStringLiteralExpression();
4155 if (StringResult.isInvalid())
4157 ArgExprs.push_back(StringResult.get());
4159 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4160 // quotes in the parens. Just append the spelling of all tokens encountered
4161 // until the closing paren.
4163 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4166 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4167 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4168 // tok::numeric_constant (0000) should be enough. But the spelling of the
4169 // uuid argument is checked later anyways, so there's no harm in accepting
4170 // almost anything here.
4171 // cl is very strict about whitespace in this form and errors out if any
4172 // is present, so check the space flags on the tokens.
4173 SourceLocation StartLoc = Tok.getLocation();
4174 while (Tok.isNot(tok::r_paren)) {
4175 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4176 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4177 SkipUntil(tok::r_paren, StopAtSemi);
4180 SmallString<16> SpellingBuffer;
4181 SpellingBuffer.resize(Tok.getLength() + 1);
4182 bool Invalid = false;
4183 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4185 SkipUntil(tok::r_paren, StopAtSemi);
4188 StrBuffer += TokSpelling;
4193 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4194 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4199 // Pretend the user wrote the appropriate string literal here.
4200 // ActOnStringLiteral() copies the string data into the literal, so it's
4201 // ok that the Token points to StrBuffer.
4203 Toks[0].startToken();
4204 Toks[0].setKind(tok::string_literal);
4205 Toks[0].setLocation(StartLoc);
4206 Toks[0].setLiteralData(StrBuffer.data());
4207 Toks[0].setLength(StrBuffer.size());
4208 StringLiteral *UuidString =
4209 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4210 ArgExprs.push_back(UuidString);
4213 if (!T.consumeClose()) {
4214 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4215 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4216 ParsedAttr::AS_Microsoft);
4220 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4222 /// [MS] ms-attribute:
4223 /// '[' token-seq ']'
4225 /// [MS] ms-attribute-seq:
4226 /// ms-attribute[opt]
4227 /// ms-attribute ms-attribute-seq
4228 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4229 SourceLocation *endLoc) {
4230 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4233 // FIXME: If this is actually a C++11 attribute, parse it as one.
4234 BalancedDelimiterTracker T(*this, tok::l_square);
4237 // Skip most ms attributes except for a whitelist.
4239 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4240 if (Tok.isNot(tok::identifier)) // ']', but also eof
4242 if (Tok.getIdentifierInfo()->getName() == "uuid")
4243 ParseMicrosoftUuidAttributeArgs(attrs);
4250 *endLoc = T.getCloseLocation();
4251 } while (Tok.is(tok::l_square));
4254 void Parser::ParseMicrosoftIfExistsClassDeclaration(
4255 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4256 AccessSpecifier &CurAS) {
4257 IfExistsCondition Result;
4258 if (ParseMicrosoftIfExistsCondition(Result))
4261 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4262 if (Braces.consumeOpen()) {
4263 Diag(Tok, diag::err_expected) << tok::l_brace;
4267 switch (Result.Behavior) {
4269 // Parse the declarations below.
4273 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4274 << Result.IsIfExists;
4275 // Fall through to skip.
4283 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4284 // __if_exists, __if_not_exists can nest.
4285 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4286 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType,
4287 AccessAttrs, CurAS);
4291 // Check for extraneous top-level semicolon.
4292 if (Tok.is(tok::semi)) {
4293 ConsumeExtraSemi(InsideStruct, TagType);
4297 AccessSpecifier AS = getAccessSpecifierIfPresent();
4298 if (AS != AS_none) {
4299 // Current token is a C++ access specifier.
4301 SourceLocation ASLoc = Tok.getLocation();
4303 if (Tok.is(tok::colon))
4304 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4305 ParsedAttributesView{});
4307 Diag(Tok, diag::err_expected) << tok::colon;
4312 // Parse all the comma separated declarators.
4313 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
4316 Braces.consumeClose();