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/Basic/Attributes.h"
18 #include "clang/Basic/CharInfo.h"
19 #include "clang/Basic/OperatorKinds.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Parse/ParseDiagnostic.h"
22 #include "clang/Parse/RAIIObjectsForParser.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/SmallString.h"
30 using namespace clang;
32 /// ParseNamespace - We know that the current token is a namespace keyword. This
33 /// may either be a top level namespace or a block-level namespace alias. If
34 /// there was an inline keyword, it has already been parsed.
36 /// namespace-definition: [C++ 7.3: basic.namespace]
37 /// named-namespace-definition
38 /// unnamed-namespace-definition
40 /// unnamed-namespace-definition:
41 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
43 /// named-namespace-definition:
44 /// original-namespace-definition
45 /// extension-namespace-definition
47 /// original-namespace-definition:
48 /// 'inline'[opt] 'namespace' identifier attributes[opt]
49 /// '{' namespace-body '}'
51 /// extension-namespace-definition:
52 /// 'inline'[opt] 'namespace' original-namespace-name
53 /// '{' namespace-body '}'
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 std::vector<SourceLocation> ExtraIdentLoc;
74 std::vector<IdentifierInfo*> ExtraIdent;
75 std::vector<SourceLocation> ExtraNamespaceLoc;
77 ParsedAttributesWithRange attrs(AttrFactory);
78 SourceLocation attrLoc;
79 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
80 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
81 ? diag::warn_cxx14_compat_ns_enum_attribute
82 : diag::ext_ns_enum_attribute)
84 attrLoc = Tok.getLocation();
85 ParseCXX11Attributes(attrs);
88 if (Tok.is(tok::identifier)) {
89 Ident = Tok.getIdentifierInfo();
90 IdentLoc = ConsumeToken(); // eat the identifier.
91 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
92 ExtraNamespaceLoc.push_back(ConsumeToken());
93 ExtraIdent.push_back(Tok.getIdentifierInfo());
94 ExtraIdentLoc.push_back(ConsumeToken());
98 // A nested namespace definition cannot have attributes.
99 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
100 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
102 // Read label attributes, if present.
103 if (Tok.is(tok::kw___attribute)) {
104 attrLoc = Tok.getLocation();
105 ParseGNUAttributes(attrs);
108 if (Tok.is(tok::equal)) {
110 Diag(Tok, diag::err_expected) << tok::identifier;
111 // Skip to end of the definition and eat the ';'.
112 SkipUntil(tok::semi);
115 if (attrLoc.isValid())
116 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
117 if (InlineLoc.isValid())
118 Diag(InlineLoc, diag::err_inline_namespace_alias)
119 << FixItHint::CreateRemoval(InlineLoc);
120 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
121 return Actions.ConvertDeclToDeclGroup(NSAlias);
124 BalancedDelimiterTracker T(*this, tok::l_brace);
125 if (T.consumeOpen()) {
127 Diag(Tok, diag::err_expected) << tok::l_brace;
129 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
133 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
134 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
135 getCurScope()->getFnParent()) {
136 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
137 SkipUntil(tok::r_brace);
141 if (ExtraIdent.empty()) {
142 // Normal namespace definition, not a nested-namespace-definition.
143 } else if (InlineLoc.isValid()) {
144 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
145 } else if (getLangOpts().CPlusPlus17) {
146 Diag(ExtraNamespaceLoc[0],
147 diag::warn_cxx14_compat_nested_namespace_definition);
149 TentativeParsingAction TPA(*this);
150 SkipUntil(tok::r_brace, StopBeforeMatch);
151 Token rBraceToken = Tok;
154 if (!rBraceToken.is(tok::r_brace)) {
155 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
156 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
158 std::string NamespaceFix;
159 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
160 E = ExtraIdent.end(); I != E; ++I) {
161 NamespaceFix += " { namespace ";
162 NamespaceFix += (*I)->getName();
166 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
169 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
170 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
171 ExtraIdentLoc.back()),
173 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
177 // If we're still good, complain about inline namespaces in non-C++0x now.
178 if (InlineLoc.isValid())
179 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
180 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
182 // Enter a scope for the namespace.
183 ParseScope NamespaceScope(this, Scope::DeclScope);
185 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
187 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
188 IdentLoc, Ident, T.getOpenLocation(),
189 attrs.getList(), ImplicitUsingDirectiveDecl);
191 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
192 "parsing namespace");
194 // Parse the contents of the namespace. This includes parsing recovery on
195 // any improperly nested namespaces.
196 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
197 InlineLoc, attrs, T);
199 // Leave the namespace scope.
200 NamespaceScope.Exit();
202 DeclEnd = T.getCloseLocation();
203 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
205 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
206 ImplicitUsingDirectiveDecl);
209 /// ParseInnerNamespace - Parse the contents of a namespace.
210 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
211 std::vector<IdentifierInfo *> &Ident,
212 std::vector<SourceLocation> &NamespaceLoc,
213 unsigned int index, SourceLocation &InlineLoc,
214 ParsedAttributes &attrs,
215 BalancedDelimiterTracker &Tracker) {
216 if (index == Ident.size()) {
217 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
218 Tok.isNot(tok::eof)) {
219 ParsedAttributesWithRange attrs(AttrFactory);
220 MaybeParseCXX11Attributes(attrs);
221 ParseExternalDeclaration(attrs);
224 // The caller is what called check -- we are simply calling
226 Tracker.consumeClose();
231 // Handle a nested namespace definition.
232 // FIXME: Preserve the source information through to the AST rather than
233 // desugaring it here.
234 ParseScope NamespaceScope(this, Scope::DeclScope);
235 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
237 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
238 NamespaceLoc[index], IdentLoc[index],
239 Ident[index], Tracker.getOpenLocation(),
240 attrs.getList(), ImplicitUsingDirectiveDecl);
241 assert(!ImplicitUsingDirectiveDecl &&
242 "nested namespace definition cannot define anonymous namespace");
244 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
247 NamespaceScope.Exit();
248 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
251 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
252 /// alias definition.
254 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
255 SourceLocation AliasLoc,
256 IdentifierInfo *Alias,
257 SourceLocation &DeclEnd) {
258 assert(Tok.is(tok::equal) && "Not equal token");
260 ConsumeToken(); // eat the '='.
262 if (Tok.is(tok::code_completion)) {
263 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
269 // Parse (optional) nested-name-specifier.
270 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
271 /*MayBePseudoDestructor=*/nullptr,
272 /*IsTypename=*/false,
274 /*OnlyNamespace=*/true);
276 if (Tok.isNot(tok::identifier)) {
277 Diag(Tok, diag::err_expected_namespace_name);
278 // Skip to end of the definition and eat the ';'.
279 SkipUntil(tok::semi);
283 if (SS.isInvalid()) {
284 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
285 // Skip to end of the definition and eat the ';'.
286 SkipUntil(tok::semi);
291 IdentifierInfo *Ident = Tok.getIdentifierInfo();
292 SourceLocation IdentLoc = ConsumeToken();
295 DeclEnd = Tok.getLocation();
296 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
297 SkipUntil(tok::semi);
299 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
300 Alias, SS, IdentLoc, Ident);
303 /// ParseLinkage - We know that the current token is a string_literal
304 /// and just before that, that extern was seen.
306 /// linkage-specification: [C++ 7.5p2: dcl.link]
307 /// 'extern' string-literal '{' declaration-seq[opt] '}'
308 /// 'extern' string-literal declaration
310 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
311 assert(isTokenStringLiteral() && "Not a string literal!");
312 ExprResult Lang = ParseStringLiteralExpression(false);
314 ParseScope LinkageScope(this, Scope::DeclScope);
318 : Actions.ActOnStartLinkageSpecification(
319 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
320 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
322 ParsedAttributesWithRange attrs(AttrFactory);
323 MaybeParseCXX11Attributes(attrs);
325 if (Tok.isNot(tok::l_brace)) {
326 // Reset the source range in DS, as the leading "extern"
327 // does not really belong to the inner declaration ...
328 DS.SetRangeStart(SourceLocation());
329 DS.SetRangeEnd(SourceLocation());
330 // ... but anyway remember that such an "extern" was seen.
331 DS.setExternInLinkageSpec(true);
332 ParseExternalDeclaration(attrs, &DS);
333 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
334 getCurScope(), LinkageSpec, SourceLocation())
340 ProhibitAttributes(attrs);
342 BalancedDelimiterTracker T(*this, tok::l_brace);
345 unsigned NestedModules = 0;
347 switch (Tok.getKind()) {
348 case tok::annot_module_begin:
353 case tok::annot_module_end:
360 case tok::annot_module_include:
372 ParsedAttributesWithRange attrs(AttrFactory);
373 MaybeParseCXX11Attributes(attrs);
374 ParseExternalDeclaration(attrs);
382 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
383 getCurScope(), LinkageSpec, T.getCloseLocation())
387 /// Parse a C++ Modules TS export-declaration.
389 /// export-declaration:
390 /// 'export' declaration
391 /// 'export' '{' declaration-seq[opt] '}'
393 Decl *Parser::ParseExportDeclaration() {
394 assert(Tok.is(tok::kw_export));
395 SourceLocation ExportLoc = ConsumeToken();
397 ParseScope ExportScope(this, Scope::DeclScope);
398 Decl *ExportDecl = Actions.ActOnStartExportDecl(
399 getCurScope(), ExportLoc,
400 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
402 if (Tok.isNot(tok::l_brace)) {
403 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
404 ParsedAttributesWithRange Attrs(AttrFactory);
405 MaybeParseCXX11Attributes(Attrs);
406 MaybeParseMicrosoftAttributes(Attrs);
407 ParseExternalDeclaration(Attrs);
408 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
412 BalancedDelimiterTracker T(*this, tok::l_brace);
415 // The Modules TS draft says "An export-declaration shall declare at least one
416 // entity", but the intent is that it shall contain at least one declaration.
417 if (Tok.is(tok::r_brace))
418 Diag(ExportLoc, diag::err_export_empty)
419 << SourceRange(ExportLoc, Tok.getLocation());
421 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
422 Tok.isNot(tok::eof)) {
423 ParsedAttributesWithRange Attrs(AttrFactory);
424 MaybeParseCXX11Attributes(Attrs);
425 MaybeParseMicrosoftAttributes(Attrs);
426 ParseExternalDeclaration(Attrs);
430 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
431 T.getCloseLocation());
434 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
435 /// using-directive. Assumes that current token is 'using'.
436 Parser::DeclGroupPtrTy
437 Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
438 const ParsedTemplateInfo &TemplateInfo,
439 SourceLocation &DeclEnd,
440 ParsedAttributesWithRange &attrs) {
441 assert(Tok.is(tok::kw_using) && "Not using token");
442 ObjCDeclContextSwitch ObjCDC(*this);
445 SourceLocation UsingLoc = ConsumeToken();
447 if (Tok.is(tok::code_completion)) {
448 Actions.CodeCompleteUsing(getCurScope());
453 // 'using namespace' means this is a using-directive.
454 if (Tok.is(tok::kw_namespace)) {
455 // Template parameters are always an error here.
456 if (TemplateInfo.Kind) {
457 SourceRange R = TemplateInfo.getSourceRange();
458 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
459 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
462 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
463 return Actions.ConvertDeclToDeclGroup(UsingDir);
466 // Otherwise, it must be a using-declaration or an alias-declaration.
468 // Using declarations can't have attributes.
469 ProhibitAttributes(attrs);
471 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
475 /// ParseUsingDirective - Parse C++ using-directive, assumes
476 /// that current token is 'namespace' and 'using' was already parsed.
478 /// using-directive: [C++ 7.3.p4: namespace.udir]
479 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
481 /// [GNU] using-directive:
482 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
483 /// namespace-name attributes[opt] ;
485 Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
486 SourceLocation UsingLoc,
487 SourceLocation &DeclEnd,
488 ParsedAttributes &attrs) {
489 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
492 SourceLocation NamespcLoc = ConsumeToken();
494 if (Tok.is(tok::code_completion)) {
495 Actions.CodeCompleteUsingDirective(getCurScope());
501 // Parse (optional) nested-name-specifier.
502 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
503 /*MayBePseudoDestructor=*/nullptr,
504 /*IsTypename=*/false,
506 /*OnlyNamespace=*/true);
508 IdentifierInfo *NamespcName = nullptr;
509 SourceLocation IdentLoc = SourceLocation();
511 // Parse namespace-name.
512 if (Tok.isNot(tok::identifier)) {
513 Diag(Tok, diag::err_expected_namespace_name);
514 // If there was invalid namespace name, skip to end of decl, and eat ';'.
515 SkipUntil(tok::semi);
516 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
520 if (SS.isInvalid()) {
521 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
522 // Skip to end of the definition and eat the ';'.
523 SkipUntil(tok::semi);
528 NamespcName = Tok.getIdentifierInfo();
529 IdentLoc = ConsumeToken();
531 // Parse (optional) attributes (most likely GNU strong-using extension).
532 bool GNUAttr = false;
533 if (Tok.is(tok::kw___attribute)) {
535 ParseGNUAttributes(attrs);
539 DeclEnd = Tok.getLocation();
540 if (ExpectAndConsume(tok::semi,
541 GNUAttr ? diag::err_expected_semi_after_attribute_list
542 : diag::err_expected_semi_after_namespace_name))
543 SkipUntil(tok::semi);
545 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
546 IdentLoc, NamespcName, attrs.getList());
549 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
551 /// using-declarator:
552 /// 'typename'[opt] nested-name-specifier unqualified-id
554 bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
555 UsingDeclarator &D) {
558 // Ignore optional 'typename'.
559 // FIXME: This is wrong; we should parse this as a typename-specifier.
560 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
562 if (Tok.is(tok::kw___super)) {
563 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
567 // Parse nested-name-specifier.
568 IdentifierInfo *LastII = nullptr;
569 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
570 /*MayBePseudoDtor=*/nullptr,
571 /*IsTypename=*/false,
573 if (D.SS.isInvalid())
576 // Parse the unqualified-id. We allow parsing of both constructor and
577 // destructor names and allow the action module to diagnose any semantic
580 // C++11 [class.qual]p2:
581 // [...] in a using-declaration that is a member-declaration, if the name
582 // specified after the nested-name-specifier is the same as the identifier
583 // or the simple-template-id's template-name in the last component of the
584 // nested-name-specifier, the name is [...] considered to name the
586 if (getLangOpts().CPlusPlus11 &&
587 Context == DeclaratorContext::MemberContext &&
588 Tok.is(tok::identifier) &&
589 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
590 NextToken().is(tok::ellipsis)) &&
591 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
592 !D.SS.getScopeRep()->getAsNamespace() &&
593 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
594 SourceLocation IdLoc = ConsumeToken();
596 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
597 D.Name.setConstructorName(Type, IdLoc, IdLoc);
599 if (ParseUnqualifiedId(
600 D.SS, /*EnteringContext=*/false,
601 /*AllowDestructorName=*/true,
602 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
603 NextToken().is(tok::equal)),
604 /*AllowDeductionGuide=*/false,
605 nullptr, D.TemplateKWLoc, D.Name))
609 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
610 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
611 diag::warn_cxx17_compat_using_declaration_pack :
612 diag::ext_using_declaration_pack);
617 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
618 /// Assumes that 'using' was already seen.
620 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
621 /// 'using' using-declarator-list[opt] ;
623 /// using-declarator-list: [C++1z]
624 /// using-declarator '...'[opt]
625 /// using-declarator-list ',' using-declarator '...'[opt]
627 /// using-declarator-list: [C++98-14]
630 /// alias-declaration: C++11 [dcl.dcl]p1
631 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
633 Parser::DeclGroupPtrTy
634 Parser::ParseUsingDeclaration(DeclaratorContext Context,
635 const ParsedTemplateInfo &TemplateInfo,
636 SourceLocation UsingLoc, SourceLocation &DeclEnd,
637 AccessSpecifier AS) {
638 // Check for misplaced attributes before the identifier in an
639 // alias-declaration.
640 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
641 MaybeParseCXX11Attributes(MisplacedAttrs);
644 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
646 ParsedAttributesWithRange Attrs(AttrFactory);
647 MaybeParseGNUAttributes(Attrs);
648 MaybeParseCXX11Attributes(Attrs);
650 // Maybe this is an alias-declaration.
651 if (Tok.is(tok::equal)) {
652 if (InvalidDeclarator) {
653 SkipUntil(tok::semi);
657 // If we had any misplaced attributes from earlier, this is where they
658 // should have been written.
659 if (MisplacedAttrs.Range.isValid()) {
660 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
661 << FixItHint::CreateInsertionFromRange(
663 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
664 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
665 Attrs.takeAllFrom(MisplacedAttrs);
668 Decl *DeclFromDeclSpec = nullptr;
669 Decl *AD = ParseAliasDeclarationAfterDeclarator(
670 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
671 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
674 // C++11 attributes are not allowed on a using-declaration, but GNU ones
676 ProhibitAttributes(MisplacedAttrs);
677 ProhibitAttributes(Attrs);
679 // Diagnose an attempt to declare a templated using-declaration.
680 // In C++11, alias-declarations can be templates:
681 // template <...> using id = type;
682 if (TemplateInfo.Kind) {
683 SourceRange R = TemplateInfo.getSourceRange();
684 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
685 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
687 // Unfortunately, we have to bail out instead of recovering by
688 // ignoring the parameters, just in case the nested name specifier
689 // depends on the parameters.
693 SmallVector<Decl *, 8> DeclsInGroup;
695 // Parse (optional) attributes (most likely GNU strong-using extension).
696 MaybeParseGNUAttributes(Attrs);
698 if (InvalidDeclarator)
699 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
701 // "typename" keyword is allowed for identifiers only,
702 // because it may be a type definition.
703 if (D.TypenameLoc.isValid() &&
704 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
705 Diag(D.Name.getSourceRange().getBegin(),
706 diag::err_typename_identifiers_only)
707 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
708 // Proceed parsing, but discard the typename keyword.
709 D.TypenameLoc = SourceLocation();
712 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
713 D.TypenameLoc, D.SS, D.Name,
714 D.EllipsisLoc, Attrs.getList());
716 DeclsInGroup.push_back(UD);
719 if (!TryConsumeToken(tok::comma))
722 // Parse another using-declarator.
724 InvalidDeclarator = ParseUsingDeclarator(Context, D);
727 if (DeclsInGroup.size() > 1)
728 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
729 diag::warn_cxx17_compat_multi_using_declaration :
730 diag::ext_multi_using_declaration);
733 DeclEnd = Tok.getLocation();
734 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
735 !Attrs.empty() ? "attributes list"
736 : "using declaration"))
737 SkipUntil(tok::semi);
739 return Actions.BuildDeclaratorGroup(DeclsInGroup);
742 Decl *Parser::ParseAliasDeclarationAfterDeclarator(
743 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
744 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
745 ParsedAttributes &Attrs, Decl **OwnedType) {
746 if (ExpectAndConsume(tok::equal)) {
747 SkipUntil(tok::semi);
751 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
752 diag::warn_cxx98_compat_alias_declaration :
753 diag::ext_alias_declaration);
755 // Type alias templates cannot be specialized.
757 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
758 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
760 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
762 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
764 if (SpecKind != -1) {
767 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
768 D.Name.TemplateId->RAngleLoc);
770 Range = TemplateInfo.getSourceRange();
771 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
772 << SpecKind << Range;
773 SkipUntil(tok::semi);
777 // Name must be an identifier.
778 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
779 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
780 // No removal fixit: can't recover from this.
781 SkipUntil(tok::semi);
783 } else if (D.TypenameLoc.isValid())
784 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
785 << FixItHint::CreateRemoval(SourceRange(
787 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
788 else if (D.SS.isNotEmpty())
789 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
790 << FixItHint::CreateRemoval(D.SS.getRange());
791 if (D.EllipsisLoc.isValid())
792 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
793 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
795 Decl *DeclFromDeclSpec = nullptr;
796 TypeResult TypeAlias = ParseTypeName(
798 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
799 : DeclaratorContext::AliasDeclContext,
800 AS, &DeclFromDeclSpec, &Attrs);
802 *OwnedType = DeclFromDeclSpec;
805 DeclEnd = Tok.getLocation();
806 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
807 !Attrs.empty() ? "attributes list"
808 : "alias declaration"))
809 SkipUntil(tok::semi);
811 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
812 MultiTemplateParamsArg TemplateParamsArg(
813 TemplateParams ? TemplateParams->data() : nullptr,
814 TemplateParams ? TemplateParams->size() : 0);
815 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
816 UsingLoc, D.Name, Attrs.getList(),
817 TypeAlias, DeclFromDeclSpec);
820 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
822 /// [C++0x] static_assert-declaration:
823 /// static_assert ( constant-expression , string-literal ) ;
825 /// [C11] static_assert-declaration:
826 /// _Static_assert ( constant-expression , string-literal ) ;
828 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
829 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
830 "Not a static_assert declaration");
832 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
833 Diag(Tok, diag::ext_c11_static_assert);
834 if (Tok.is(tok::kw_static_assert))
835 Diag(Tok, diag::warn_cxx98_compat_static_assert);
837 SourceLocation StaticAssertLoc = ConsumeToken();
839 BalancedDelimiterTracker T(*this, tok::l_paren);
840 if (T.consumeOpen()) {
841 Diag(Tok, diag::err_expected) << tok::l_paren;
846 EnterExpressionEvaluationContext ConstantEvaluated(
847 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
848 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
849 if (AssertExpr.isInvalid()) {
854 ExprResult AssertMessage;
855 if (Tok.is(tok::r_paren)) {
856 Diag(Tok, getLangOpts().CPlusPlus17
857 ? diag::warn_cxx14_compat_static_assert_no_message
858 : diag::ext_static_assert_no_message)
859 << (getLangOpts().CPlusPlus17
861 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
863 if (ExpectAndConsume(tok::comma)) {
864 SkipUntil(tok::semi);
868 if (!isTokenStringLiteral()) {
869 Diag(Tok, diag::err_expected_string_literal)
870 << /*Source='static_assert'*/1;
875 AssertMessage = ParseStringLiteralExpression();
876 if (AssertMessage.isInvalid()) {
884 DeclEnd = Tok.getLocation();
885 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
887 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
890 T.getCloseLocation());
893 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
895 /// 'decltype' ( expression )
896 /// 'decltype' ( 'auto' ) [C++1y]
898 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
899 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
900 && "Not a decltype specifier");
903 SourceLocation StartLoc = Tok.getLocation();
904 SourceLocation EndLoc;
906 if (Tok.is(tok::annot_decltype)) {
907 Result = getExprAnnotation(Tok);
908 EndLoc = Tok.getAnnotationEndLoc();
909 ConsumeAnnotationToken();
910 if (Result.isInvalid()) {
911 DS.SetTypeSpecError();
915 if (Tok.getIdentifierInfo()->isStr("decltype"))
916 Diag(Tok, diag::warn_cxx98_compat_decltype);
920 BalancedDelimiterTracker T(*this, tok::l_paren);
921 if (T.expectAndConsume(diag::err_expected_lparen_after,
922 "decltype", tok::r_paren)) {
923 DS.SetTypeSpecError();
924 return T.getOpenLocation() == Tok.getLocation() ?
925 StartLoc : T.getOpenLocation();
928 // Check for C++1y 'decltype(auto)'.
929 if (Tok.is(tok::kw_auto)) {
930 // No need to disambiguate here: an expression can't start with 'auto',
931 // because the typename-specifier in a function-style cast operation can't
933 Diag(Tok.getLocation(),
934 getLangOpts().CPlusPlus14
935 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
936 : diag::ext_decltype_auto_type_specifier);
939 // Parse the expression
941 // C++11 [dcl.type.simple]p4:
942 // The operand of the decltype specifier is an unevaluated operand.
943 EnterExpressionEvaluationContext Unevaluated(
944 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
945 /*IsDecltype=*/true);
947 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
948 return E->hasPlaceholderType() ? ExprError() : E;
950 if (Result.isInvalid()) {
951 DS.SetTypeSpecError();
952 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
953 EndLoc = ConsumeParen();
955 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
956 // Backtrack to get the location of the last token before the semi.
957 PP.RevertCachedTokens(2);
958 ConsumeToken(); // the semi.
959 EndLoc = ConsumeAnyToken();
960 assert(Tok.is(tok::semi));
962 EndLoc = Tok.getLocation();
968 Result = Actions.ActOnDecltypeExpression(Result.get());
973 if (T.getCloseLocation().isInvalid()) {
974 DS.SetTypeSpecError();
975 // FIXME: this should return the location of the last token
976 // that was consumed (by "consumeClose()")
977 return T.getCloseLocation();
980 if (Result.isInvalid()) {
981 DS.SetTypeSpecError();
982 return T.getCloseLocation();
985 EndLoc = T.getCloseLocation();
987 assert(!Result.isInvalid());
989 const char *PrevSpec = nullptr;
991 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
992 // Check for duplicate type specifiers (e.g. "int decltype(a)").
994 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
995 DiagID, Result.get(), Policy)
996 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
998 Diag(StartLoc, DiagID) << PrevSpec;
999 DS.SetTypeSpecError();
1004 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1005 SourceLocation StartLoc,
1006 SourceLocation EndLoc) {
1007 // make sure we have a token we can turn into an annotation token
1008 if (PP.isBacktrackEnabled())
1009 PP.RevertCachedTokens(1);
1013 Tok.setKind(tok::annot_decltype);
1014 setExprAnnotation(Tok,
1015 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1016 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1018 Tok.setAnnotationEndLoc(EndLoc);
1019 Tok.setLocation(StartLoc);
1020 PP.AnnotateCachedTokens(Tok);
1023 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1024 assert(Tok.is(tok::kw___underlying_type) &&
1025 "Not an underlying type specifier");
1027 SourceLocation StartLoc = ConsumeToken();
1028 BalancedDelimiterTracker T(*this, tok::l_paren);
1029 if (T.expectAndConsume(diag::err_expected_lparen_after,
1030 "__underlying_type", tok::r_paren)) {
1034 TypeResult Result = ParseTypeName();
1035 if (Result.isInvalid()) {
1036 SkipUntil(tok::r_paren, StopAtSemi);
1042 if (T.getCloseLocation().isInvalid())
1045 const char *PrevSpec = nullptr;
1047 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
1048 DiagID, Result.get(),
1049 Actions.getASTContext().getPrintingPolicy()))
1050 Diag(StartLoc, DiagID) << PrevSpec;
1051 DS.setTypeofParensRange(T.getRange());
1054 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1055 /// class name or decltype-specifier. Note that we only check that the result
1056 /// names a type; semantic analysis will need to verify that the type names a
1057 /// class. The result is either a type or null, depending on whether a type
1060 /// base-type-specifier: [C++11 class.derived]
1061 /// class-or-decltype
1062 /// class-or-decltype: [C++11 class.derived]
1063 /// nested-name-specifier[opt] class-name
1064 /// decltype-specifier
1065 /// class-name: [C++ class.name]
1067 /// simple-template-id
1069 /// In C++98, instead of base-type-specifier, we have:
1071 /// ::[opt] nested-name-specifier[opt] class-name
1072 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1073 SourceLocation &EndLocation) {
1074 // Ignore attempts to use typename
1075 if (Tok.is(tok::kw_typename)) {
1076 Diag(Tok, diag::err_expected_class_name_not_template)
1077 << FixItHint::CreateRemoval(Tok.getLocation());
1081 // Parse optional nested-name-specifier
1083 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
1085 BaseLoc = Tok.getLocation();
1087 // Parse decltype-specifier
1088 // tok == kw_decltype is just error recovery, it can only happen when SS
1090 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
1091 if (SS.isNotEmpty())
1092 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1093 << FixItHint::CreateRemoval(SS.getRange());
1094 // Fake up a Declarator to use with ActOnTypeName.
1095 DeclSpec DS(AttrFactory);
1097 EndLocation = ParseDecltypeSpecifier(DS);
1099 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1100 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1103 // Check whether we have a template-id that names a type.
1104 if (Tok.is(tok::annot_template_id)) {
1105 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1106 if (TemplateId->Kind == TNK_Type_template ||
1107 TemplateId->Kind == TNK_Dependent_template_name) {
1108 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1110 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1111 ParsedType Type = getTypeAnnotation(Tok);
1112 EndLocation = Tok.getAnnotationEndLoc();
1113 ConsumeAnnotationToken();
1120 // Fall through to produce an error below.
1123 if (Tok.isNot(tok::identifier)) {
1124 Diag(Tok, diag::err_expected_class_name);
1128 IdentifierInfo *Id = Tok.getIdentifierInfo();
1129 SourceLocation IdLoc = ConsumeToken();
1131 if (Tok.is(tok::less)) {
1132 // It looks the user intended to write a template-id here, but the
1133 // template-name was wrong. Try to fix that.
1134 TemplateNameKind TNK = TNK_Type_template;
1135 TemplateTy Template;
1136 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
1137 &SS, Template, TNK)) {
1138 Diag(IdLoc, diag::err_unknown_template_name)
1143 TemplateArgList TemplateArgs;
1144 SourceLocation LAngleLoc, RAngleLoc;
1145 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1150 // Form the template name
1151 UnqualifiedId TemplateName;
1152 TemplateName.setIdentifier(Id, IdLoc);
1154 // Parse the full template-id, then turn it into a type.
1155 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1158 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1159 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1161 // If we didn't end up with a typename token, there's nothing more we
1163 if (Tok.isNot(tok::annot_typename))
1166 // Retrieve the type from the annotation token, consume that token, and
1168 EndLocation = Tok.getAnnotationEndLoc();
1169 ParsedType Type = getTypeAnnotation(Tok);
1170 ConsumeAnnotationToken();
1174 // We have an identifier; check whether it is actually a type.
1175 IdentifierInfo *CorrectedII = nullptr;
1176 ParsedType Type = Actions.getTypeName(
1177 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
1178 /*IsCtorOrDtorName=*/false,
1179 /*NonTrivialTypeSourceInfo=*/true,
1180 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
1182 Diag(IdLoc, diag::err_expected_class_name);
1186 // Consume the identifier.
1187 EndLocation = IdLoc;
1189 // Fake up a Declarator to use with ActOnTypeName.
1190 DeclSpec DS(AttrFactory);
1191 DS.SetRangeStart(IdLoc);
1192 DS.SetRangeEnd(EndLocation);
1193 DS.getTypeSpecScope() = SS;
1195 const char *PrevSpec = nullptr;
1197 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1198 Actions.getASTContext().getPrintingPolicy());
1200 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1201 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1204 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1205 while (Tok.isOneOf(tok::kw___single_inheritance,
1206 tok::kw___multiple_inheritance,
1207 tok::kw___virtual_inheritance)) {
1208 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1209 SourceLocation AttrNameLoc = ConsumeToken();
1210 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1211 AttributeList::AS_Keyword);
1215 /// Determine whether the following tokens are valid after a type-specifier
1216 /// which could be a standalone declaration. This will conservatively return
1217 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1218 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1219 // This switch enumerates the valid "follow" set for type-specifiers.
1220 switch (Tok.getKind()) {
1222 case tok::semi: // struct foo {...} ;
1223 case tok::star: // struct foo {...} * P;
1224 case tok::amp: // struct foo {...} & R = ...
1225 case tok::ampamp: // struct foo {...} && R = ...
1226 case tok::identifier: // struct foo {...} V ;
1227 case tok::r_paren: //(struct foo {...} ) {4}
1228 case tok::annot_cxxscope: // struct foo {...} a:: b;
1229 case tok::annot_typename: // struct foo {...} a ::b;
1230 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1231 case tok::l_paren: // struct foo {...} ( x);
1232 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1233 case tok::kw_operator: // struct foo operator ++() {...}
1234 case tok::kw___declspec: // struct foo {...} __declspec(...)
1235 case tok::l_square: // void f(struct f [ 3])
1236 case tok::ellipsis: // void f(struct f ... [Ns])
1237 // FIXME: we should emit semantic diagnostic when declaration
1238 // attribute is in type attribute position.
1239 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1240 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1241 // struct foo {...} _Pragma(section(...));
1242 case tok::annot_pragma_ms_pragma:
1243 // struct foo {...} _Pragma(vtordisp(pop));
1244 case tok::annot_pragma_ms_vtordisp:
1245 // struct foo {...} _Pragma(pointers_to_members(...));
1246 case tok::annot_pragma_ms_pointers_to_members:
1249 return CouldBeBitfield; // enum E { ... } : 2;
1250 // Microsoft compatibility
1251 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1252 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1253 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1254 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1255 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1256 // We will diagnose these calling-convention specifiers on non-function
1257 // declarations later, so claim they are valid after a type specifier.
1258 return getLangOpts().MicrosoftExt;
1260 case tok::kw_const: // struct foo {...} const x;
1261 case tok::kw_volatile: // struct foo {...} volatile x;
1262 case tok::kw_restrict: // struct foo {...} restrict x;
1263 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1264 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1265 // Function specifiers
1266 // Note, no 'explicit'. An explicit function must be either a conversion
1267 // operator or a constructor. Either way, it can't have a return type.
1268 case tok::kw_inline: // struct foo inline f();
1269 case tok::kw_virtual: // struct foo virtual f();
1270 case tok::kw_friend: // struct foo friend f();
1271 // Storage-class specifiers
1272 case tok::kw_static: // struct foo {...} static x;
1273 case tok::kw_extern: // struct foo {...} extern x;
1274 case tok::kw_typedef: // struct foo {...} typedef x;
1275 case tok::kw_register: // struct foo {...} register x;
1276 case tok::kw_auto: // struct foo {...} auto x;
1277 case tok::kw_mutable: // struct foo {...} mutable x;
1278 case tok::kw_thread_local: // struct foo {...} thread_local x;
1279 case tok::kw_constexpr: // struct foo {...} constexpr x;
1280 // As shown above, type qualifiers and storage class specifiers absolutely
1281 // can occur after class specifiers according to the grammar. However,
1282 // almost no one actually writes code like this. If we see one of these,
1283 // it is much more likely that someone missed a semi colon and the
1284 // type/storage class specifier we're seeing is part of the *next*
1285 // intended declaration, as in:
1287 // struct foo { ... }
1290 // We'd really like to emit a missing semicolon error instead of emitting
1291 // an error on the 'int' saying that you can't have two type specifiers in
1292 // the same declaration of X. Because of this, we look ahead past this
1293 // token to see if it's a type specifier. If so, we know the code is
1294 // otherwise invalid, so we can produce the expected semi error.
1295 if (!isKnownToBeTypeSpecifier(NextToken()))
1298 case tok::r_brace: // struct bar { struct foo {...} }
1299 // Missing ';' at end of struct is accepted as an extension in C mode.
1300 if (!getLangOpts().CPlusPlus)
1304 // template<class T = class X>
1305 return getLangOpts().CPlusPlus;
1310 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1311 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1312 /// until we reach the start of a definition or see a token that
1313 /// cannot start a definition.
1315 /// class-specifier: [C++ class]
1316 /// class-head '{' member-specification[opt] '}'
1317 /// class-head '{' member-specification[opt] '}' attributes[opt]
1319 /// class-key identifier[opt] base-clause[opt]
1320 /// class-key nested-name-specifier identifier base-clause[opt]
1321 /// class-key nested-name-specifier[opt] simple-template-id
1322 /// base-clause[opt]
1323 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1324 /// [GNU] class-key attributes[opt] nested-name-specifier
1325 /// identifier base-clause[opt]
1326 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1327 /// simple-template-id base-clause[opt]
1333 /// elaborated-type-specifier: [C++ dcl.type.elab]
1334 /// class-key ::[opt] nested-name-specifier[opt] identifier
1335 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1336 /// simple-template-id
1338 /// Note that the C++ class-specifier and elaborated-type-specifier,
1339 /// together, subsume the C99 struct-or-union-specifier:
1341 /// struct-or-union-specifier: [C99 6.7.2.1]
1342 /// struct-or-union identifier[opt] '{' struct-contents '}'
1343 /// struct-or-union identifier
1344 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1345 /// '}' attributes[opt]
1346 /// [GNU] struct-or-union attributes[opt] identifier
1347 /// struct-or-union:
1350 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1351 SourceLocation StartLoc, DeclSpec &DS,
1352 const ParsedTemplateInfo &TemplateInfo,
1354 bool EnteringContext, DeclSpecContext DSC,
1355 ParsedAttributesWithRange &Attributes) {
1356 DeclSpec::TST TagType;
1357 if (TagTokKind == tok::kw_struct)
1358 TagType = DeclSpec::TST_struct;
1359 else if (TagTokKind == tok::kw___interface)
1360 TagType = DeclSpec::TST_interface;
1361 else if (TagTokKind == tok::kw_class)
1362 TagType = DeclSpec::TST_class;
1364 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1365 TagType = DeclSpec::TST_union;
1368 if (Tok.is(tok::code_completion)) {
1369 // Code completion for a struct, class, or union name.
1370 Actions.CodeCompleteTag(getCurScope(), TagType);
1371 return cutOffParsing();
1374 // C++03 [temp.explicit] 14.7.2/8:
1375 // The usual access checking rules do not apply to names used to specify
1376 // explicit instantiations.
1378 // As an extension we do not perform access checking on the names used to
1379 // specify explicit specializations either. This is important to allow
1380 // specializing traits classes for private types.
1382 // Note that we don't suppress if this turns out to be an elaborated
1384 bool shouldDelayDiagsInTag =
1385 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1386 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1387 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1389 ParsedAttributesWithRange attrs(AttrFactory);
1390 // If attributes exist after tag, parse them.
1391 MaybeParseGNUAttributes(attrs);
1392 MaybeParseMicrosoftDeclSpecs(attrs);
1394 // Parse inheritance specifiers.
1395 if (Tok.isOneOf(tok::kw___single_inheritance,
1396 tok::kw___multiple_inheritance,
1397 tok::kw___virtual_inheritance))
1398 ParseMicrosoftInheritanceClassAttributes(attrs);
1400 // If C++0x attributes exist here, parse them.
1401 // FIXME: Are we consistent with the ordering of parsing of different
1402 // styles of attributes?
1403 MaybeParseCXX11Attributes(attrs);
1405 // Source location used by FIXIT to insert misplaced
1407 SourceLocation AttrFixitLoc = Tok.getLocation();
1409 if (TagType == DeclSpec::TST_struct &&
1410 Tok.isNot(tok::identifier) &&
1411 !Tok.isAnnotation() &&
1412 Tok.getIdentifierInfo() &&
1413 Tok.isOneOf(tok::kw___is_abstract,
1414 tok::kw___is_aggregate,
1415 tok::kw___is_arithmetic,
1417 tok::kw___is_assignable,
1418 tok::kw___is_base_of,
1420 tok::kw___is_complete_type,
1421 tok::kw___is_compound,
1423 tok::kw___is_constructible,
1424 tok::kw___is_convertible,
1425 tok::kw___is_convertible_to,
1426 tok::kw___is_destructible,
1429 tok::kw___is_floating_point,
1431 tok::kw___is_function,
1432 tok::kw___is_fundamental,
1433 tok::kw___is_integral,
1434 tok::kw___is_interface_class,
1435 tok::kw___is_literal,
1436 tok::kw___is_lvalue_expr,
1437 tok::kw___is_lvalue_reference,
1438 tok::kw___is_member_function_pointer,
1439 tok::kw___is_member_object_pointer,
1440 tok::kw___is_member_pointer,
1441 tok::kw___is_nothrow_assignable,
1442 tok::kw___is_nothrow_constructible,
1443 tok::kw___is_nothrow_destructible,
1444 tok::kw___is_object,
1446 tok::kw___is_pointer,
1447 tok::kw___is_polymorphic,
1448 tok::kw___is_reference,
1449 tok::kw___is_rvalue_expr,
1450 tok::kw___is_rvalue_reference,
1452 tok::kw___is_scalar,
1453 tok::kw___is_sealed,
1454 tok::kw___is_signed,
1455 tok::kw___is_standard_layout,
1456 tok::kw___is_trivial,
1457 tok::kw___is_trivially_assignable,
1458 tok::kw___is_trivially_constructible,
1459 tok::kw___is_trivially_copyable,
1461 tok::kw___is_unsigned,
1463 tok::kw___is_volatile))
1464 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1465 // name of struct templates, but some are keywords in GCC >= 4.3
1466 // and Clang. Therefore, when we see the token sequence "struct
1467 // X", make X into a normal identifier rather than a keyword, to
1468 // allow libstdc++ 4.2 and libc++ to work properly.
1469 TryKeywordIdentFallback(true);
1471 struct PreserveAtomicIdentifierInfoRAII {
1472 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1473 : AtomicII(nullptr) {
1476 assert(Tok.is(tok::kw__Atomic));
1477 AtomicII = Tok.getIdentifierInfo();
1478 AtomicII->revertTokenIDToIdentifier();
1479 Tok.setKind(tok::identifier);
1481 ~PreserveAtomicIdentifierInfoRAII() {
1484 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1486 IdentifierInfo *AtomicII;
1489 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1490 // implementation for VS2013 uses _Atomic as an identifier for one of the
1491 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1492 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1493 // use '_Atomic' in its own header files.
1494 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1495 Tok.is(tok::kw__Atomic) &&
1496 TagType == DeclSpec::TST_struct;
1497 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1498 Tok, ShouldChangeAtomicToIdentifier);
1500 // Parse the (optional) nested-name-specifier.
1501 CXXScopeSpec &SS = DS.getTypeSpecScope();
1502 if (getLangOpts().CPlusPlus) {
1503 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1504 // is a base-specifier-list.
1505 ColonProtectionRAIIObject X(*this);
1508 bool HasValidSpec = true;
1509 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
1510 DS.SetTypeSpecError();
1511 HasValidSpec = false;
1514 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1515 Diag(Tok, diag::err_expected) << tok::identifier;
1516 HasValidSpec = false;
1522 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1524 // Parse the (optional) class name or simple-template-id.
1525 IdentifierInfo *Name = nullptr;
1526 SourceLocation NameLoc;
1527 TemplateIdAnnotation *TemplateId = nullptr;
1528 if (Tok.is(tok::identifier)) {
1529 Name = Tok.getIdentifierInfo();
1530 NameLoc = ConsumeToken();
1532 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1533 // The name was supposed to refer to a template, but didn't.
1534 // Eat the template argument list and try to continue parsing this as
1535 // a class (or template thereof).
1536 TemplateArgList TemplateArgs;
1537 SourceLocation LAngleLoc, RAngleLoc;
1538 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1540 // We couldn't parse the template argument list at all, so don't
1541 // try to give any location information for the list.
1542 LAngleLoc = RAngleLoc = SourceLocation();
1545 Diag(NameLoc, diag::err_explicit_spec_non_template)
1546 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1547 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1549 // Strip off the last template parameter list if it was empty, since
1550 // we've removed its template argument list.
1551 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1552 if (TemplateParams->size() > 1) {
1553 TemplateParams->pop_back();
1555 TemplateParams = nullptr;
1556 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1557 = ParsedTemplateInfo::NonTemplate;
1559 } else if (TemplateInfo.Kind
1560 == ParsedTemplateInfo::ExplicitInstantiation) {
1561 // Pretend this is just a forward declaration.
1562 TemplateParams = nullptr;
1563 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1564 = ParsedTemplateInfo::NonTemplate;
1565 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1567 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1571 } else if (Tok.is(tok::annot_template_id)) {
1572 TemplateId = takeTemplateIdAnnotation(Tok);
1573 NameLoc = ConsumeAnnotationToken();
1575 if (TemplateId->Kind != TNK_Type_template &&
1576 TemplateId->Kind != TNK_Dependent_template_name) {
1577 // The template-name in the simple-template-id refers to
1578 // something other than a class template. Give an appropriate
1579 // error message and skip to the ';'.
1580 SourceRange Range(NameLoc);
1581 if (SS.isNotEmpty())
1582 Range.setBegin(SS.getBeginLoc());
1584 // FIXME: Name may be null here.
1585 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1586 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1588 DS.SetTypeSpecError();
1589 SkipUntil(tok::semi, StopBeforeMatch);
1594 // There are four options here.
1595 // - If we are in a trailing return type, this is always just a reference,
1596 // and we must not try to parse a definition. For instance,
1597 // [] () -> struct S { };
1598 // does not define a type.
1599 // - If we have 'struct foo {...', 'struct foo :...',
1600 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1601 // - If we have 'struct foo;', then this is either a forward declaration
1602 // or a friend declaration, which have to be treated differently.
1603 // - Otherwise we have something like 'struct foo xyz', a reference.
1605 // We also detect these erroneous cases to provide better diagnostic for
1606 // C++11 attributes parsing.
1607 // - attributes follow class name:
1608 // struct foo [[]] {};
1609 // - attributes appear before or after 'final':
1610 // struct foo [[]] final [[]] {};
1612 // However, in type-specifier-seq's, things look like declarations but are
1613 // just references, e.g.
1616 // &T::operator struct s;
1617 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1618 // DeclSpecContext::DSC_alias_declaration.
1620 // If there are attributes after class name, parse them.
1621 MaybeParseCXX11Attributes(Attributes);
1623 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1624 Sema::TagUseKind TUK;
1625 if (DSC == DeclSpecContext::DSC_trailing)
1626 TUK = Sema::TUK_Reference;
1627 else if (Tok.is(tok::l_brace) ||
1628 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1629 (isCXX11FinalKeyword() &&
1630 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1631 if (DS.isFriendSpecified()) {
1632 // C++ [class.friend]p2:
1633 // A class shall not be defined in a friend declaration.
1634 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1635 << SourceRange(DS.getFriendSpecLoc());
1637 // Skip everything up to the semicolon, so that this looks like a proper
1638 // friend class (or template thereof) declaration.
1639 SkipUntil(tok::semi, StopBeforeMatch);
1640 TUK = Sema::TUK_Friend;
1642 // Okay, this is a class definition.
1643 TUK = Sema::TUK_Definition;
1645 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1646 NextToken().is(tok::kw_alignas))) {
1647 // We can't tell if this is a definition or reference
1648 // until we skipped the 'final' and C++11 attribute specifiers.
1649 TentativeParsingAction PA(*this);
1651 // Skip the 'final' keyword.
1654 // Skip C++11 attribute specifiers.
1656 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1658 if (!SkipUntil(tok::r_square, StopAtSemi))
1660 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1663 if (!SkipUntil(tok::r_paren, StopAtSemi))
1670 if (Tok.isOneOf(tok::l_brace, tok::colon))
1671 TUK = Sema::TUK_Definition;
1673 TUK = Sema::TUK_Reference;
1676 } else if (!isTypeSpecifier(DSC) &&
1677 (Tok.is(tok::semi) ||
1678 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1679 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1680 if (Tok.isNot(tok::semi)) {
1681 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1682 // A semicolon was missing after this declaration. Diagnose and recover.
1683 ExpectAndConsume(tok::semi, diag::err_expected_after,
1684 DeclSpec::getSpecifierName(TagType, PPol));
1686 Tok.setKind(tok::semi);
1689 TUK = Sema::TUK_Reference;
1691 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1692 // to caller to handle.
1693 if (TUK != Sema::TUK_Reference) {
1694 // If this is not a reference, then the only possible
1695 // valid place for C++11 attributes to appear here
1696 // is between class-key and class-name. If there are
1697 // any attributes after class-name, we try a fixit to move
1698 // them to the right place.
1699 SourceRange AttrRange = Attributes.Range;
1700 if (AttrRange.isValid()) {
1701 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1703 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1704 CharSourceRange(AttrRange, true))
1705 << FixItHint::CreateRemoval(AttrRange);
1707 // Recover by adding misplaced attributes to the attribute list
1708 // of the class so they can be applied on the class later.
1709 attrs.takeAllFrom(Attributes);
1713 // If this is an elaborated type specifier, and we delayed
1714 // diagnostics before, just merge them into the current pool.
1715 if (shouldDelayDiagsInTag) {
1716 diagsFromTag.done();
1717 if (TUK == Sema::TUK_Reference)
1718 diagsFromTag.redelay();
1721 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1722 TUK != Sema::TUK_Definition)) {
1723 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1724 // We have a declaration or reference to an anonymous class.
1725 Diag(StartLoc, diag::err_anon_type_definition)
1726 << DeclSpec::getSpecifierName(TagType, Policy);
1729 // If we are parsing a definition and stop at a base-clause, continue on
1730 // until the semicolon. Continuing from the comma will just trick us into
1731 // thinking we are seeing a variable declaration.
1732 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1733 SkipUntil(tok::semi, StopBeforeMatch);
1735 SkipUntil(tok::comma, StopAtSemi);
1739 // Create the tag portion of the class or class template.
1740 DeclResult TagOrTempResult = true; // invalid
1741 TypeResult TypeResult = true; // invalid
1744 Sema::SkipBodyInfo SkipBody;
1746 // Explicit specialization, class template partial specialization,
1747 // or explicit instantiation.
1748 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1749 TemplateId->NumArgs);
1750 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1751 TUK == Sema::TUK_Declaration) {
1752 // This is an explicit instantiation of a class template.
1753 ProhibitAttributes(attrs);
1756 = Actions.ActOnExplicitInstantiation(getCurScope(),
1757 TemplateInfo.ExternLoc,
1758 TemplateInfo.TemplateLoc,
1762 TemplateId->Template,
1763 TemplateId->TemplateNameLoc,
1764 TemplateId->LAngleLoc,
1766 TemplateId->RAngleLoc,
1769 // Friend template-ids are treated as references unless
1770 // they have template headers, in which case they're ill-formed
1771 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1772 // We diagnose this error in ActOnClassTemplateSpecialization.
1773 } else if (TUK == Sema::TUK_Reference ||
1774 (TUK == Sema::TUK_Friend &&
1775 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1776 ProhibitAttributes(attrs);
1777 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1779 TemplateId->TemplateKWLoc,
1780 TemplateId->Template,
1781 TemplateId->TemplateNameLoc,
1782 TemplateId->LAngleLoc,
1784 TemplateId->RAngleLoc);
1786 // This is an explicit specialization or a class template
1787 // partial specialization.
1788 TemplateParameterLists FakedParamLists;
1789 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1790 // This looks like an explicit instantiation, because we have
1793 // template class Foo<X>
1795 // but it actually has a definition. Most likely, this was
1796 // meant to be an explicit specialization, but the user forgot
1797 // the '<>' after 'template'.
1798 // It this is friend declaration however, since it cannot have a
1799 // template header, it is most likely that the user meant to
1800 // remove the 'template' keyword.
1801 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1802 "Expected a definition here");
1804 if (TUK == Sema::TUK_Friend) {
1805 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1806 TemplateParams = nullptr;
1808 SourceLocation LAngleLoc =
1809 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1810 Diag(TemplateId->TemplateNameLoc,
1811 diag::err_explicit_instantiation_with_definition)
1812 << SourceRange(TemplateInfo.TemplateLoc)
1813 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1815 // Create a fake template parameter list that contains only
1816 // "template<>", so that we treat this construct as a class
1817 // template specialization.
1818 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1819 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1820 LAngleLoc, nullptr));
1821 TemplateParams = &FakedParamLists;
1825 // Build the class template specialization.
1826 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1827 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1828 *TemplateId, attrs.getList(),
1829 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1831 TemplateParams ? TemplateParams->size() : 0),
1834 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1835 TUK == Sema::TUK_Declaration) {
1836 // Explicit instantiation of a member of a class template
1837 // specialization, e.g.,
1839 // template struct Outer<int>::Inner;
1841 ProhibitAttributes(attrs);
1844 = Actions.ActOnExplicitInstantiation(getCurScope(),
1845 TemplateInfo.ExternLoc,
1846 TemplateInfo.TemplateLoc,
1847 TagType, StartLoc, SS, Name,
1848 NameLoc, attrs.getList());
1849 } else if (TUK == Sema::TUK_Friend &&
1850 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1851 ProhibitAttributes(attrs);
1854 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1855 TagType, StartLoc, SS,
1856 Name, NameLoc, attrs.getList(),
1857 MultiTemplateParamsArg(
1858 TemplateParams? &(*TemplateParams)[0]
1860 TemplateParams? TemplateParams->size() : 0));
1862 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1863 ProhibitAttributes(attrs);
1865 if (TUK == Sema::TUK_Definition &&
1866 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1867 // If the declarator-id is not a template-id, issue a diagnostic and
1868 // recover by ignoring the 'template' keyword.
1869 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1870 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1871 TemplateParams = nullptr;
1874 bool IsDependent = false;
1876 // Don't pass down template parameter lists if this is just a tag
1877 // reference. For example, we don't need the template parameters here:
1878 // template <class T> class A *makeA(T t);
1879 MultiTemplateParamsArg TParams;
1880 if (TUK != Sema::TUK_Reference && TemplateParams)
1882 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1884 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
1886 // Declaration or definition of a class type
1887 TagOrTempResult = Actions.ActOnTag(
1888 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc,
1889 attrs.getList(), AS, DS.getModulePrivateSpecLoc(), TParams, Owned,
1890 IsDependent, SourceLocation(), false, clang::TypeResult(),
1891 DSC == DeclSpecContext::DSC_type_specifier,
1892 DSC == DeclSpecContext::DSC_template_param ||
1893 DSC == DeclSpecContext::DSC_template_type_arg,
1896 // If ActOnTag said the type was dependent, try again with the
1897 // less common call.
1899 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1900 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1901 SS, Name, StartLoc, NameLoc);
1905 // If there is a body, parse it and inform the actions module.
1906 if (TUK == Sema::TUK_Definition) {
1907 assert(Tok.is(tok::l_brace) ||
1908 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1909 isCXX11FinalKeyword());
1910 if (SkipBody.ShouldSkip)
1911 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1912 TagOrTempResult.get());
1913 else if (getLangOpts().CPlusPlus)
1914 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1915 TagOrTempResult.get());
1918 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1919 // Parse the definition body.
1920 ParseStructUnionBody(StartLoc, TagType, D);
1921 if (SkipBody.CheckSameAsPrevious &&
1922 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1924 DS.SetTypeSpecError();
1930 if (!TagOrTempResult.isInvalid())
1931 // Delayed processing of attributes.
1932 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1934 const char *PrevSpec = nullptr;
1937 if (!TypeResult.isInvalid()) {
1938 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1939 NameLoc.isValid() ? NameLoc : StartLoc,
1940 PrevSpec, DiagID, TypeResult.get(), Policy);
1941 } else if (!TagOrTempResult.isInvalid()) {
1942 Result = DS.SetTypeSpecType(TagType, StartLoc,
1943 NameLoc.isValid() ? NameLoc : StartLoc,
1944 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1947 DS.SetTypeSpecError();
1952 Diag(StartLoc, DiagID) << PrevSpec;
1954 // At this point, we've successfully parsed a class-specifier in 'definition'
1955 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1956 // going to look at what comes after it to improve error recovery. If an
1957 // impossible token occurs next, we assume that the programmer forgot a ; at
1958 // the end of the declaration and recover that way.
1960 // Also enforce C++ [temp]p3:
1961 // In a template-declaration which defines a class, no declarator
1964 // After a type-specifier, we don't expect a semicolon. This only happens in
1965 // C, since definitions are not permitted in this context in C++.
1966 if (TUK == Sema::TUK_Definition &&
1967 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1968 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1969 if (Tok.isNot(tok::semi)) {
1970 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1971 ExpectAndConsume(tok::semi, diag::err_expected_after,
1972 DeclSpec::getSpecifierName(TagType, PPol));
1973 // Push this token back into the preprocessor and change our current token
1974 // to ';' so that the rest of the code recovers as though there were an
1975 // ';' after the definition.
1977 Tok.setKind(tok::semi);
1982 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1984 /// base-clause : [C++ class.derived]
1985 /// ':' base-specifier-list
1986 /// base-specifier-list:
1987 /// base-specifier '...'[opt]
1988 /// base-specifier-list ',' base-specifier '...'[opt]
1989 void Parser::ParseBaseClause(Decl *ClassDecl) {
1990 assert(Tok.is(tok::colon) && "Not a base clause");
1993 // Build up an array of parsed base specifiers.
1994 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1997 // Parse a base-specifier.
1998 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1999 if (Result.isInvalid()) {
2000 // Skip the rest of this base specifier, up until the comma or
2002 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2004 // Add this to our array of base specifiers.
2005 BaseInfo.push_back(Result.get());
2008 // If the next token is a comma, consume it and keep reading
2010 if (!TryConsumeToken(tok::comma))
2014 // Attach the base specifiers
2015 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2018 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2019 /// one entry in the base class list of a class specifier, for example:
2020 /// class foo : public bar, virtual private baz {
2021 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2023 /// base-specifier: [C++ class.derived]
2024 /// attribute-specifier-seq[opt] base-type-specifier
2025 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2026 /// base-type-specifier
2027 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2028 /// base-type-specifier
2029 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2030 bool IsVirtual = false;
2031 SourceLocation StartLoc = Tok.getLocation();
2033 ParsedAttributesWithRange Attributes(AttrFactory);
2034 MaybeParseCXX11Attributes(Attributes);
2036 // Parse the 'virtual' keyword.
2037 if (TryConsumeToken(tok::kw_virtual))
2040 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2042 // Parse an (optional) access specifier.
2043 AccessSpecifier Access = getAccessSpecifierIfPresent();
2044 if (Access != AS_none)
2047 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2049 // Parse the 'virtual' keyword (again!), in case it came after the
2050 // access specifier.
2051 if (Tok.is(tok::kw_virtual)) {
2052 SourceLocation VirtualLoc = ConsumeToken();
2054 // Complain about duplicate 'virtual'
2055 Diag(VirtualLoc, diag::err_dup_virtual)
2056 << FixItHint::CreateRemoval(VirtualLoc);
2062 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2064 // Parse the class-name.
2066 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2067 // implementation for VS2013 uses _Atomic as an identifier for one of the
2068 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2069 // parsing the class-name for a base specifier.
2070 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2071 NextToken().is(tok::less))
2072 Tok.setKind(tok::identifier);
2074 SourceLocation EndLocation;
2075 SourceLocation BaseLoc;
2076 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2077 if (BaseType.isInvalid())
2080 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2081 // actually part of the base-specifier-list grammar productions, but we
2082 // parse it here for convenience.
2083 SourceLocation EllipsisLoc;
2084 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2086 // Find the complete source range for the base-specifier.
2087 SourceRange Range(StartLoc, EndLocation);
2089 // Notify semantic analysis that we have parsed a complete
2091 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2092 Access, BaseType.get(), BaseLoc,
2096 /// getAccessSpecifierIfPresent - Determine whether the next token is
2097 /// a C++ access-specifier.
2099 /// access-specifier: [C++ class.derived]
2103 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2104 switch (Tok.getKind()) {
2105 default: return AS_none;
2106 case tok::kw_private: return AS_private;
2107 case tok::kw_protected: return AS_protected;
2108 case tok::kw_public: return AS_public;
2112 /// \brief If the given declarator has any parts for which parsing has to be
2113 /// delayed, e.g., default arguments or an exception-specification, create a
2114 /// late-parsed method declaration record to handle the parsing at the end of
2115 /// the class definition.
2116 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2118 DeclaratorChunk::FunctionTypeInfo &FTI
2119 = DeclaratorInfo.getFunctionTypeInfo();
2120 // If there was a late-parsed exception-specification, we'll need a
2122 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2124 if (!NeedLateParse) {
2125 // Look ahead to see if there are any default args
2126 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2127 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2128 if (Param->hasUnparsedDefaultArg()) {
2129 NeedLateParse = true;
2135 if (NeedLateParse) {
2136 // Push this method onto the stack of late-parsed method
2138 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2139 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2140 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2142 // Stash the exception-specification tokens in the late-pased method.
2143 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2144 FTI.ExceptionSpecTokens = nullptr;
2146 // Push tokens for each parameter. Those that do not have
2147 // defaults will be NULL.
2148 LateMethod->DefaultArgs.reserve(FTI.NumParams);
2149 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2150 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2151 FTI.Params[ParamIdx].Param,
2152 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2156 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2163 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2164 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2165 return VirtSpecifiers::VS_None;
2167 IdentifierInfo *II = Tok.getIdentifierInfo();
2169 // Initialize the contextual keywords.
2171 Ident_final = &PP.getIdentifierTable().get("final");
2172 if (getLangOpts().GNUKeywords)
2173 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2174 if (getLangOpts().MicrosoftExt)
2175 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2176 Ident_override = &PP.getIdentifierTable().get("override");
2179 if (II == Ident_override)
2180 return VirtSpecifiers::VS_Override;
2182 if (II == Ident_sealed)
2183 return VirtSpecifiers::VS_Sealed;
2185 if (II == Ident_final)
2186 return VirtSpecifiers::VS_Final;
2188 if (II == Ident_GNU_final)
2189 return VirtSpecifiers::VS_GNU_Final;
2191 return VirtSpecifiers::VS_None;
2194 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2196 /// virt-specifier-seq:
2198 /// virt-specifier-seq virt-specifier
2199 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2201 SourceLocation FriendLoc) {
2203 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2204 if (Specifier == VirtSpecifiers::VS_None)
2207 if (FriendLoc.isValid()) {
2208 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2209 << VirtSpecifiers::getSpecifierName(Specifier)
2210 << FixItHint::CreateRemoval(Tok.getLocation())
2211 << SourceRange(FriendLoc, FriendLoc);
2216 // C++ [class.mem]p8:
2217 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2218 const char *PrevSpec = nullptr;
2219 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2220 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2222 << FixItHint::CreateRemoval(Tok.getLocation());
2224 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2225 Specifier == VirtSpecifiers::VS_Sealed)) {
2226 Diag(Tok.getLocation(), diag::err_override_control_interface)
2227 << VirtSpecifiers::getSpecifierName(Specifier);
2228 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2229 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2230 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2231 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2233 Diag(Tok.getLocation(),
2234 getLangOpts().CPlusPlus11
2235 ? diag::warn_cxx98_compat_override_control_keyword
2236 : diag::ext_override_control_keyword)
2237 << VirtSpecifiers::getSpecifierName(Specifier);
2243 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2244 /// 'final' or Microsoft 'sealed' contextual keyword.
2245 bool Parser::isCXX11FinalKeyword() const {
2246 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2247 return Specifier == VirtSpecifiers::VS_Final ||
2248 Specifier == VirtSpecifiers::VS_GNU_Final ||
2249 Specifier == VirtSpecifiers::VS_Sealed;
2252 /// \brief Parse a C++ member-declarator up to, but not including, the optional
2253 /// brace-or-equal-initializer or pure-specifier.
2254 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2255 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2256 LateParsedAttrList &LateParsedAttrs) {
2257 // member-declarator:
2258 // declarator pure-specifier[opt]
2259 // declarator brace-or-equal-initializer[opt]
2260 // identifier[opt] ':' constant-expression
2261 if (Tok.isNot(tok::colon))
2262 ParseDeclarator(DeclaratorInfo);
2264 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2266 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2267 assert(DeclaratorInfo.isPastIdentifier() &&
2268 "don't know where identifier would go yet?");
2269 BitfieldSize = ParseConstantExpression();
2270 if (BitfieldSize.isInvalid())
2271 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2273 ParseOptionalCXX11VirtSpecifierSeq(
2274 VS, getCurrentClass().IsInterface,
2275 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2277 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2280 // If a simple-asm-expr is present, parse it.
2281 if (Tok.is(tok::kw_asm)) {
2283 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2284 if (AsmLabel.isInvalid())
2285 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2287 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2288 DeclaratorInfo.SetRangeEnd(Loc);
2291 // If attributes exist after the declarator, but before an '{', parse them.
2292 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2294 // For compatibility with code written to older Clang, also accept a
2295 // virt-specifier *after* the GNU attributes.
2296 if (BitfieldSize.isUnset() && VS.isUnset()) {
2297 ParseOptionalCXX11VirtSpecifierSeq(
2298 VS, getCurrentClass().IsInterface,
2299 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2300 if (!VS.isUnset()) {
2301 // If we saw any GNU-style attributes that are known to GCC followed by a
2302 // virt-specifier, issue a GCC-compat warning.
2303 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2305 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2306 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2307 Attr = Attr->getNext();
2309 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2313 // If this has neither a name nor a bit width, something has gone seriously
2314 // wrong. Skip until the semi-colon or }.
2315 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2316 // If so, skip until the semi-colon or a }.
2317 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2323 /// \brief Look for declaration specifiers possibly occurring after C++11
2324 /// virt-specifier-seq and diagnose them.
2325 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2327 VirtSpecifiers &VS) {
2328 DeclSpec DS(AttrFactory);
2330 // GNU-style and C++11 attributes are not allowed here, but they will be
2331 // handled by the caller. Diagnose everything else.
2332 ParseTypeQualifierListOpt(
2333 DS, AR_NoAttributesParsed, false,
2334 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2335 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2337 D.ExtendWithDeclSpec(DS);
2339 if (D.isFunctionDeclarator()) {
2340 auto &Function = D.getFunctionTypeInfo();
2341 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2342 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2343 const char *FixItName,
2344 SourceLocation SpecLoc,
2345 unsigned* QualifierLoc) {
2346 FixItHint Insertion;
2347 if (DS.getTypeQualifiers() & TypeQual) {
2348 if (!(Function.TypeQuals & TypeQual)) {
2349 std::string Name(FixItName);
2351 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2352 Function.TypeQuals |= TypeQual;
2353 *QualifierLoc = SpecLoc.getRawEncoding();
2355 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2357 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2358 << FixItHint::CreateRemoval(SpecLoc)
2362 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2363 &Function.ConstQualifierLoc);
2364 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2365 &Function.VolatileQualifierLoc);
2366 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2367 &Function.RestrictQualifierLoc);
2370 // Parse ref-qualifiers.
2371 bool RefQualifierIsLValueRef = true;
2372 SourceLocation RefQualifierLoc;
2373 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2374 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2375 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2376 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2377 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2379 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2380 << (RefQualifierIsLValueRef ? "&" : "&&")
2381 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2382 << FixItHint::CreateRemoval(RefQualifierLoc)
2384 D.SetRangeEnd(RefQualifierLoc);
2389 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2391 /// member-declaration:
2392 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2393 /// function-definition ';'[opt]
2394 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2395 /// using-declaration [TODO]
2396 /// [C++0x] static_assert-declaration
2397 /// template-declaration
2398 /// [GNU] '__extension__' member-declaration
2400 /// member-declarator-list:
2401 /// member-declarator
2402 /// member-declarator-list ',' member-declarator
2404 /// member-declarator:
2405 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2406 /// declarator constant-initializer[opt]
2407 /// [C++11] declarator brace-or-equal-initializer[opt]
2408 /// identifier[opt] ':' constant-expression
2410 /// virt-specifier-seq:
2412 /// virt-specifier-seq virt-specifier
2422 /// constant-initializer:
2423 /// '=' constant-expression
2425 Parser::DeclGroupPtrTy
2426 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2427 AttributeList *AccessAttrs,
2428 const ParsedTemplateInfo &TemplateInfo,
2429 ParsingDeclRAIIObject *TemplateDiags) {
2430 if (Tok.is(tok::at)) {
2431 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2432 Diag(Tok, diag::err_at_defs_cxx);
2434 Diag(Tok, diag::err_at_in_class);
2437 SkipUntil(tok::r_brace, StopAtSemi);
2441 // Turn on colon protection early, while parsing declspec, although there is
2442 // nothing to protect there. It prevents from false errors if error recovery
2443 // incorrectly determines where the declspec ends, as in the example:
2444 // struct A { enum class B { C }; };
2446 // struct D { A::B : C; };
2447 ColonProtectionRAIIObject X(*this);
2449 // Access declarations.
2450 bool MalformedTypeSpec = false;
2451 if (!TemplateInfo.Kind &&
2452 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2453 if (TryAnnotateCXXScopeToken())
2454 MalformedTypeSpec = true;
2457 if (Tok.isNot(tok::annot_cxxscope))
2458 isAccessDecl = false;
2459 else if (NextToken().is(tok::identifier))
2460 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2462 isAccessDecl = NextToken().is(tok::kw_operator);
2465 // Collect the scope specifier token we annotated earlier.
2467 ParseOptionalCXXScopeSpecifier(SS, nullptr,
2468 /*EnteringContext=*/false);
2470 if (SS.isInvalid()) {
2471 SkipUntil(tok::semi);
2475 // Try to parse an unqualified-id.
2476 SourceLocation TemplateKWLoc;
2478 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2479 TemplateKWLoc, Name)) {
2480 SkipUntil(tok::semi);
2484 // TODO: recover from mistakenly-qualified operator declarations.
2485 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2486 "access declaration")) {
2487 SkipUntil(tok::semi);
2491 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2492 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2493 /*TypenameLoc*/ SourceLocation(), SS, Name,
2494 /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
2498 // static_assert-declaration. A templated static_assert declaration is
2499 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2500 if (!TemplateInfo.Kind &&
2501 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2502 SourceLocation DeclEnd;
2503 return DeclGroupPtrTy::make(
2504 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2507 if (Tok.is(tok::kw_template)) {
2508 assert(!TemplateInfo.TemplateParams &&
2509 "Nested template improperly parsed?");
2510 ObjCDeclContextSwitch ObjCDC(*this);
2511 SourceLocation DeclEnd;
2512 return DeclGroupPtrTy::make(
2513 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2514 DeclaratorContext::MemberContext, DeclEnd, AS, AccessAttrs)));
2517 // Handle: member-declaration ::= '__extension__' member-declaration
2518 if (Tok.is(tok::kw___extension__)) {
2519 // __extension__ silences extension warnings in the subexpression.
2520 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2522 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2523 TemplateInfo, TemplateDiags);
2526 ParsedAttributesWithRange attrs(AttrFactory);
2527 ParsedAttributesWithRange FnAttrs(AttrFactory);
2528 // Optional C++11 attribute-specifier
2529 MaybeParseCXX11Attributes(attrs);
2530 // We need to keep these attributes for future diagnostic
2531 // before they are taken over by declaration specifier.
2532 FnAttrs.addAll(attrs.getList());
2533 FnAttrs.Range = attrs.Range;
2535 MaybeParseMicrosoftAttributes(attrs);
2537 if (Tok.is(tok::kw_using)) {
2538 ProhibitAttributes(attrs);
2541 SourceLocation UsingLoc = ConsumeToken();
2543 if (Tok.is(tok::kw_namespace)) {
2544 Diag(UsingLoc, diag::err_using_namespace_in_class);
2545 SkipUntil(tok::semi, StopBeforeMatch);
2548 SourceLocation DeclEnd;
2549 // Otherwise, it must be a using-declaration or an alias-declaration.
2550 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
2551 UsingLoc, DeclEnd, AS);
2554 // Hold late-parsed attributes so we can attach a Decl to them later.
2555 LateParsedAttrList CommonLateParsedAttrs;
2557 // decl-specifier-seq:
2558 // Parse the common declaration-specifiers piece.
2559 ParsingDeclSpec DS(*this, TemplateDiags);
2560 DS.takeAttributesFrom(attrs);
2561 if (MalformedTypeSpec)
2562 DS.SetTypeSpecError();
2564 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2565 &CommonLateParsedAttrs);
2567 // Turn off colon protection that was set for declspec.
2570 // If we had a free-standing type definition with a missing semicolon, we
2571 // may get this far before the problem becomes obvious.
2572 if (DS.hasTagDefinition() &&
2573 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2574 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
2575 &CommonLateParsedAttrs))
2578 MultiTemplateParamsArg TemplateParams(
2579 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2581 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2583 if (TryConsumeToken(tok::semi)) {
2584 if (DS.isFriendSpecified())
2585 ProhibitAttributes(FnAttrs);
2587 RecordDecl *AnonRecord = nullptr;
2588 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2589 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2590 DS.complete(TheDecl);
2592 Decl* decls[] = {AnonRecord, TheDecl};
2593 return Actions.BuildDeclaratorGroup(decls);
2595 return Actions.ConvertDeclToDeclGroup(TheDecl);
2598 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
2601 // Hold late-parsed attributes so we can attach a Decl to them later.
2602 LateParsedAttrList LateParsedAttrs;
2604 SourceLocation EqualLoc;
2605 SourceLocation PureSpecLoc;
2607 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2608 if (Tok.isNot(tok::equal))
2611 auto &Zero = NextToken();
2612 SmallString<8> Buffer;
2613 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2614 PP.getSpelling(Zero, Buffer) != "0")
2617 auto &After = GetLookAheadToken(2);
2618 if (!After.isOneOf(tok::semi, tok::comma) &&
2619 !(AllowDefinition &&
2620 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2623 EqualLoc = ConsumeToken();
2624 PureSpecLoc = ConsumeToken();
2628 SmallVector<Decl *, 8> DeclsInGroup;
2629 ExprResult BitfieldSize;
2630 bool ExpectSemi = true;
2632 // Parse the first declarator.
2633 if (ParseCXXMemberDeclaratorBeforeInitializer(
2634 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2635 TryConsumeToken(tok::semi);
2639 // Check for a member function definition.
2640 if (BitfieldSize.isUnset()) {
2641 // MSVC permits pure specifier on inline functions defined at class scope.
2642 // Hence check for =0 before checking for function definition.
2643 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2644 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2646 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2647 // function-definition:
2649 // In C++11, a non-function declarator followed by an open brace is a
2650 // braced-init-list for an in-class member initialization, not an
2651 // erroneous function definition.
2652 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2653 DefinitionKind = FDK_Definition;
2654 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2655 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2656 DefinitionKind = FDK_Definition;
2657 } else if (Tok.is(tok::equal)) {
2658 const Token &KW = NextToken();
2659 if (KW.is(tok::kw_default))
2660 DefinitionKind = FDK_Defaulted;
2661 else if (KW.is(tok::kw_delete))
2662 DefinitionKind = FDK_Deleted;
2665 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2667 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2668 // to a friend declaration, that declaration shall be a definition.
2669 if (DeclaratorInfo.isFunctionDeclarator() &&
2670 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2671 // Diagnose attributes that appear before decl specifier:
2672 // [[]] friend int foo();
2673 ProhibitAttributes(FnAttrs);
2676 if (DefinitionKind != FDK_Declaration) {
2677 if (!DeclaratorInfo.isFunctionDeclarator()) {
2678 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2680 SkipUntil(tok::r_brace);
2682 // Consume the optional ';'
2683 TryConsumeToken(tok::semi);
2688 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2689 Diag(DeclaratorInfo.getIdentifierLoc(),
2690 diag::err_function_declared_typedef);
2692 // Recover by treating the 'typedef' as spurious.
2693 DS.ClearStorageClassSpecs();
2697 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2701 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2702 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2704 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2705 LateParsedAttrs[i]->addDecl(FunDecl);
2708 LateParsedAttrs.clear();
2710 // Consume the ';' - it's optional unless we have a delete or default
2711 if (Tok.is(tok::semi))
2712 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2714 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2718 // member-declarator-list:
2719 // member-declarator
2720 // member-declarator-list ',' member-declarator
2723 InClassInitStyle HasInClassInit = ICIS_NoInit;
2724 bool HasStaticInitializer = false;
2725 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2726 if (DeclaratorInfo.isDeclarationOfFunction()) {
2727 // It's a pure-specifier.
2728 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2729 // Parse it as an expression so that Sema can diagnose it.
2730 HasStaticInitializer = true;
2731 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2732 DeclSpec::SCS_static &&
2733 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2734 DeclSpec::SCS_typedef &&
2735 !DS.isFriendSpecified()) {
2736 // It's a default member initializer.
2737 if (BitfieldSize.get())
2738 Diag(Tok, getLangOpts().CPlusPlus2a
2739 ? diag::warn_cxx17_compat_bitfield_member_init
2740 : diag::ext_bitfield_member_init);
2741 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2743 HasStaticInitializer = true;
2747 // NOTE: If Sema is the Action module and declarator is an instance field,
2748 // this call will *not* return the created decl; It will return null.
2749 // See Sema::ActOnCXXMemberDeclarator for details.
2751 NamedDecl *ThisDecl = nullptr;
2752 if (DS.isFriendSpecified()) {
2753 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2754 // to a friend declaration, that declaration shall be a definition.
2756 // Diagnose attributes that appear in a friend member function declarator:
2757 // friend int foo [[]] ();
2758 SmallVector<SourceRange, 4> Ranges;
2759 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2760 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2761 E = Ranges.end(); I != E; ++I)
2762 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2764 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2767 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2771 VS, HasInClassInit);
2773 if (VarTemplateDecl *VT =
2774 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2775 // Re-direct this decl to refer to the templated decl so that we can
2777 ThisDecl = VT->getTemplatedDecl();
2779 if (ThisDecl && AccessAttrs)
2780 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2783 // Error recovery might have converted a non-static member into a static
2785 if (HasInClassInit != ICIS_NoInit &&
2786 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2787 DeclSpec::SCS_static) {
2788 HasInClassInit = ICIS_NoInit;
2789 HasStaticInitializer = true;
2792 if (ThisDecl && PureSpecLoc.isValid())
2793 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2795 // Handle the initializer.
2796 if (HasInClassInit != ICIS_NoInit) {
2797 // The initializer was deferred; parse it and cache the tokens.
2798 Diag(Tok, getLangOpts().CPlusPlus11
2799 ? diag::warn_cxx98_compat_nonstatic_member_init
2800 : diag::ext_nonstatic_member_init);
2802 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2803 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2804 // declarator is followed by an initializer.
2806 // A brace-or-equal-initializer for a member-declarator is not an
2807 // initializer in the grammar, so this is ill-formed.
2808 Diag(Tok, diag::err_incomplete_array_member_init);
2809 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2811 // Avoid later warnings about a class member of incomplete type.
2813 ThisDecl->setInvalidDecl();
2815 ParseCXXNonStaticMemberInitializer(ThisDecl);
2816 } else if (HasStaticInitializer) {
2817 // Normal initializer.
2818 ExprResult Init = ParseCXXMemberInitializer(
2819 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2821 if (Init.isInvalid())
2822 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2824 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
2825 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2827 Actions.ActOnUninitializedDecl(ThisDecl);
2830 if (!ThisDecl->isInvalidDecl()) {
2831 // Set the Decl for any late parsed attributes
2832 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2833 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2835 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2836 LateParsedAttrs[i]->addDecl(ThisDecl);
2838 Actions.FinalizeDeclaration(ThisDecl);
2839 DeclsInGroup.push_back(ThisDecl);
2841 if (DeclaratorInfo.isFunctionDeclarator() &&
2842 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2843 DeclSpec::SCS_typedef)
2844 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2846 LateParsedAttrs.clear();
2848 DeclaratorInfo.complete(ThisDecl);
2850 // If we don't have a comma, it is either the end of the list (a ';')
2851 // or an error, bail out.
2852 SourceLocation CommaLoc;
2853 if (!TryConsumeToken(tok::comma, CommaLoc))
2856 if (Tok.isAtStartOfLine() &&
2857 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
2858 // This comma was followed by a line-break and something which can't be
2859 // the start of a declarator. The comma was probably a typo for a
2861 Diag(CommaLoc, diag::err_expected_semi_declaration)
2862 << FixItHint::CreateReplacement(CommaLoc, ";");
2867 // Parse the next declarator.
2868 DeclaratorInfo.clear();
2870 BitfieldSize = ExprResult(/*Invalid=*/false);
2871 EqualLoc = PureSpecLoc = SourceLocation();
2872 DeclaratorInfo.setCommaLoc(CommaLoc);
2874 // GNU attributes are allowed before the second and subsequent declarator.
2875 MaybeParseGNUAttributes(DeclaratorInfo);
2877 if (ParseCXXMemberDeclaratorBeforeInitializer(
2878 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2883 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2884 // Skip to end of block or statement.
2885 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2886 // If we stopped at a ';', eat it.
2887 TryConsumeToken(tok::semi);
2891 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2894 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2895 /// Also detect and reject any attempted defaulted/deleted function definition.
2896 /// The location of the '=', if any, will be placed in EqualLoc.
2898 /// This does not check for a pure-specifier; that's handled elsewhere.
2900 /// brace-or-equal-initializer:
2901 /// '=' initializer-expression
2902 /// braced-init-list
2904 /// initializer-clause:
2905 /// assignment-expression
2906 /// braced-init-list
2908 /// defaulted/deleted function-definition:
2912 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2913 /// be a constant-expression.
2914 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2915 SourceLocation &EqualLoc) {
2916 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2917 && "Data member initializer not starting with '=' or '{'");
2919 EnterExpressionEvaluationContext Context(
2920 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
2921 if (TryConsumeToken(tok::equal, EqualLoc)) {
2922 if (Tok.is(tok::kw_delete)) {
2923 // In principle, an initializer of '= delete p;' is legal, but it will
2924 // never type-check. It's better to diagnose it as an ill-formed expression
2925 // than as an ill-formed deleted non-function member.
2926 // An initializer of '= delete p, foo' will never be parsed, because
2927 // a top-level comma always ends the initializer expression.
2928 const Token &Next = NextToken();
2929 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2931 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2934 Diag(ConsumeToken(), diag::err_deleted_non_function);
2937 } else if (Tok.is(tok::kw_default)) {
2939 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2942 Diag(ConsumeToken(), diag::err_default_special_members);
2946 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2947 Diag(Tok, diag::err_ms_property_initializer) << PD;
2950 return ParseInitializer();
2953 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2954 SourceLocation AttrFixitLoc,
2955 unsigned TagType, Decl *TagDecl) {
2956 // Skip the optional 'final' keyword.
2957 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2958 assert(isCXX11FinalKeyword() && "not a class definition");
2961 // Diagnose any C++11 attributes after 'final' keyword.
2962 // We deliberately discard these attributes.
2963 ParsedAttributesWithRange Attrs(AttrFactory);
2964 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2966 // This can only happen if we had malformed misplaced attributes;
2967 // we only get called if there is a colon or left-brace after the
2969 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2973 // Skip the base clauses. This requires actually parsing them, because
2974 // otherwise we can't be sure where they end (a left brace may appear
2975 // within a template argument).
2976 if (Tok.is(tok::colon)) {
2977 // Enter the scope of the class so that we can correctly parse its bases.
2978 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2979 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2980 TagType == DeclSpec::TST_interface);
2982 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2984 // Parse the bases but don't attach them to the class.
2985 ParseBaseClause(nullptr);
2987 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2989 if (!Tok.is(tok::l_brace)) {
2990 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2991 diag::err_expected_lbrace_after_base_specifiers);
2997 assert(Tok.is(tok::l_brace));
2998 BalancedDelimiterTracker T(*this, tok::l_brace);
3002 // Parse and discard any trailing attributes.
3003 ParsedAttributes Attrs(AttrFactory);
3004 if (Tok.is(tok::kw___attribute))
3005 MaybeParseGNUAttributes(Attrs);
3008 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3009 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3010 DeclSpec::TST TagType, Decl *TagDecl) {
3011 switch (Tok.getKind()) {
3012 case tok::kw___if_exists:
3013 case tok::kw___if_not_exists:
3014 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
3018 // Check for extraneous top-level semicolon.
3019 ConsumeExtraSemi(InsideStruct, TagType);
3022 // Handle pragmas that can appear as member declarations.
3023 case tok::annot_pragma_vis:
3024 HandlePragmaVisibility();
3026 case tok::annot_pragma_pack:
3029 case tok::annot_pragma_align:
3030 HandlePragmaAlign();
3032 case tok::annot_pragma_ms_pointers_to_members:
3033 HandlePragmaMSPointersToMembers();
3035 case tok::annot_pragma_ms_pragma:
3036 HandlePragmaMSPragma();
3038 case tok::annot_pragma_ms_vtordisp:
3039 HandlePragmaMSVtorDisp();
3041 case tok::annot_pragma_dump:
3045 case tok::kw_namespace:
3046 // If we see a namespace here, a close brace was missing somewhere.
3047 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3050 case tok::kw_public:
3051 case tok::kw_protected:
3052 case tok::kw_private: {
3053 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3054 assert(NewAS != AS_none);
3055 // Current token is a C++ access specifier.
3057 SourceLocation ASLoc = Tok.getLocation();
3058 unsigned TokLength = Tok.getLength();
3060 AccessAttrs.clear();
3061 MaybeParseGNUAttributes(AccessAttrs);
3063 SourceLocation EndLoc;
3064 if (TryConsumeToken(tok::colon, EndLoc)) {
3065 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3066 Diag(EndLoc, diag::err_expected)
3067 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3069 EndLoc = ASLoc.getLocWithOffset(TokLength);
3070 Diag(EndLoc, diag::err_expected)
3071 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3074 // The Microsoft extension __interface does not permit non-public
3075 // access specifiers.
3076 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3077 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3080 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3081 AccessAttrs.getList())) {
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.getList());
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, 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(),
3286 // C++11 [class.mem]p2:
3287 // Within the class member-specification, the class is regarded as complete
3288 // within function bodies, default arguments, exception-specifications, and
3289 // brace-or-equal-initializers for non-static data members (including such
3290 // things in nested classes).
3291 if (TagDecl && NonNestedClass) {
3292 // We are not inside a nested class. This class and its nested classes
3293 // are complete and we can parse the delayed portions of method
3294 // declarations and the lexed inline method definitions, along with any
3295 // delayed attributes.
3296 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3297 ParseLexedAttributes(getCurrentClass());
3298 ParseLexedMethodDeclarations(getCurrentClass());
3300 // We've finished with all pending member declarations.
3301 Actions.ActOnFinishCXXMemberDecls();
3303 ParseLexedMemberInitializers(getCurrentClass());
3304 ParseLexedMethodDefs(getCurrentClass());
3305 PrevTokLocation = SavedPrevTokLocation;
3307 // We've finished parsing everything, including default argument
3309 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3313 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3315 // Leave the class scope.
3320 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3321 assert(Tok.is(tok::kw_namespace));
3323 // FIXME: Suggest where the close brace should have gone by looking
3324 // at indentation changes within the definition body.
3325 Diag(D->getLocation(),
3326 diag::err_missing_end_of_definition) << D;
3327 Diag(Tok.getLocation(),
3328 diag::note_missing_end_of_definition_before) << D;
3330 // Push '};' onto the token stream to recover.
3334 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3335 Tok.setKind(tok::semi);
3338 Tok.setKind(tok::r_brace);
3341 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3342 /// which explicitly initializes the members or base classes of a
3343 /// class (C++ [class.base.init]). For example, the three initializers
3344 /// after the ':' in the Derived constructor below:
3348 /// class Derived : Base {
3352 /// Derived(float f) : Base(), x(17), f(f) { }
3356 /// [C++] ctor-initializer:
3357 /// ':' mem-initializer-list
3359 /// [C++] mem-initializer-list:
3360 /// mem-initializer ...[opt]
3361 /// mem-initializer ...[opt] , mem-initializer-list
3362 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3363 assert(Tok.is(tok::colon) &&
3364 "Constructor initializer always starts with ':'");
3366 // Poison the SEH identifiers so they are flagged as illegal in constructor
3368 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3369 SourceLocation ColonLoc = ConsumeToken();
3371 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3372 bool AnyErrors = false;
3375 if (Tok.is(tok::code_completion)) {
3376 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3378 return cutOffParsing();
3381 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3382 if (!MemInit.isInvalid())
3383 MemInitializers.push_back(MemInit.get());
3387 if (Tok.is(tok::comma))
3389 else if (Tok.is(tok::l_brace))
3391 // If the previous initializer was valid and the next token looks like a
3392 // base or member initializer, assume that we're just missing a comma.
3393 else if (!MemInit.isInvalid() &&
3394 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3395 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3396 Diag(Loc, diag::err_ctor_init_missing_comma)
3397 << FixItHint::CreateInsertion(Loc, ", ");
3399 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3400 if (!MemInit.isInvalid())
3401 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3403 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3408 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3412 /// ParseMemInitializer - Parse a C++ member initializer, which is
3413 /// part of a constructor initializer that explicitly initializes one
3414 /// member or base class (C++ [class.base.init]). See
3415 /// ParseConstructorInitializer for an example.
3417 /// [C++] mem-initializer:
3418 /// mem-initializer-id '(' expression-list[opt] ')'
3419 /// [C++0x] mem-initializer-id braced-init-list
3421 /// [C++] mem-initializer-id:
3422 /// '::'[opt] nested-name-specifier[opt] class-name
3424 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3425 // parse '::'[opt] nested-name-specifier[opt]
3427 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
3430 IdentifierInfo *II = nullptr;
3431 SourceLocation IdLoc = Tok.getLocation();
3433 DeclSpec DS(AttrFactory);
3434 // : template_name<...>
3435 ParsedType TemplateTypeTy;
3437 if (Tok.is(tok::identifier)) {
3438 // Get the identifier. This may be a member name or a class name,
3439 // but we'll let the semantic analysis determine which it is.
3440 II = Tok.getIdentifierInfo();
3442 } else if (Tok.is(tok::annot_decltype)) {
3443 // Get the decltype expression, if there is one.
3444 // Uses of decltype will already have been converted to annot_decltype by
3445 // ParseOptionalCXXScopeSpecifier at this point.
3446 // FIXME: Can we get here with a scope specifier?
3447 ParseDecltypeSpecifier(DS);
3449 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3450 ? takeTemplateIdAnnotation(Tok)
3452 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3453 TemplateId->Kind == TNK_Dependent_template_name)) {
3454 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
3455 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3456 TemplateTypeTy = getTypeAnnotation(Tok);
3457 ConsumeAnnotationToken();
3459 Diag(Tok, diag::err_expected_member_or_base_name);
3465 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3466 Diag(Tok, diag::warn_cxx98_compat_generalized_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) && ParseExpressionList(ArgExprs, CommaLocs)) {
3486 SkipUntil(tok::r_paren, StopAtSemi);
3492 SourceLocation EllipsisLoc;
3493 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3495 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3496 TemplateTypeTy, DS, IdLoc,
3497 T.getOpenLocation(), ArgExprs,
3498 T.getCloseLocation(), EllipsisLoc);
3501 if (getLangOpts().CPlusPlus11)
3502 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3504 return Diag(Tok, diag::err_expected) << tok::l_paren;
3507 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
3509 /// exception-specification:
3510 /// dynamic-exception-specification
3511 /// noexcept-specification
3513 /// noexcept-specification:
3515 /// 'noexcept' '(' constant-expression ')'
3516 ExceptionSpecificationType
3517 Parser::tryParseExceptionSpecification(bool Delayed,
3518 SourceRange &SpecificationRange,
3519 SmallVectorImpl<ParsedType> &DynamicExceptions,
3520 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3521 ExprResult &NoexceptExpr,
3522 CachedTokens *&ExceptionSpecTokens) {
3523 ExceptionSpecificationType Result = EST_None;
3524 ExceptionSpecTokens = nullptr;
3526 // Handle delayed parsing of exception-specifications.
3528 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3531 // Consume and cache the starting token.
3532 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3533 Token StartTok = Tok;
3534 SpecificationRange = SourceRange(ConsumeToken());
3537 if (!Tok.is(tok::l_paren)) {
3538 // If this is a bare 'noexcept', we're done.
3540 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3541 NoexceptExpr = nullptr;
3542 return EST_BasicNoexcept;
3545 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3546 return EST_DynamicNone;
3549 // Cache the tokens for the exception-specification.
3550 ExceptionSpecTokens = new CachedTokens;
3551 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3552 ExceptionSpecTokens->push_back(Tok); // '('
3553 SpecificationRange.setEnd(ConsumeParen()); // '('
3555 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3556 /*StopAtSemi=*/true,
3557 /*ConsumeFinalToken=*/true);
3558 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3560 return EST_Unparsed;
3563 // See if there's a dynamic specification.
3564 if (Tok.is(tok::kw_throw)) {
3565 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3567 DynamicExceptionRanges);
3568 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3569 "Produced different number of exception types and ranges.");
3572 // If there's no noexcept specification, we're done.
3573 if (Tok.isNot(tok::kw_noexcept))
3576 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3578 // If we already had a dynamic specification, parse the noexcept for,
3579 // recovery, but emit a diagnostic and don't store the results.
3580 SourceRange NoexceptRange;
3581 ExceptionSpecificationType NoexceptType = EST_None;
3583 SourceLocation KeywordLoc = ConsumeToken();
3584 if (Tok.is(tok::l_paren)) {
3585 // There is an argument.
3586 BalancedDelimiterTracker T(*this, tok::l_paren);
3588 NoexceptType = EST_ComputedNoexcept;
3589 NoexceptExpr = ParseConstantExpression();
3591 // The argument must be contextually convertible to bool. We use
3592 // CheckBooleanCondition for this purpose.
3593 // FIXME: Add a proper Sema entry point for this.
3594 if (!NoexceptExpr.isInvalid()) {
3596 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
3597 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3599 NoexceptType = EST_BasicNoexcept;
3602 // There is no argument.
3603 NoexceptType = EST_BasicNoexcept;
3604 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3607 if (Result == EST_None) {
3608 SpecificationRange = NoexceptRange;
3609 Result = NoexceptType;
3611 // If there's a dynamic specification after a noexcept specification,
3612 // parse that and ignore the results.
3613 if (Tok.is(tok::kw_throw)) {
3614 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3615 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3616 DynamicExceptionRanges);
3619 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3625 static void diagnoseDynamicExceptionSpecification(
3626 Parser &P, SourceRange Range, bool IsNoexcept) {
3627 if (P.getLangOpts().CPlusPlus11) {
3628 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3629 P.Diag(Range.getBegin(),
3630 P.getLangOpts().CPlusPlus17 && !IsNoexcept
3631 ? diag::ext_dynamic_exception_spec
3632 : diag::warn_exception_spec_deprecated)
3634 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3635 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3639 /// ParseDynamicExceptionSpecification - Parse a C++
3640 /// dynamic-exception-specification (C++ [except.spec]).
3642 /// dynamic-exception-specification:
3643 /// 'throw' '(' type-id-list [opt] ')'
3644 /// [MS] 'throw' '(' '...' ')'
3647 /// type-id ... [opt]
3648 /// type-id-list ',' type-id ... [opt]
3650 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3651 SourceRange &SpecificationRange,
3652 SmallVectorImpl<ParsedType> &Exceptions,
3653 SmallVectorImpl<SourceRange> &Ranges) {
3654 assert(Tok.is(tok::kw_throw) && "expected throw");
3656 SpecificationRange.setBegin(ConsumeToken());
3657 BalancedDelimiterTracker T(*this, tok::l_paren);
3658 if (T.consumeOpen()) {
3659 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3660 SpecificationRange.setEnd(SpecificationRange.getBegin());
3661 return EST_DynamicNone;
3664 // Parse throw(...), a Microsoft extension that means "this function
3665 // can throw anything".
3666 if (Tok.is(tok::ellipsis)) {
3667 SourceLocation EllipsisLoc = ConsumeToken();
3668 if (!getLangOpts().MicrosoftExt)
3669 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3671 SpecificationRange.setEnd(T.getCloseLocation());
3672 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3676 // Parse the sequence of type-ids.
3678 while (Tok.isNot(tok::r_paren)) {
3679 TypeResult Res(ParseTypeName(&Range));
3681 if (Tok.is(tok::ellipsis)) {
3682 // C++0x [temp.variadic]p5:
3683 // - In a dynamic-exception-specification (15.4); the pattern is a
3685 SourceLocation Ellipsis = ConsumeToken();
3686 Range.setEnd(Ellipsis);
3687 if (!Res.isInvalid())
3688 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3691 if (!Res.isInvalid()) {
3692 Exceptions.push_back(Res.get());
3693 Ranges.push_back(Range);
3696 if (!TryConsumeToken(tok::comma))
3701 SpecificationRange.setEnd(T.getCloseLocation());
3702 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3703 Exceptions.empty());
3704 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3707 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3708 /// function declaration.
3709 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3710 assert(Tok.is(tok::arrow) && "expected arrow");
3714 return ParseTypeName(&Range, DeclaratorContext::TrailingReturnContext);
3717 /// \brief We have just started parsing the definition of a new class,
3718 /// so push that class onto our stack of classes that is currently
3720 Sema::ParsingClassState
3721 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3723 assert((NonNestedClass || !ClassStack.empty()) &&
3724 "Nested class without outer class");
3725 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3726 return Actions.PushParsingClass();
3729 /// \brief Deallocate the given parsed class and all of its nested
3731 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3732 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3733 delete Class->LateParsedDeclarations[I];
3737 /// \brief Pop the top class of the stack of classes that are
3738 /// currently being parsed.
3740 /// This routine should be called when we have finished parsing the
3741 /// definition of a class, but have not yet popped the Scope
3742 /// associated with the class's definition.
3743 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3744 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3746 Actions.PopParsingClass(state);
3748 ParsingClass *Victim = ClassStack.top();
3750 if (Victim->TopLevelClass) {
3751 // Deallocate all of the nested classes of this class,
3752 // recursively: we don't need to keep any of this information.
3753 DeallocateParsedClasses(Victim);
3756 assert(!ClassStack.empty() && "Missing top-level class?");
3758 if (Victim->LateParsedDeclarations.empty()) {
3759 // The victim is a nested class, but we will not need to perform
3760 // any processing after the definition of this class since it has
3761 // no members whose handling was delayed. Therefore, we can just
3762 // remove this nested class.
3763 DeallocateParsedClasses(Victim);
3767 // This nested class has some members that will need to be processed
3768 // after the top-level class is completely defined. Therefore, add
3769 // it to the list of nested classes within its parent.
3770 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3771 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3772 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3775 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3777 /// \return the parsed identifier on success, and 0 if the next token is not an
3778 /// attribute-token.
3780 /// C++11 [dcl.attr.grammar]p3:
3781 /// If a keyword or an alternative token that satisfies the syntactic
3782 /// requirements of an identifier is contained in an attribute-token,
3783 /// it is considered an identifier.
3784 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3785 switch (Tok.getKind()) {
3787 // Identifiers and keywords have identifier info attached.
3788 if (!Tok.isAnnotation()) {
3789 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3790 Loc = ConsumeToken();
3796 case tok::ampamp: // 'and'
3797 case tok::pipe: // 'bitor'
3798 case tok::pipepipe: // 'or'
3799 case tok::caret: // 'xor'
3800 case tok::tilde: // 'compl'
3801 case tok::amp: // 'bitand'
3802 case tok::ampequal: // 'and_eq'
3803 case tok::pipeequal: // 'or_eq'
3804 case tok::caretequal: // 'xor_eq'
3805 case tok::exclaim: // 'not'
3806 case tok::exclaimequal: // 'not_eq'
3807 // Alternative tokens do not have identifier info, but their spelling
3808 // starts with an alphabetical character.
3809 SmallString<8> SpellingBuf;
3810 SourceLocation SpellingLoc =
3811 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3812 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3813 if (isLetter(Spelling[0])) {
3814 Loc = ConsumeToken();
3815 return &PP.getIdentifierTable().get(Spelling);
3821 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3822 IdentifierInfo *ScopeName) {
3823 switch (AttributeList::getKind(AttrName, ScopeName,
3824 AttributeList::AS_CXX11)) {
3825 case AttributeList::AT_CarriesDependency:
3826 case AttributeList::AT_Deprecated:
3827 case AttributeList::AT_FallThrough:
3828 case AttributeList::AT_CXX11NoReturn:
3830 case AttributeList::AT_WarnUnusedResult:
3831 return !ScopeName && AttrName->getName().equals("nodiscard");
3832 case AttributeList::AT_Unused:
3833 return !ScopeName && AttrName->getName().equals("maybe_unused");
3839 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3841 /// [C++11] attribute-argument-clause:
3842 /// '(' balanced-token-seq ')'
3844 /// [C++11] balanced-token-seq:
3846 /// balanced-token-seq balanced-token
3848 /// [C++11] balanced-token:
3849 /// '(' balanced-token-seq ')'
3850 /// '[' balanced-token-seq ']'
3851 /// '{' balanced-token-seq '}'
3852 /// any token but '(', ')', '[', ']', '{', or '}'
3853 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3854 SourceLocation AttrNameLoc,
3855 ParsedAttributes &Attrs,
3856 SourceLocation *EndLoc,
3857 IdentifierInfo *ScopeName,
3858 SourceLocation ScopeLoc) {
3859 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3860 SourceLocation LParenLoc = Tok.getLocation();
3861 const LangOptions &LO = getLangOpts();
3862 AttributeList::Syntax Syntax =
3863 LO.CPlusPlus ? AttributeList::AS_CXX11 : AttributeList::AS_C2x;
3865 // If the attribute isn't known, we will not attempt to parse any
3867 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3868 AttrName, getTargetInfo(), getLangOpts())) {
3869 // Eat the left paren, then skip to the ending right paren.
3871 SkipUntil(tok::r_paren);
3875 if (ScopeName && ScopeName->getName() == "gnu") {
3876 // GNU-scoped attributes have some special cases to handle GNU-specific
3878 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3879 ScopeLoc, Syntax, nullptr);
3884 // Some Clang-scoped attributes have some special parsing behavior.
3885 if (ScopeName && ScopeName->getName() == "clang")
3887 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3891 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3892 ScopeName, ScopeLoc, Syntax);
3894 const AttributeList *Attr = Attrs.getList();
3895 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3896 // If the attribute is a standard or built-in attribute and we are
3897 // parsing an argument list, we need to determine whether this attribute
3898 // was allowed to have an argument list (such as [[deprecated]]), and how
3899 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3900 if (Attr->getMaxArgs() && !NumArgs) {
3901 // The attribute was allowed to have arguments, but none were provided
3902 // even though the attribute parsed successfully. This is an error.
3903 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3904 Attr->setInvalid(true);
3905 } else if (!Attr->getMaxArgs()) {
3906 // The attribute parsed successfully, but was not allowed to have any
3907 // arguments. It doesn't matter whether any were provided -- the
3908 // presence of the argument list (even if empty) is diagnosed.
3909 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3911 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3912 Attr->setInvalid(true);
3918 /// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
3920 /// [C++11] attribute-specifier:
3921 /// '[' '[' attribute-list ']' ']'
3922 /// alignment-specifier
3924 /// [C++11] attribute-list:
3926 /// attribute-list ',' attribute[opt]
3928 /// attribute-list ',' attribute '...'
3930 /// [C++11] attribute:
3931 /// attribute-token attribute-argument-clause[opt]
3933 /// [C++11] attribute-token:
3935 /// attribute-scoped-token
3937 /// [C++11] attribute-scoped-token:
3938 /// attribute-namespace '::' identifier
3940 /// [C++11] attribute-namespace:
3942 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3943 SourceLocation *endLoc) {
3944 if (Tok.is(tok::kw_alignas)) {
3945 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3946 ParseAlignmentSpecifier(attrs, endLoc);
3950 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3951 "Not a double square bracket attribute list");
3953 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3958 SourceLocation CommonScopeLoc;
3959 IdentifierInfo *CommonScopeName = nullptr;
3960 if (Tok.is(tok::kw_using)) {
3961 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
3962 ? diag::warn_cxx14_compat_using_attribute_ns
3963 : diag::ext_using_attribute_ns);
3966 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3967 if (!CommonScopeName) {
3968 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3969 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3971 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3972 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3975 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3977 while (Tok.isNot(tok::r_square)) {
3978 // attribute not present
3979 if (TryConsumeToken(tok::comma))
3982 SourceLocation ScopeLoc, AttrLoc;
3983 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3985 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3987 // Break out to the "expected ']'" diagnostic.
3991 if (TryConsumeToken(tok::coloncolon)) {
3992 ScopeName = AttrName;
3995 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3997 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3998 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
4003 if (CommonScopeName) {
4005 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4006 << SourceRange(CommonScopeLoc);
4008 ScopeName = CommonScopeName;
4009 ScopeLoc = CommonScopeLoc;
4013 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
4014 bool AttrParsed = false;
4017 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4018 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
4019 << AttrName << SourceRange(SeenAttrs[AttrName]);
4021 // Parse attribute arguments
4022 if (Tok.is(tok::l_paren))
4023 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4024 ScopeName, ScopeLoc);
4029 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4030 ScopeName, ScopeLoc, nullptr, 0,
4031 getLangOpts().CPlusPlus ? AttributeList::AS_CXX11
4032 : AttributeList::AS_C2x);
4034 if (TryConsumeToken(tok::ellipsis))
4035 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4036 << AttrName->getName();
4039 if (ExpectAndConsume(tok::r_square))
4040 SkipUntil(tok::r_square);
4042 *endLoc = Tok.getLocation();
4043 if (ExpectAndConsume(tok::r_square))
4044 SkipUntil(tok::r_square);
4047 /// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
4049 /// attribute-specifier-seq:
4050 /// attribute-specifier-seq[opt] attribute-specifier
4051 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
4052 SourceLocation *endLoc) {
4053 assert(standardAttributesAllowed());
4055 SourceLocation StartLoc = Tok.getLocation(), Loc;
4060 ParseCXX11AttributeSpecifier(attrs, endLoc);
4061 } while (isCXX11AttributeSpecifier());
4063 attrs.Range = SourceRange(StartLoc, *endLoc);
4066 void Parser::DiagnoseAndSkipCXX11Attributes() {
4067 // Start and end location of an attribute or an attribute list.
4068 SourceLocation StartLoc = Tok.getLocation();
4069 SourceLocation EndLoc = SkipCXX11Attributes();
4071 if (EndLoc.isValid()) {
4072 SourceRange Range(StartLoc, EndLoc);
4073 Diag(StartLoc, diag::err_attributes_not_allowed)
4078 SourceLocation Parser::SkipCXX11Attributes() {
4079 SourceLocation EndLoc;
4081 if (!isCXX11AttributeSpecifier())
4085 if (Tok.is(tok::l_square)) {
4086 BalancedDelimiterTracker T(*this, tok::l_square);
4089 EndLoc = T.getCloseLocation();
4091 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4093 BalancedDelimiterTracker T(*this, tok::l_paren);
4094 if (!T.consumeOpen())
4096 EndLoc = T.getCloseLocation();
4098 } while (isCXX11AttributeSpecifier());
4103 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4104 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4105 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4106 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4107 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4109 SourceLocation UuidLoc = Tok.getLocation();
4112 // Ignore the left paren location for now.
4113 BalancedDelimiterTracker T(*this, tok::l_paren);
4114 if (T.consumeOpen()) {
4115 Diag(Tok, diag::err_expected) << tok::l_paren;
4119 ArgsVector ArgExprs;
4120 if (Tok.is(tok::string_literal)) {
4121 // Easy case: uuid("...") -- quoted string.
4122 ExprResult StringResult = ParseStringLiteralExpression();
4123 if (StringResult.isInvalid())
4125 ArgExprs.push_back(StringResult.get());
4127 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4128 // quotes in the parens. Just append the spelling of all tokens encountered
4129 // until the closing paren.
4131 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4134 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4135 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4136 // tok::numeric_constant (0000) should be enough. But the spelling of the
4137 // uuid argument is checked later anyways, so there's no harm in accepting
4138 // almost anything here.
4139 // cl is very strict about whitespace in this form and errors out if any
4140 // is present, so check the space flags on the tokens.
4141 SourceLocation StartLoc = Tok.getLocation();
4142 while (Tok.isNot(tok::r_paren)) {
4143 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4144 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4145 SkipUntil(tok::r_paren, StopAtSemi);
4148 SmallString<16> SpellingBuffer;
4149 SpellingBuffer.resize(Tok.getLength() + 1);
4150 bool Invalid = false;
4151 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4153 SkipUntil(tok::r_paren, StopAtSemi);
4156 StrBuffer += TokSpelling;
4161 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4162 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4167 // Pretend the user wrote the appropriate string literal here.
4168 // ActOnStringLiteral() copies the string data into the literal, so it's
4169 // ok that the Token points to StrBuffer.
4171 Toks[0].startToken();
4172 Toks[0].setKind(tok::string_literal);
4173 Toks[0].setLocation(StartLoc);
4174 Toks[0].setLiteralData(StrBuffer.data());
4175 Toks[0].setLength(StrBuffer.size());
4176 StringLiteral *UuidString =
4177 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4178 ArgExprs.push_back(UuidString);
4181 if (!T.consumeClose()) {
4182 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4183 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4184 AttributeList::AS_Microsoft);
4188 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4190 /// [MS] ms-attribute:
4191 /// '[' token-seq ']'
4193 /// [MS] ms-attribute-seq:
4194 /// ms-attribute[opt]
4195 /// ms-attribute ms-attribute-seq
4196 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4197 SourceLocation *endLoc) {
4198 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4201 // FIXME: If this is actually a C++11 attribute, parse it as one.
4202 BalancedDelimiterTracker T(*this, tok::l_square);
4205 // Skip most ms attributes except for a whitelist.
4207 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4208 if (Tok.isNot(tok::identifier)) // ']', but also eof
4210 if (Tok.getIdentifierInfo()->getName() == "uuid")
4211 ParseMicrosoftUuidAttributeArgs(attrs);
4218 *endLoc = T.getCloseLocation();
4219 } while (Tok.is(tok::l_square));
4222 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4223 AccessSpecifier& CurAS) {
4224 IfExistsCondition Result;
4225 if (ParseMicrosoftIfExistsCondition(Result))
4228 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4229 if (Braces.consumeOpen()) {
4230 Diag(Tok, diag::err_expected) << tok::l_brace;
4234 switch (Result.Behavior) {
4236 // Parse the declarations below.
4240 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4241 << Result.IsIfExists;
4242 // Fall through to skip.
4250 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4251 // __if_exists, __if_not_exists can nest.
4252 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4253 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4257 // Check for extraneous top-level semicolon.
4258 if (Tok.is(tok::semi)) {
4259 ConsumeExtraSemi(InsideStruct, TagType);
4263 AccessSpecifier AS = getAccessSpecifierIfPresent();
4264 if (AS != AS_none) {
4265 // Current token is a C++ access specifier.
4267 SourceLocation ASLoc = Tok.getLocation();
4269 if (Tok.is(tok::colon))
4270 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4272 Diag(Tok, diag::err_expected) << tok::colon;
4277 // Parse all the comma separated declarators.
4278 ParseCXXClassMemberDeclaration(CurAS, nullptr);
4281 Braces.consumeClose();