1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++ Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/PrettyDeclStackTrace.h"
18 #include "clang/Basic/Attributes.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/OperatorKinds.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Parse/RAIIObjectsForParser.h"
24 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/ParsedTemplate.h"
26 #include "clang/Sema/Scope.h"
27 #include "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;
186 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
187 getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
188 T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
190 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
191 NamespaceLoc, "parsing namespace");
193 // Parse the contents of the namespace. This includes parsing recovery on
194 // any improperly nested namespaces.
195 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
196 InlineLoc, attrs, T);
198 // Leave the namespace scope.
199 NamespaceScope.Exit();
201 DeclEnd = T.getCloseLocation();
202 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
204 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
205 ImplicitUsingDirectiveDecl);
208 /// ParseInnerNamespace - Parse the contents of a namespace.
209 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
210 std::vector<IdentifierInfo *> &Ident,
211 std::vector<SourceLocation> &NamespaceLoc,
212 unsigned int index, SourceLocation &InlineLoc,
213 ParsedAttributes &attrs,
214 BalancedDelimiterTracker &Tracker) {
215 if (index == Ident.size()) {
216 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
217 Tok.isNot(tok::eof)) {
218 ParsedAttributesWithRange attrs(AttrFactory);
219 MaybeParseCXX11Attributes(attrs);
220 ParseExternalDeclaration(attrs);
223 // The caller is what called check -- we are simply calling
225 Tracker.consumeClose();
230 // Handle a nested namespace definition.
231 // FIXME: Preserve the source information through to the AST rather than
232 // desugaring it here.
233 ParseScope NamespaceScope(this, Scope::DeclScope);
234 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
235 Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
236 getCurScope(), SourceLocation(), NamespaceLoc[index], IdentLoc[index],
237 Ident[index], Tracker.getOpenLocation(), attrs,
238 ImplicitUsingDirectiveDecl);
239 assert(!ImplicitUsingDirectiveDecl &&
240 "nested namespace definition cannot define anonymous namespace");
242 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
245 NamespaceScope.Exit();
246 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
249 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
250 /// alias definition.
252 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
253 SourceLocation AliasLoc,
254 IdentifierInfo *Alias,
255 SourceLocation &DeclEnd) {
256 assert(Tok.is(tok::equal) && "Not equal token");
258 ConsumeToken(); // eat the '='.
260 if (Tok.is(tok::code_completion)) {
261 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
267 // Parse (optional) nested-name-specifier.
268 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
269 /*MayBePseudoDestructor=*/nullptr,
270 /*IsTypename=*/false,
272 /*OnlyNamespace=*/true);
274 if (Tok.isNot(tok::identifier)) {
275 Diag(Tok, diag::err_expected_namespace_name);
276 // Skip to end of the definition and eat the ';'.
277 SkipUntil(tok::semi);
281 if (SS.isInvalid()) {
282 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
283 // Skip to end of the definition and eat the ';'.
284 SkipUntil(tok::semi);
289 IdentifierInfo *Ident = Tok.getIdentifierInfo();
290 SourceLocation IdentLoc = ConsumeToken();
293 DeclEnd = Tok.getLocation();
294 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
295 SkipUntil(tok::semi);
297 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
298 Alias, SS, IdentLoc, Ident);
301 /// ParseLinkage - We know that the current token is a string_literal
302 /// and just before that, that extern was seen.
304 /// linkage-specification: [C++ 7.5p2: dcl.link]
305 /// 'extern' string-literal '{' declaration-seq[opt] '}'
306 /// 'extern' string-literal declaration
308 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
309 assert(isTokenStringLiteral() && "Not a string literal!");
310 ExprResult Lang = ParseStringLiteralExpression(false);
312 ParseScope LinkageScope(this, Scope::DeclScope);
316 : Actions.ActOnStartLinkageSpecification(
317 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
318 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
320 ParsedAttributesWithRange attrs(AttrFactory);
321 MaybeParseCXX11Attributes(attrs);
323 if (Tok.isNot(tok::l_brace)) {
324 // Reset the source range in DS, as the leading "extern"
325 // does not really belong to the inner declaration ...
326 DS.SetRangeStart(SourceLocation());
327 DS.SetRangeEnd(SourceLocation());
328 // ... but anyway remember that such an "extern" was seen.
329 DS.setExternInLinkageSpec(true);
330 ParseExternalDeclaration(attrs, &DS);
331 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
332 getCurScope(), LinkageSpec, SourceLocation())
338 ProhibitAttributes(attrs);
340 BalancedDelimiterTracker T(*this, tok::l_brace);
343 unsigned NestedModules = 0;
345 switch (Tok.getKind()) {
346 case tok::annot_module_begin:
351 case tok::annot_module_end:
358 case tok::annot_module_include:
370 ParsedAttributesWithRange attrs(AttrFactory);
371 MaybeParseCXX11Attributes(attrs);
372 ParseExternalDeclaration(attrs);
380 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
381 getCurScope(), LinkageSpec, T.getCloseLocation())
385 /// Parse a C++ Modules TS export-declaration.
387 /// export-declaration:
388 /// 'export' declaration
389 /// 'export' '{' declaration-seq[opt] '}'
391 Decl *Parser::ParseExportDeclaration() {
392 assert(Tok.is(tok::kw_export));
393 SourceLocation ExportLoc = ConsumeToken();
395 ParseScope ExportScope(this, Scope::DeclScope);
396 Decl *ExportDecl = Actions.ActOnStartExportDecl(
397 getCurScope(), ExportLoc,
398 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
400 if (Tok.isNot(tok::l_brace)) {
401 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
402 ParsedAttributesWithRange Attrs(AttrFactory);
403 MaybeParseCXX11Attributes(Attrs);
404 MaybeParseMicrosoftAttributes(Attrs);
405 ParseExternalDeclaration(Attrs);
406 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
410 BalancedDelimiterTracker T(*this, tok::l_brace);
413 // The Modules TS draft says "An export-declaration shall declare at least one
414 // entity", but the intent is that it shall contain at least one declaration.
415 if (Tok.is(tok::r_brace))
416 Diag(ExportLoc, diag::err_export_empty)
417 << SourceRange(ExportLoc, Tok.getLocation());
419 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
420 Tok.isNot(tok::eof)) {
421 ParsedAttributesWithRange Attrs(AttrFactory);
422 MaybeParseCXX11Attributes(Attrs);
423 MaybeParseMicrosoftAttributes(Attrs);
424 ParseExternalDeclaration(Attrs);
428 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
429 T.getCloseLocation());
432 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
433 /// using-directive. Assumes that current token is 'using'.
434 Parser::DeclGroupPtrTy
435 Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
436 const ParsedTemplateInfo &TemplateInfo,
437 SourceLocation &DeclEnd,
438 ParsedAttributesWithRange &attrs) {
439 assert(Tok.is(tok::kw_using) && "Not using token");
440 ObjCDeclContextSwitch ObjCDC(*this);
443 SourceLocation UsingLoc = ConsumeToken();
445 if (Tok.is(tok::code_completion)) {
446 Actions.CodeCompleteUsing(getCurScope());
451 // 'using namespace' means this is a using-directive.
452 if (Tok.is(tok::kw_namespace)) {
453 // Template parameters are always an error here.
454 if (TemplateInfo.Kind) {
455 SourceRange R = TemplateInfo.getSourceRange();
456 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
457 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
460 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
461 return Actions.ConvertDeclToDeclGroup(UsingDir);
464 // Otherwise, it must be a using-declaration or an alias-declaration.
466 // Using declarations can't have attributes.
467 ProhibitAttributes(attrs);
469 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
473 /// ParseUsingDirective - Parse C++ using-directive, assumes
474 /// that current token is 'namespace' and 'using' was already parsed.
476 /// using-directive: [C++ 7.3.p4: namespace.udir]
477 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
479 /// [GNU] using-directive:
480 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
481 /// namespace-name attributes[opt] ;
483 Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
484 SourceLocation UsingLoc,
485 SourceLocation &DeclEnd,
486 ParsedAttributes &attrs) {
487 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
490 SourceLocation NamespcLoc = ConsumeToken();
492 if (Tok.is(tok::code_completion)) {
493 Actions.CodeCompleteUsingDirective(getCurScope());
499 // Parse (optional) nested-name-specifier.
500 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
501 /*MayBePseudoDestructor=*/nullptr,
502 /*IsTypename=*/false,
504 /*OnlyNamespace=*/true);
506 IdentifierInfo *NamespcName = nullptr;
507 SourceLocation IdentLoc = SourceLocation();
509 // Parse namespace-name.
510 if (Tok.isNot(tok::identifier)) {
511 Diag(Tok, diag::err_expected_namespace_name);
512 // If there was invalid namespace name, skip to end of decl, and eat ';'.
513 SkipUntil(tok::semi);
514 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
518 if (SS.isInvalid()) {
519 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
520 // Skip to end of the definition and eat the ';'.
521 SkipUntil(tok::semi);
526 NamespcName = Tok.getIdentifierInfo();
527 IdentLoc = ConsumeToken();
529 // Parse (optional) attributes (most likely GNU strong-using extension).
530 bool GNUAttr = false;
531 if (Tok.is(tok::kw___attribute)) {
533 ParseGNUAttributes(attrs);
537 DeclEnd = Tok.getLocation();
538 if (ExpectAndConsume(tok::semi,
539 GNUAttr ? diag::err_expected_semi_after_attribute_list
540 : diag::err_expected_semi_after_namespace_name))
541 SkipUntil(tok::semi);
543 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
544 IdentLoc, NamespcName, attrs);
547 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
549 /// using-declarator:
550 /// 'typename'[opt] nested-name-specifier unqualified-id
552 bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
553 UsingDeclarator &D) {
556 // Ignore optional 'typename'.
557 // FIXME: This is wrong; we should parse this as a typename-specifier.
558 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
560 if (Tok.is(tok::kw___super)) {
561 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
565 // Parse nested-name-specifier.
566 IdentifierInfo *LastII = nullptr;
567 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
568 /*MayBePseudoDtor=*/nullptr,
569 /*IsTypename=*/false,
571 if (D.SS.isInvalid())
574 // Parse the unqualified-id. We allow parsing of both constructor and
575 // destructor names and allow the action module to diagnose any semantic
578 // C++11 [class.qual]p2:
579 // [...] in a using-declaration that is a member-declaration, if the name
580 // specified after the nested-name-specifier is the same as the identifier
581 // or the simple-template-id's template-name in the last component of the
582 // nested-name-specifier, the name is [...] considered to name the
584 if (getLangOpts().CPlusPlus11 &&
585 Context == DeclaratorContext::MemberContext &&
586 Tok.is(tok::identifier) &&
587 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
588 NextToken().is(tok::ellipsis)) &&
589 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
590 !D.SS.getScopeRep()->getAsNamespace() &&
591 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
592 SourceLocation IdLoc = ConsumeToken();
594 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
595 D.Name.setConstructorName(Type, IdLoc, IdLoc);
597 if (ParseUnqualifiedId(
598 D.SS, /*EnteringContext=*/false,
599 /*AllowDestructorName=*/true,
600 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
601 NextToken().is(tok::equal)),
602 /*AllowDeductionGuide=*/false,
603 nullptr, nullptr, D.Name))
607 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
608 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
609 diag::warn_cxx17_compat_using_declaration_pack :
610 diag::ext_using_declaration_pack);
615 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
616 /// Assumes that 'using' was already seen.
618 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
619 /// 'using' using-declarator-list[opt] ;
621 /// using-declarator-list: [C++1z]
622 /// using-declarator '...'[opt]
623 /// using-declarator-list ',' using-declarator '...'[opt]
625 /// using-declarator-list: [C++98-14]
628 /// alias-declaration: C++11 [dcl.dcl]p1
629 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
631 Parser::DeclGroupPtrTy
632 Parser::ParseUsingDeclaration(DeclaratorContext Context,
633 const ParsedTemplateInfo &TemplateInfo,
634 SourceLocation UsingLoc, SourceLocation &DeclEnd,
635 AccessSpecifier AS) {
636 // Check for misplaced attributes before the identifier in an
637 // alias-declaration.
638 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
639 MaybeParseCXX11Attributes(MisplacedAttrs);
642 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
644 ParsedAttributesWithRange Attrs(AttrFactory);
645 MaybeParseGNUAttributes(Attrs);
646 MaybeParseCXX11Attributes(Attrs);
648 // Maybe this is an alias-declaration.
649 if (Tok.is(tok::equal)) {
650 if (InvalidDeclarator) {
651 SkipUntil(tok::semi);
655 // If we had any misplaced attributes from earlier, this is where they
656 // should have been written.
657 if (MisplacedAttrs.Range.isValid()) {
658 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
659 << FixItHint::CreateInsertionFromRange(
661 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
662 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
663 Attrs.takeAllFrom(MisplacedAttrs);
666 Decl *DeclFromDeclSpec = nullptr;
667 Decl *AD = ParseAliasDeclarationAfterDeclarator(
668 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
669 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
672 // C++11 attributes are not allowed on a using-declaration, but GNU ones
674 ProhibitAttributes(MisplacedAttrs);
675 ProhibitAttributes(Attrs);
677 // Diagnose an attempt to declare a templated using-declaration.
678 // In C++11, alias-declarations can be templates:
679 // template <...> using id = type;
680 if (TemplateInfo.Kind) {
681 SourceRange R = TemplateInfo.getSourceRange();
682 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
683 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
685 // Unfortunately, we have to bail out instead of recovering by
686 // ignoring the parameters, just in case the nested name specifier
687 // depends on the parameters.
691 SmallVector<Decl *, 8> DeclsInGroup;
693 // Parse (optional) attributes (most likely GNU strong-using extension).
694 MaybeParseGNUAttributes(Attrs);
696 if (InvalidDeclarator)
697 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
699 // "typename" keyword is allowed for identifiers only,
700 // because it may be a type definition.
701 if (D.TypenameLoc.isValid() &&
702 D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
703 Diag(D.Name.getSourceRange().getBegin(),
704 diag::err_typename_identifiers_only)
705 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
706 // Proceed parsing, but discard the typename keyword.
707 D.TypenameLoc = SourceLocation();
710 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
711 D.TypenameLoc, D.SS, D.Name,
712 D.EllipsisLoc, Attrs);
714 DeclsInGroup.push_back(UD);
717 if (!TryConsumeToken(tok::comma))
720 // Parse another using-declarator.
722 InvalidDeclarator = ParseUsingDeclarator(Context, D);
725 if (DeclsInGroup.size() > 1)
726 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
727 diag::warn_cxx17_compat_multi_using_declaration :
728 diag::ext_multi_using_declaration);
731 DeclEnd = Tok.getLocation();
732 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
733 !Attrs.empty() ? "attributes list"
734 : "using declaration"))
735 SkipUntil(tok::semi);
737 return Actions.BuildDeclaratorGroup(DeclsInGroup);
740 Decl *Parser::ParseAliasDeclarationAfterDeclarator(
741 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
742 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
743 ParsedAttributes &Attrs, Decl **OwnedType) {
744 if (ExpectAndConsume(tok::equal)) {
745 SkipUntil(tok::semi);
749 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
750 diag::warn_cxx98_compat_alias_declaration :
751 diag::ext_alias_declaration);
753 // Type alias templates cannot be specialized.
755 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
756 D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
758 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
760 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
762 if (SpecKind != -1) {
765 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
766 D.Name.TemplateId->RAngleLoc);
768 Range = TemplateInfo.getSourceRange();
769 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
770 << SpecKind << Range;
771 SkipUntil(tok::semi);
775 // Name must be an identifier.
776 if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
777 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
778 // No removal fixit: can't recover from this.
779 SkipUntil(tok::semi);
781 } else if (D.TypenameLoc.isValid())
782 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
783 << FixItHint::CreateRemoval(SourceRange(
785 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
786 else if (D.SS.isNotEmpty())
787 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
788 << FixItHint::CreateRemoval(D.SS.getRange());
789 if (D.EllipsisLoc.isValid())
790 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
791 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
793 Decl *DeclFromDeclSpec = nullptr;
794 TypeResult TypeAlias = ParseTypeName(
796 TemplateInfo.Kind ? DeclaratorContext::AliasTemplateContext
797 : DeclaratorContext::AliasDeclContext,
798 AS, &DeclFromDeclSpec, &Attrs);
800 *OwnedType = DeclFromDeclSpec;
803 DeclEnd = Tok.getLocation();
804 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
805 !Attrs.empty() ? "attributes list"
806 : "alias declaration"))
807 SkipUntil(tok::semi);
809 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
810 MultiTemplateParamsArg TemplateParamsArg(
811 TemplateParams ? TemplateParams->data() : nullptr,
812 TemplateParams ? TemplateParams->size() : 0);
813 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
814 UsingLoc, D.Name, Attrs, TypeAlias,
818 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
820 /// [C++0x] static_assert-declaration:
821 /// static_assert ( constant-expression , string-literal ) ;
823 /// [C11] static_assert-declaration:
824 /// _Static_assert ( constant-expression , string-literal ) ;
826 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
827 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
828 "Not a static_assert declaration");
830 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
831 Diag(Tok, diag::ext_c11_static_assert);
832 if (Tok.is(tok::kw_static_assert))
833 Diag(Tok, diag::warn_cxx98_compat_static_assert);
835 SourceLocation StaticAssertLoc = ConsumeToken();
837 BalancedDelimiterTracker T(*this, tok::l_paren);
838 if (T.consumeOpen()) {
839 Diag(Tok, diag::err_expected) << tok::l_paren;
844 EnterExpressionEvaluationContext ConstantEvaluated(
845 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
846 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
847 if (AssertExpr.isInvalid()) {
852 ExprResult AssertMessage;
853 if (Tok.is(tok::r_paren)) {
854 Diag(Tok, getLangOpts().CPlusPlus17
855 ? diag::warn_cxx14_compat_static_assert_no_message
856 : diag::ext_static_assert_no_message)
857 << (getLangOpts().CPlusPlus17
859 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
861 if (ExpectAndConsume(tok::comma)) {
862 SkipUntil(tok::semi);
866 if (!isTokenStringLiteral()) {
867 Diag(Tok, diag::err_expected_string_literal)
868 << /*Source='static_assert'*/1;
873 AssertMessage = ParseStringLiteralExpression();
874 if (AssertMessage.isInvalid()) {
882 DeclEnd = Tok.getLocation();
883 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
885 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
888 T.getCloseLocation());
891 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
893 /// 'decltype' ( expression )
894 /// 'decltype' ( 'auto' ) [C++1y]
896 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
897 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
898 && "Not a decltype specifier");
901 SourceLocation StartLoc = Tok.getLocation();
902 SourceLocation EndLoc;
904 if (Tok.is(tok::annot_decltype)) {
905 Result = getExprAnnotation(Tok);
906 EndLoc = Tok.getAnnotationEndLoc();
907 ConsumeAnnotationToken();
908 if (Result.isInvalid()) {
909 DS.SetTypeSpecError();
913 if (Tok.getIdentifierInfo()->isStr("decltype"))
914 Diag(Tok, diag::warn_cxx98_compat_decltype);
918 BalancedDelimiterTracker T(*this, tok::l_paren);
919 if (T.expectAndConsume(diag::err_expected_lparen_after,
920 "decltype", tok::r_paren)) {
921 DS.SetTypeSpecError();
922 return T.getOpenLocation() == Tok.getLocation() ?
923 StartLoc : T.getOpenLocation();
926 // Check for C++1y 'decltype(auto)'.
927 if (Tok.is(tok::kw_auto)) {
928 // No need to disambiguate here: an expression can't start with 'auto',
929 // because the typename-specifier in a function-style cast operation can't
931 Diag(Tok.getLocation(),
932 getLangOpts().CPlusPlus14
933 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
934 : diag::ext_decltype_auto_type_specifier);
937 // Parse the expression
939 // C++11 [dcl.type.simple]p4:
940 // The operand of the decltype specifier is an unevaluated operand.
941 EnterExpressionEvaluationContext Unevaluated(
942 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
943 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
945 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
946 return E->hasPlaceholderType() ? ExprError() : E;
948 if (Result.isInvalid()) {
949 DS.SetTypeSpecError();
950 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
951 EndLoc = ConsumeParen();
953 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
954 // Backtrack to get the location of the last token before the semi.
955 PP.RevertCachedTokens(2);
956 ConsumeToken(); // the semi.
957 EndLoc = ConsumeAnyToken();
958 assert(Tok.is(tok::semi));
960 EndLoc = Tok.getLocation();
966 Result = Actions.ActOnDecltypeExpression(Result.get());
971 if (T.getCloseLocation().isInvalid()) {
972 DS.SetTypeSpecError();
973 // FIXME: this should return the location of the last token
974 // that was consumed (by "consumeClose()")
975 return T.getCloseLocation();
978 if (Result.isInvalid()) {
979 DS.SetTypeSpecError();
980 return T.getCloseLocation();
983 EndLoc = T.getCloseLocation();
985 assert(!Result.isInvalid());
987 const char *PrevSpec = nullptr;
989 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
990 // Check for duplicate type specifiers (e.g. "int decltype(a)").
992 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
993 DiagID, Result.get(), Policy)
994 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
996 Diag(StartLoc, DiagID) << PrevSpec;
997 DS.SetTypeSpecError();
1002 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1003 SourceLocation StartLoc,
1004 SourceLocation EndLoc) {
1005 // make sure we have a token we can turn into an annotation token
1006 if (PP.isBacktrackEnabled())
1007 PP.RevertCachedTokens(1);
1011 Tok.setKind(tok::annot_decltype);
1012 setExprAnnotation(Tok,
1013 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1014 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1016 Tok.setAnnotationEndLoc(EndLoc);
1017 Tok.setLocation(StartLoc);
1018 PP.AnnotateCachedTokens(Tok);
1021 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1022 assert(Tok.is(tok::kw___underlying_type) &&
1023 "Not an underlying type specifier");
1025 SourceLocation StartLoc = ConsumeToken();
1026 BalancedDelimiterTracker T(*this, tok::l_paren);
1027 if (T.expectAndConsume(diag::err_expected_lparen_after,
1028 "__underlying_type", tok::r_paren)) {
1032 TypeResult Result = ParseTypeName();
1033 if (Result.isInvalid()) {
1034 SkipUntil(tok::r_paren, StopAtSemi);
1040 if (T.getCloseLocation().isInvalid())
1043 const char *PrevSpec = nullptr;
1045 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
1046 DiagID, Result.get(),
1047 Actions.getASTContext().getPrintingPolicy()))
1048 Diag(StartLoc, DiagID) << PrevSpec;
1049 DS.setTypeofParensRange(T.getRange());
1052 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1053 /// class name or decltype-specifier. Note that we only check that the result
1054 /// names a type; semantic analysis will need to verify that the type names a
1055 /// class. The result is either a type or null, depending on whether a type
1058 /// base-type-specifier: [C++11 class.derived]
1059 /// class-or-decltype
1060 /// class-or-decltype: [C++11 class.derived]
1061 /// nested-name-specifier[opt] class-name
1062 /// decltype-specifier
1063 /// class-name: [C++ class.name]
1065 /// simple-template-id
1067 /// In C++98, instead of base-type-specifier, we have:
1069 /// ::[opt] nested-name-specifier[opt] class-name
1070 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1071 SourceLocation &EndLocation) {
1072 // Ignore attempts to use typename
1073 if (Tok.is(tok::kw_typename)) {
1074 Diag(Tok, diag::err_expected_class_name_not_template)
1075 << FixItHint::CreateRemoval(Tok.getLocation());
1079 // Parse optional nested-name-specifier
1081 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
1083 BaseLoc = Tok.getLocation();
1085 // Parse decltype-specifier
1086 // tok == kw_decltype is just error recovery, it can only happen when SS
1088 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
1089 if (SS.isNotEmpty())
1090 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1091 << FixItHint::CreateRemoval(SS.getRange());
1092 // Fake up a Declarator to use with ActOnTypeName.
1093 DeclSpec DS(AttrFactory);
1095 EndLocation = ParseDecltypeSpecifier(DS);
1097 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1098 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1101 // Check whether we have a template-id that names a type.
1102 if (Tok.is(tok::annot_template_id)) {
1103 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1104 if (TemplateId->Kind == TNK_Type_template ||
1105 TemplateId->Kind == TNK_Dependent_template_name) {
1106 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1108 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1109 ParsedType Type = getTypeAnnotation(Tok);
1110 EndLocation = Tok.getAnnotationEndLoc();
1111 ConsumeAnnotationToken();
1118 // Fall through to produce an error below.
1121 if (Tok.isNot(tok::identifier)) {
1122 Diag(Tok, diag::err_expected_class_name);
1126 IdentifierInfo *Id = Tok.getIdentifierInfo();
1127 SourceLocation IdLoc = ConsumeToken();
1129 if (Tok.is(tok::less)) {
1130 // It looks the user intended to write a template-id here, but the
1131 // template-name was wrong. Try to fix that.
1132 TemplateNameKind TNK = TNK_Type_template;
1133 TemplateTy Template;
1134 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
1135 &SS, Template, TNK)) {
1136 Diag(IdLoc, diag::err_unknown_template_name)
1141 TemplateArgList TemplateArgs;
1142 SourceLocation LAngleLoc, RAngleLoc;
1143 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1148 // Form the template name
1149 UnqualifiedId TemplateName;
1150 TemplateName.setIdentifier(Id, IdLoc);
1152 // Parse the full template-id, then turn it into a type.
1153 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1156 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1157 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1159 // If we didn't end up with a typename token, there's nothing more we
1161 if (Tok.isNot(tok::annot_typename))
1164 // Retrieve the type from the annotation token, consume that token, and
1166 EndLocation = Tok.getAnnotationEndLoc();
1167 ParsedType Type = getTypeAnnotation(Tok);
1168 ConsumeAnnotationToken();
1172 // We have an identifier; check whether it is actually a type.
1173 IdentifierInfo *CorrectedII = nullptr;
1174 ParsedType Type = Actions.getTypeName(
1175 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
1176 /*IsCtorOrDtorName=*/false,
1177 /*NonTrivialTypeSourceInfo=*/true,
1178 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
1180 Diag(IdLoc, diag::err_expected_class_name);
1184 // Consume the identifier.
1185 EndLocation = IdLoc;
1187 // Fake up a Declarator to use with ActOnTypeName.
1188 DeclSpec DS(AttrFactory);
1189 DS.SetRangeStart(IdLoc);
1190 DS.SetRangeEnd(EndLocation);
1191 DS.getTypeSpecScope() = SS;
1193 const char *PrevSpec = nullptr;
1195 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1196 Actions.getASTContext().getPrintingPolicy());
1198 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1199 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1202 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1203 while (Tok.isOneOf(tok::kw___single_inheritance,
1204 tok::kw___multiple_inheritance,
1205 tok::kw___virtual_inheritance)) {
1206 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1207 SourceLocation AttrNameLoc = ConsumeToken();
1208 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1209 ParsedAttr::AS_Keyword);
1213 /// Determine whether the following tokens are valid after a type-specifier
1214 /// which could be a standalone declaration. This will conservatively return
1215 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1216 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1217 // This switch enumerates the valid "follow" set for type-specifiers.
1218 switch (Tok.getKind()) {
1220 case tok::semi: // struct foo {...} ;
1221 case tok::star: // struct foo {...} * P;
1222 case tok::amp: // struct foo {...} & R = ...
1223 case tok::ampamp: // struct foo {...} && R = ...
1224 case tok::identifier: // struct foo {...} V ;
1225 case tok::r_paren: //(struct foo {...} ) {4}
1226 case tok::annot_cxxscope: // struct foo {...} a:: b;
1227 case tok::annot_typename: // struct foo {...} a ::b;
1228 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1229 case tok::l_paren: // struct foo {...} ( x);
1230 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1231 case tok::kw_operator: // struct foo operator ++() {...}
1232 case tok::kw___declspec: // struct foo {...} __declspec(...)
1233 case tok::l_square: // void f(struct f [ 3])
1234 case tok::ellipsis: // void f(struct f ... [Ns])
1235 // FIXME: we should emit semantic diagnostic when declaration
1236 // attribute is in type attribute position.
1237 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1238 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1239 // struct foo {...} _Pragma(section(...));
1240 case tok::annot_pragma_ms_pragma:
1241 // struct foo {...} _Pragma(vtordisp(pop));
1242 case tok::annot_pragma_ms_vtordisp:
1243 // struct foo {...} _Pragma(pointers_to_members(...));
1244 case tok::annot_pragma_ms_pointers_to_members:
1247 return CouldBeBitfield; // enum E { ... } : 2;
1248 // Microsoft compatibility
1249 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1250 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1251 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1252 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1253 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1254 // We will diagnose these calling-convention specifiers on non-function
1255 // declarations later, so claim they are valid after a type specifier.
1256 return getLangOpts().MicrosoftExt;
1258 case tok::kw_const: // struct foo {...} const x;
1259 case tok::kw_volatile: // struct foo {...} volatile x;
1260 case tok::kw_restrict: // struct foo {...} restrict x;
1261 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1262 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1263 // Function specifiers
1264 // Note, no 'explicit'. An explicit function must be either a conversion
1265 // operator or a constructor. Either way, it can't have a return type.
1266 case tok::kw_inline: // struct foo inline f();
1267 case tok::kw_virtual: // struct foo virtual f();
1268 case tok::kw_friend: // struct foo friend f();
1269 // Storage-class specifiers
1270 case tok::kw_static: // struct foo {...} static x;
1271 case tok::kw_extern: // struct foo {...} extern x;
1272 case tok::kw_typedef: // struct foo {...} typedef x;
1273 case tok::kw_register: // struct foo {...} register x;
1274 case tok::kw_auto: // struct foo {...} auto x;
1275 case tok::kw_mutable: // struct foo {...} mutable x;
1276 case tok::kw_thread_local: // struct foo {...} thread_local x;
1277 case tok::kw_constexpr: // struct foo {...} constexpr x;
1278 // As shown above, type qualifiers and storage class specifiers absolutely
1279 // can occur after class specifiers according to the grammar. However,
1280 // almost no one actually writes code like this. If we see one of these,
1281 // it is much more likely that someone missed a semi colon and the
1282 // type/storage class specifier we're seeing is part of the *next*
1283 // intended declaration, as in:
1285 // struct foo { ... }
1288 // We'd really like to emit a missing semicolon error instead of emitting
1289 // an error on the 'int' saying that you can't have two type specifiers in
1290 // the same declaration of X. Because of this, we look ahead past this
1291 // token to see if it's a type specifier. If so, we know the code is
1292 // otherwise invalid, so we can produce the expected semi error.
1293 if (!isKnownToBeTypeSpecifier(NextToken()))
1296 case tok::r_brace: // struct bar { struct foo {...} }
1297 // Missing ';' at end of struct is accepted as an extension in C mode.
1298 if (!getLangOpts().CPlusPlus)
1302 // template<class T = class X>
1303 return getLangOpts().CPlusPlus;
1308 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1309 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1310 /// until we reach the start of a definition or see a token that
1311 /// cannot start a definition.
1313 /// class-specifier: [C++ class]
1314 /// class-head '{' member-specification[opt] '}'
1315 /// class-head '{' member-specification[opt] '}' attributes[opt]
1317 /// class-key identifier[opt] base-clause[opt]
1318 /// class-key nested-name-specifier identifier base-clause[opt]
1319 /// class-key nested-name-specifier[opt] simple-template-id
1320 /// base-clause[opt]
1321 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1322 /// [GNU] class-key attributes[opt] nested-name-specifier
1323 /// identifier base-clause[opt]
1324 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1325 /// simple-template-id base-clause[opt]
1331 /// elaborated-type-specifier: [C++ dcl.type.elab]
1332 /// class-key ::[opt] nested-name-specifier[opt] identifier
1333 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1334 /// simple-template-id
1336 /// Note that the C++ class-specifier and elaborated-type-specifier,
1337 /// together, subsume the C99 struct-or-union-specifier:
1339 /// struct-or-union-specifier: [C99 6.7.2.1]
1340 /// struct-or-union identifier[opt] '{' struct-contents '}'
1341 /// struct-or-union identifier
1342 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1343 /// '}' attributes[opt]
1344 /// [GNU] struct-or-union attributes[opt] identifier
1345 /// struct-or-union:
1348 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1349 SourceLocation StartLoc, DeclSpec &DS,
1350 const ParsedTemplateInfo &TemplateInfo,
1352 bool EnteringContext, DeclSpecContext DSC,
1353 ParsedAttributesWithRange &Attributes) {
1354 DeclSpec::TST TagType;
1355 if (TagTokKind == tok::kw_struct)
1356 TagType = DeclSpec::TST_struct;
1357 else if (TagTokKind == tok::kw___interface)
1358 TagType = DeclSpec::TST_interface;
1359 else if (TagTokKind == tok::kw_class)
1360 TagType = DeclSpec::TST_class;
1362 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1363 TagType = DeclSpec::TST_union;
1366 if (Tok.is(tok::code_completion)) {
1367 // Code completion for a struct, class, or union name.
1368 Actions.CodeCompleteTag(getCurScope(), TagType);
1369 return cutOffParsing();
1372 // C++03 [temp.explicit] 14.7.2/8:
1373 // The usual access checking rules do not apply to names used to specify
1374 // explicit instantiations.
1376 // As an extension we do not perform access checking on the names used to
1377 // specify explicit specializations either. This is important to allow
1378 // specializing traits classes for private types.
1380 // Note that we don't suppress if this turns out to be an elaborated
1382 bool shouldDelayDiagsInTag =
1383 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1384 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1385 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1387 ParsedAttributesWithRange attrs(AttrFactory);
1388 // If attributes exist after tag, parse them.
1389 MaybeParseGNUAttributes(attrs);
1390 MaybeParseMicrosoftDeclSpecs(attrs);
1392 // Parse inheritance specifiers.
1393 if (Tok.isOneOf(tok::kw___single_inheritance,
1394 tok::kw___multiple_inheritance,
1395 tok::kw___virtual_inheritance))
1396 ParseMicrosoftInheritanceClassAttributes(attrs);
1398 // If C++0x attributes exist here, parse them.
1399 // FIXME: Are we consistent with the ordering of parsing of different
1400 // styles of attributes?
1401 MaybeParseCXX11Attributes(attrs);
1403 // Source location used by FIXIT to insert misplaced
1405 SourceLocation AttrFixitLoc = Tok.getLocation();
1407 if (TagType == DeclSpec::TST_struct &&
1408 Tok.isNot(tok::identifier) &&
1409 !Tok.isAnnotation() &&
1410 Tok.getIdentifierInfo() &&
1411 Tok.isOneOf(tok::kw___is_abstract,
1412 tok::kw___is_aggregate,
1413 tok::kw___is_arithmetic,
1415 tok::kw___is_assignable,
1416 tok::kw___is_base_of,
1418 tok::kw___is_complete_type,
1419 tok::kw___is_compound,
1421 tok::kw___is_constructible,
1422 tok::kw___is_convertible,
1423 tok::kw___is_convertible_to,
1424 tok::kw___is_destructible,
1427 tok::kw___is_floating_point,
1429 tok::kw___is_function,
1430 tok::kw___is_fundamental,
1431 tok::kw___is_integral,
1432 tok::kw___is_interface_class,
1433 tok::kw___is_literal,
1434 tok::kw___is_lvalue_expr,
1435 tok::kw___is_lvalue_reference,
1436 tok::kw___is_member_function_pointer,
1437 tok::kw___is_member_object_pointer,
1438 tok::kw___is_member_pointer,
1439 tok::kw___is_nothrow_assignable,
1440 tok::kw___is_nothrow_constructible,
1441 tok::kw___is_nothrow_destructible,
1442 tok::kw___is_object,
1444 tok::kw___is_pointer,
1445 tok::kw___is_polymorphic,
1446 tok::kw___is_reference,
1447 tok::kw___is_rvalue_expr,
1448 tok::kw___is_rvalue_reference,
1450 tok::kw___is_scalar,
1451 tok::kw___is_sealed,
1452 tok::kw___is_signed,
1453 tok::kw___is_standard_layout,
1454 tok::kw___is_trivial,
1455 tok::kw___is_trivially_assignable,
1456 tok::kw___is_trivially_constructible,
1457 tok::kw___is_trivially_copyable,
1459 tok::kw___is_unsigned,
1461 tok::kw___is_volatile))
1462 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1463 // name of struct templates, but some are keywords in GCC >= 4.3
1464 // and Clang. Therefore, when we see the token sequence "struct
1465 // X", make X into a normal identifier rather than a keyword, to
1466 // allow libstdc++ 4.2 and libc++ to work properly.
1467 TryKeywordIdentFallback(true);
1469 struct PreserveAtomicIdentifierInfoRAII {
1470 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1471 : AtomicII(nullptr) {
1474 assert(Tok.is(tok::kw__Atomic));
1475 AtomicII = Tok.getIdentifierInfo();
1476 AtomicII->revertTokenIDToIdentifier();
1477 Tok.setKind(tok::identifier);
1479 ~PreserveAtomicIdentifierInfoRAII() {
1482 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1484 IdentifierInfo *AtomicII;
1487 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1488 // implementation for VS2013 uses _Atomic as an identifier for one of the
1489 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1490 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1491 // use '_Atomic' in its own header files.
1492 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1493 Tok.is(tok::kw__Atomic) &&
1494 TagType == DeclSpec::TST_struct;
1495 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1496 Tok, ShouldChangeAtomicToIdentifier);
1498 // Parse the (optional) nested-name-specifier.
1499 CXXScopeSpec &SS = DS.getTypeSpecScope();
1500 if (getLangOpts().CPlusPlus) {
1501 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1502 // is a base-specifier-list.
1503 ColonProtectionRAIIObject X(*this);
1506 bool HasValidSpec = true;
1507 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
1508 DS.SetTypeSpecError();
1509 HasValidSpec = false;
1512 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1513 Diag(Tok, diag::err_expected) << tok::identifier;
1514 HasValidSpec = false;
1520 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1522 // Parse the (optional) class name or simple-template-id.
1523 IdentifierInfo *Name = nullptr;
1524 SourceLocation NameLoc;
1525 TemplateIdAnnotation *TemplateId = nullptr;
1526 if (Tok.is(tok::identifier)) {
1527 Name = Tok.getIdentifierInfo();
1528 NameLoc = ConsumeToken();
1530 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1531 // The name was supposed to refer to a template, but didn't.
1532 // Eat the template argument list and try to continue parsing this as
1533 // a class (or template thereof).
1534 TemplateArgList TemplateArgs;
1535 SourceLocation LAngleLoc, RAngleLoc;
1536 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1538 // We couldn't parse the template argument list at all, so don't
1539 // try to give any location information for the list.
1540 LAngleLoc = RAngleLoc = SourceLocation();
1543 Diag(NameLoc, diag::err_explicit_spec_non_template)
1544 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1545 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1547 // Strip off the last template parameter list if it was empty, since
1548 // we've removed its template argument list.
1549 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1550 if (TemplateParams->size() > 1) {
1551 TemplateParams->pop_back();
1553 TemplateParams = nullptr;
1554 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1555 = ParsedTemplateInfo::NonTemplate;
1557 } else if (TemplateInfo.Kind
1558 == ParsedTemplateInfo::ExplicitInstantiation) {
1559 // Pretend this is just a forward declaration.
1560 TemplateParams = nullptr;
1561 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1562 = ParsedTemplateInfo::NonTemplate;
1563 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1565 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1569 } else if (Tok.is(tok::annot_template_id)) {
1570 TemplateId = takeTemplateIdAnnotation(Tok);
1571 NameLoc = ConsumeAnnotationToken();
1573 if (TemplateId->Kind != TNK_Type_template &&
1574 TemplateId->Kind != TNK_Dependent_template_name) {
1575 // The template-name in the simple-template-id refers to
1576 // something other than a class template. Give an appropriate
1577 // error message and skip to the ';'.
1578 SourceRange Range(NameLoc);
1579 if (SS.isNotEmpty())
1580 Range.setBegin(SS.getBeginLoc());
1582 // FIXME: Name may be null here.
1583 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1584 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1586 DS.SetTypeSpecError();
1587 SkipUntil(tok::semi, StopBeforeMatch);
1592 // There are four options here.
1593 // - If we are in a trailing return type, this is always just a reference,
1594 // and we must not try to parse a definition. For instance,
1595 // [] () -> struct S { };
1596 // does not define a type.
1597 // - If we have 'struct foo {...', 'struct foo :...',
1598 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1599 // - If we have 'struct foo;', then this is either a forward declaration
1600 // or a friend declaration, which have to be treated differently.
1601 // - Otherwise we have something like 'struct foo xyz', a reference.
1603 // We also detect these erroneous cases to provide better diagnostic for
1604 // C++11 attributes parsing.
1605 // - attributes follow class name:
1606 // struct foo [[]] {};
1607 // - attributes appear before or after 'final':
1608 // struct foo [[]] final [[]] {};
1610 // However, in type-specifier-seq's, things look like declarations but are
1611 // just references, e.g.
1614 // &T::operator struct s;
1615 // For these, DSC is DeclSpecContext::DSC_type_specifier or
1616 // DeclSpecContext::DSC_alias_declaration.
1618 // If there are attributes after class name, parse them.
1619 MaybeParseCXX11Attributes(Attributes);
1621 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1622 Sema::TagUseKind TUK;
1623 if (DSC == DeclSpecContext::DSC_trailing)
1624 TUK = Sema::TUK_Reference;
1625 else if (Tok.is(tok::l_brace) ||
1626 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1627 (isCXX11FinalKeyword() &&
1628 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1629 if (DS.isFriendSpecified()) {
1630 // C++ [class.friend]p2:
1631 // A class shall not be defined in a friend declaration.
1632 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1633 << SourceRange(DS.getFriendSpecLoc());
1635 // Skip everything up to the semicolon, so that this looks like a proper
1636 // friend class (or template thereof) declaration.
1637 SkipUntil(tok::semi, StopBeforeMatch);
1638 TUK = Sema::TUK_Friend;
1640 // Okay, this is a class definition.
1641 TUK = Sema::TUK_Definition;
1643 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1644 NextToken().is(tok::kw_alignas))) {
1645 // We can't tell if this is a definition or reference
1646 // until we skipped the 'final' and C++11 attribute specifiers.
1647 TentativeParsingAction PA(*this);
1649 // Skip the 'final' keyword.
1652 // Skip C++11 attribute specifiers.
1654 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1656 if (!SkipUntil(tok::r_square, StopAtSemi))
1658 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1661 if (!SkipUntil(tok::r_paren, StopAtSemi))
1668 if (Tok.isOneOf(tok::l_brace, tok::colon))
1669 TUK = Sema::TUK_Definition;
1671 TUK = Sema::TUK_Reference;
1674 } else if (!isTypeSpecifier(DSC) &&
1675 (Tok.is(tok::semi) ||
1676 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1677 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1678 if (Tok.isNot(tok::semi)) {
1679 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1680 // A semicolon was missing after this declaration. Diagnose and recover.
1681 ExpectAndConsume(tok::semi, diag::err_expected_after,
1682 DeclSpec::getSpecifierName(TagType, PPol));
1684 Tok.setKind(tok::semi);
1687 TUK = Sema::TUK_Reference;
1689 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1690 // to caller to handle.
1691 if (TUK != Sema::TUK_Reference) {
1692 // If this is not a reference, then the only possible
1693 // valid place for C++11 attributes to appear here
1694 // is between class-key and class-name. If there are
1695 // any attributes after class-name, we try a fixit to move
1696 // them to the right place.
1697 SourceRange AttrRange = Attributes.Range;
1698 if (AttrRange.isValid()) {
1699 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1701 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1702 CharSourceRange(AttrRange, true))
1703 << FixItHint::CreateRemoval(AttrRange);
1705 // Recover by adding misplaced attributes to the attribute list
1706 // of the class so they can be applied on the class later.
1707 attrs.takeAllFrom(Attributes);
1711 // If this is an elaborated type specifier, and we delayed
1712 // diagnostics before, just merge them into the current pool.
1713 if (shouldDelayDiagsInTag) {
1714 diagsFromTag.done();
1715 if (TUK == Sema::TUK_Reference)
1716 diagsFromTag.redelay();
1719 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1720 TUK != Sema::TUK_Definition)) {
1721 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1722 // We have a declaration or reference to an anonymous class.
1723 Diag(StartLoc, diag::err_anon_type_definition)
1724 << DeclSpec::getSpecifierName(TagType, Policy);
1727 // If we are parsing a definition and stop at a base-clause, continue on
1728 // until the semicolon. Continuing from the comma will just trick us into
1729 // thinking we are seeing a variable declaration.
1730 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1731 SkipUntil(tok::semi, StopBeforeMatch);
1733 SkipUntil(tok::comma, StopAtSemi);
1737 // Create the tag portion of the class or class template.
1738 DeclResult TagOrTempResult = true; // invalid
1739 TypeResult TypeResult = true; // invalid
1742 Sema::SkipBodyInfo SkipBody;
1744 // Explicit specialization, class template partial specialization,
1745 // or explicit instantiation.
1746 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1747 TemplateId->NumArgs);
1748 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1749 TUK == Sema::TUK_Declaration) {
1750 // This is an explicit instantiation of a class template.
1751 ProhibitAttributes(attrs);
1753 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1754 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1755 TagType, StartLoc, SS, TemplateId->Template,
1756 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
1757 TemplateId->RAngleLoc, attrs);
1759 // Friend template-ids are treated as references unless
1760 // they have template headers, in which case they're ill-formed
1761 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1762 // We diagnose this error in ActOnClassTemplateSpecialization.
1763 } else if (TUK == Sema::TUK_Reference ||
1764 (TUK == Sema::TUK_Friend &&
1765 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1766 ProhibitAttributes(attrs);
1767 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1769 TemplateId->TemplateKWLoc,
1770 TemplateId->Template,
1771 TemplateId->TemplateNameLoc,
1772 TemplateId->LAngleLoc,
1774 TemplateId->RAngleLoc);
1776 // This is an explicit specialization or a class template
1777 // partial specialization.
1778 TemplateParameterLists FakedParamLists;
1779 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1780 // This looks like an explicit instantiation, because we have
1783 // template class Foo<X>
1785 // but it actually has a definition. Most likely, this was
1786 // meant to be an explicit specialization, but the user forgot
1787 // the '<>' after 'template'.
1788 // It this is friend declaration however, since it cannot have a
1789 // template header, it is most likely that the user meant to
1790 // remove the 'template' keyword.
1791 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1792 "Expected a definition here");
1794 if (TUK == Sema::TUK_Friend) {
1795 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1796 TemplateParams = nullptr;
1798 SourceLocation LAngleLoc =
1799 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1800 Diag(TemplateId->TemplateNameLoc,
1801 diag::err_explicit_instantiation_with_definition)
1802 << SourceRange(TemplateInfo.TemplateLoc)
1803 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1805 // Create a fake template parameter list that contains only
1806 // "template<>", so that we treat this construct as a class
1807 // template specialization.
1808 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1809 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1810 LAngleLoc, nullptr));
1811 TemplateParams = &FakedParamLists;
1815 // Build the class template specialization.
1816 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1817 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1819 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1821 TemplateParams ? TemplateParams->size() : 0),
1824 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1825 TUK == Sema::TUK_Declaration) {
1826 // Explicit instantiation of a member of a class template
1827 // specialization, e.g.,
1829 // template struct Outer<int>::Inner;
1831 ProhibitAttributes(attrs);
1833 TagOrTempResult = Actions.ActOnExplicitInstantiation(
1834 getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
1835 TagType, StartLoc, SS, Name, NameLoc, attrs);
1836 } else if (TUK == Sema::TUK_Friend &&
1837 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1838 ProhibitAttributes(attrs);
1840 TagOrTempResult = Actions.ActOnTemplatedFriendTag(
1841 getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
1843 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
1844 TemplateParams ? TemplateParams->size() : 0));
1846 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1847 ProhibitAttributes(attrs);
1849 if (TUK == Sema::TUK_Definition &&
1850 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1851 // If the declarator-id is not a template-id, issue a diagnostic and
1852 // recover by ignoring the 'template' keyword.
1853 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1854 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1855 TemplateParams = nullptr;
1858 bool IsDependent = false;
1860 // Don't pass down template parameter lists if this is just a tag
1861 // reference. For example, we don't need the template parameters here:
1862 // template <class T> class A *makeA(T t);
1863 MultiTemplateParamsArg TParams;
1864 if (TUK != Sema::TUK_Reference && TemplateParams)
1866 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1868 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
1870 // Declaration or definition of a class type
1871 TagOrTempResult = Actions.ActOnTag(
1872 getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
1873 DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
1874 SourceLocation(), false, clang::TypeResult(),
1875 DSC == DeclSpecContext::DSC_type_specifier,
1876 DSC == DeclSpecContext::DSC_template_param ||
1877 DSC == DeclSpecContext::DSC_template_type_arg,
1880 // If ActOnTag said the type was dependent, try again with the
1881 // less common call.
1883 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1884 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1885 SS, Name, StartLoc, NameLoc);
1889 // If there is a body, parse it and inform the actions module.
1890 if (TUK == Sema::TUK_Definition) {
1891 assert(Tok.is(tok::l_brace) ||
1892 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1893 isCXX11FinalKeyword());
1894 if (SkipBody.ShouldSkip)
1895 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1896 TagOrTempResult.get());
1897 else if (getLangOpts().CPlusPlus)
1898 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1899 TagOrTempResult.get());
1902 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1903 // Parse the definition body.
1904 ParseStructUnionBody(StartLoc, TagType, D);
1905 if (SkipBody.CheckSameAsPrevious &&
1906 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1908 DS.SetTypeSpecError();
1914 if (!TagOrTempResult.isInvalid())
1915 // Delayed processing of attributes.
1916 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
1918 const char *PrevSpec = nullptr;
1921 if (!TypeResult.isInvalid()) {
1922 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1923 NameLoc.isValid() ? NameLoc : StartLoc,
1924 PrevSpec, DiagID, TypeResult.get(), Policy);
1925 } else if (!TagOrTempResult.isInvalid()) {
1926 Result = DS.SetTypeSpecType(TagType, StartLoc,
1927 NameLoc.isValid() ? NameLoc : StartLoc,
1928 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1931 DS.SetTypeSpecError();
1936 Diag(StartLoc, DiagID) << PrevSpec;
1938 // At this point, we've successfully parsed a class-specifier in 'definition'
1939 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1940 // going to look at what comes after it to improve error recovery. If an
1941 // impossible token occurs next, we assume that the programmer forgot a ; at
1942 // the end of the declaration and recover that way.
1944 // Also enforce C++ [temp]p3:
1945 // In a template-declaration which defines a class, no declarator
1948 // After a type-specifier, we don't expect a semicolon. This only happens in
1949 // C, since definitions are not permitted in this context in C++.
1950 if (TUK == Sema::TUK_Definition &&
1951 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1952 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1953 if (Tok.isNot(tok::semi)) {
1954 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1955 ExpectAndConsume(tok::semi, diag::err_expected_after,
1956 DeclSpec::getSpecifierName(TagType, PPol));
1957 // Push this token back into the preprocessor and change our current token
1958 // to ';' so that the rest of the code recovers as though there were an
1959 // ';' after the definition.
1961 Tok.setKind(tok::semi);
1966 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1968 /// base-clause : [C++ class.derived]
1969 /// ':' base-specifier-list
1970 /// base-specifier-list:
1971 /// base-specifier '...'[opt]
1972 /// base-specifier-list ',' base-specifier '...'[opt]
1973 void Parser::ParseBaseClause(Decl *ClassDecl) {
1974 assert(Tok.is(tok::colon) && "Not a base clause");
1977 // Build up an array of parsed base specifiers.
1978 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1981 // Parse a base-specifier.
1982 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1983 if (Result.isInvalid()) {
1984 // Skip the rest of this base specifier, up until the comma or
1986 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
1988 // Add this to our array of base specifiers.
1989 BaseInfo.push_back(Result.get());
1992 // If the next token is a comma, consume it and keep reading
1994 if (!TryConsumeToken(tok::comma))
1998 // Attach the base specifiers
1999 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2002 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2003 /// one entry in the base class list of a class specifier, for example:
2004 /// class foo : public bar, virtual private baz {
2005 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2007 /// base-specifier: [C++ class.derived]
2008 /// attribute-specifier-seq[opt] base-type-specifier
2009 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2010 /// base-type-specifier
2011 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2012 /// base-type-specifier
2013 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2014 bool IsVirtual = false;
2015 SourceLocation StartLoc = Tok.getLocation();
2017 ParsedAttributesWithRange Attributes(AttrFactory);
2018 MaybeParseCXX11Attributes(Attributes);
2020 // Parse the 'virtual' keyword.
2021 if (TryConsumeToken(tok::kw_virtual))
2024 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2026 // Parse an (optional) access specifier.
2027 AccessSpecifier Access = getAccessSpecifierIfPresent();
2028 if (Access != AS_none)
2031 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2033 // Parse the 'virtual' keyword (again!), in case it came after the
2034 // access specifier.
2035 if (Tok.is(tok::kw_virtual)) {
2036 SourceLocation VirtualLoc = ConsumeToken();
2038 // Complain about duplicate 'virtual'
2039 Diag(VirtualLoc, diag::err_dup_virtual)
2040 << FixItHint::CreateRemoval(VirtualLoc);
2046 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2048 // Parse the class-name.
2050 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2051 // implementation for VS2013 uses _Atomic as an identifier for one of the
2052 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2053 // parsing the class-name for a base specifier.
2054 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2055 NextToken().is(tok::less))
2056 Tok.setKind(tok::identifier);
2058 SourceLocation EndLocation;
2059 SourceLocation BaseLoc;
2060 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2061 if (BaseType.isInvalid())
2064 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2065 // actually part of the base-specifier-list grammar productions, but we
2066 // parse it here for convenience.
2067 SourceLocation EllipsisLoc;
2068 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2070 // Find the complete source range for the base-specifier.
2071 SourceRange Range(StartLoc, EndLocation);
2073 // Notify semantic analysis that we have parsed a complete
2075 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2076 Access, BaseType.get(), BaseLoc,
2080 /// getAccessSpecifierIfPresent - Determine whether the next token is
2081 /// a C++ access-specifier.
2083 /// access-specifier: [C++ class.derived]
2087 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2088 switch (Tok.getKind()) {
2089 default: return AS_none;
2090 case tok::kw_private: return AS_private;
2091 case tok::kw_protected: return AS_protected;
2092 case tok::kw_public: return AS_public;
2096 /// If the given declarator has any parts for which parsing has to be
2097 /// delayed, e.g., default arguments or an exception-specification, create a
2098 /// late-parsed method declaration record to handle the parsing at the end of
2099 /// the class definition.
2100 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2102 DeclaratorChunk::FunctionTypeInfo &FTI
2103 = DeclaratorInfo.getFunctionTypeInfo();
2104 // If there was a late-parsed exception-specification, we'll need a
2106 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2108 if (!NeedLateParse) {
2109 // Look ahead to see if there are any default args
2110 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2111 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2112 if (Param->hasUnparsedDefaultArg()) {
2113 NeedLateParse = true;
2119 if (NeedLateParse) {
2120 // Push this method onto the stack of late-parsed method
2122 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2123 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2124 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2126 // Stash the exception-specification tokens in the late-pased method.
2127 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2128 FTI.ExceptionSpecTokens = nullptr;
2130 // Push tokens for each parameter. Those that do not have
2131 // defaults will be NULL.
2132 LateMethod->DefaultArgs.reserve(FTI.NumParams);
2133 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2134 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2135 FTI.Params[ParamIdx].Param,
2136 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2140 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2147 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2148 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2149 return VirtSpecifiers::VS_None;
2151 IdentifierInfo *II = Tok.getIdentifierInfo();
2153 // Initialize the contextual keywords.
2155 Ident_final = &PP.getIdentifierTable().get("final");
2156 if (getLangOpts().GNUKeywords)
2157 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2158 if (getLangOpts().MicrosoftExt)
2159 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2160 Ident_override = &PP.getIdentifierTable().get("override");
2163 if (II == Ident_override)
2164 return VirtSpecifiers::VS_Override;
2166 if (II == Ident_sealed)
2167 return VirtSpecifiers::VS_Sealed;
2169 if (II == Ident_final)
2170 return VirtSpecifiers::VS_Final;
2172 if (II == Ident_GNU_final)
2173 return VirtSpecifiers::VS_GNU_Final;
2175 return VirtSpecifiers::VS_None;
2178 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2180 /// virt-specifier-seq:
2182 /// virt-specifier-seq virt-specifier
2183 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2185 SourceLocation FriendLoc) {
2187 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2188 if (Specifier == VirtSpecifiers::VS_None)
2191 if (FriendLoc.isValid()) {
2192 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2193 << VirtSpecifiers::getSpecifierName(Specifier)
2194 << FixItHint::CreateRemoval(Tok.getLocation())
2195 << SourceRange(FriendLoc, FriendLoc);
2200 // C++ [class.mem]p8:
2201 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2202 const char *PrevSpec = nullptr;
2203 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2204 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2206 << FixItHint::CreateRemoval(Tok.getLocation());
2208 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2209 Specifier == VirtSpecifiers::VS_Sealed)) {
2210 Diag(Tok.getLocation(), diag::err_override_control_interface)
2211 << VirtSpecifiers::getSpecifierName(Specifier);
2212 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2213 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2214 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2215 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2217 Diag(Tok.getLocation(),
2218 getLangOpts().CPlusPlus11
2219 ? diag::warn_cxx98_compat_override_control_keyword
2220 : diag::ext_override_control_keyword)
2221 << VirtSpecifiers::getSpecifierName(Specifier);
2227 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2228 /// 'final' or Microsoft 'sealed' contextual keyword.
2229 bool Parser::isCXX11FinalKeyword() const {
2230 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2231 return Specifier == VirtSpecifiers::VS_Final ||
2232 Specifier == VirtSpecifiers::VS_GNU_Final ||
2233 Specifier == VirtSpecifiers::VS_Sealed;
2236 /// Parse a C++ member-declarator up to, but not including, the optional
2237 /// brace-or-equal-initializer or pure-specifier.
2238 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2239 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2240 LateParsedAttrList &LateParsedAttrs) {
2241 // member-declarator:
2242 // declarator pure-specifier[opt]
2243 // declarator brace-or-equal-initializer[opt]
2244 // identifier[opt] ':' constant-expression
2245 if (Tok.isNot(tok::colon))
2246 ParseDeclarator(DeclaratorInfo);
2248 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2250 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2251 assert(DeclaratorInfo.isPastIdentifier() &&
2252 "don't know where identifier would go yet?");
2253 BitfieldSize = ParseConstantExpression();
2254 if (BitfieldSize.isInvalid())
2255 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2257 ParseOptionalCXX11VirtSpecifierSeq(
2258 VS, getCurrentClass().IsInterface,
2259 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2261 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2264 // If a simple-asm-expr is present, parse it.
2265 if (Tok.is(tok::kw_asm)) {
2267 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2268 if (AsmLabel.isInvalid())
2269 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2271 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2272 DeclaratorInfo.SetRangeEnd(Loc);
2275 // If attributes exist after the declarator, but before an '{', parse them.
2276 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2278 // For compatibility with code written to older Clang, also accept a
2279 // virt-specifier *after* the GNU attributes.
2280 if (BitfieldSize.isUnset() && VS.isUnset()) {
2281 ParseOptionalCXX11VirtSpecifierSeq(
2282 VS, getCurrentClass().IsInterface,
2283 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2284 if (!VS.isUnset()) {
2285 // If we saw any GNU-style attributes that are known to GCC followed by a
2286 // virt-specifier, issue a GCC-compat warning.
2287 for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
2288 if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
2289 Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
2291 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2295 // If this has neither a name nor a bit width, something has gone seriously
2296 // wrong. Skip until the semi-colon or }.
2297 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2298 // If so, skip until the semi-colon or a }.
2299 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2305 /// Look for declaration specifiers possibly occurring after C++11
2306 /// virt-specifier-seq and diagnose them.
2307 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2309 VirtSpecifiers &VS) {
2310 DeclSpec DS(AttrFactory);
2312 // GNU-style and C++11 attributes are not allowed here, but they will be
2313 // handled by the caller. Diagnose everything else.
2314 ParseTypeQualifierListOpt(
2315 DS, AR_NoAttributesParsed, false,
2316 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2317 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2319 D.ExtendWithDeclSpec(DS);
2321 if (D.isFunctionDeclarator()) {
2322 auto &Function = D.getFunctionTypeInfo();
2323 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2324 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2325 const char *FixItName,
2326 SourceLocation SpecLoc,
2327 unsigned* QualifierLoc) {
2328 FixItHint Insertion;
2329 if (DS.getTypeQualifiers() & TypeQual) {
2330 if (!(Function.TypeQuals & TypeQual)) {
2331 std::string Name(FixItName);
2333 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2334 Function.TypeQuals |= TypeQual;
2335 *QualifierLoc = SpecLoc.getRawEncoding();
2337 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2339 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2340 << FixItHint::CreateRemoval(SpecLoc)
2344 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2345 &Function.ConstQualifierLoc);
2346 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2347 &Function.VolatileQualifierLoc);
2348 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2349 &Function.RestrictQualifierLoc);
2352 // Parse ref-qualifiers.
2353 bool RefQualifierIsLValueRef = true;
2354 SourceLocation RefQualifierLoc;
2355 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2356 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2357 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2358 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2359 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2361 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2362 << (RefQualifierIsLValueRef ? "&" : "&&")
2363 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2364 << FixItHint::CreateRemoval(RefQualifierLoc)
2366 D.SetRangeEnd(RefQualifierLoc);
2371 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2373 /// member-declaration:
2374 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2375 /// function-definition ';'[opt]
2376 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2377 /// using-declaration [TODO]
2378 /// [C++0x] static_assert-declaration
2379 /// template-declaration
2380 /// [GNU] '__extension__' member-declaration
2382 /// member-declarator-list:
2383 /// member-declarator
2384 /// member-declarator-list ',' member-declarator
2386 /// member-declarator:
2387 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2388 /// declarator constant-initializer[opt]
2389 /// [C++11] declarator brace-or-equal-initializer[opt]
2390 /// identifier[opt] ':' constant-expression
2392 /// virt-specifier-seq:
2394 /// virt-specifier-seq virt-specifier
2404 /// constant-initializer:
2405 /// '=' constant-expression
2407 Parser::DeclGroupPtrTy
2408 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2409 ParsedAttributes &AccessAttrs,
2410 const ParsedTemplateInfo &TemplateInfo,
2411 ParsingDeclRAIIObject *TemplateDiags) {
2412 if (Tok.is(tok::at)) {
2413 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2414 Diag(Tok, diag::err_at_defs_cxx);
2416 Diag(Tok, diag::err_at_in_class);
2419 SkipUntil(tok::r_brace, StopAtSemi);
2423 // Turn on colon protection early, while parsing declspec, although there is
2424 // nothing to protect there. It prevents from false errors if error recovery
2425 // incorrectly determines where the declspec ends, as in the example:
2426 // struct A { enum class B { C }; };
2428 // struct D { A::B : C; };
2429 ColonProtectionRAIIObject X(*this);
2431 // Access declarations.
2432 bool MalformedTypeSpec = false;
2433 if (!TemplateInfo.Kind &&
2434 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2435 if (TryAnnotateCXXScopeToken())
2436 MalformedTypeSpec = true;
2439 if (Tok.isNot(tok::annot_cxxscope))
2440 isAccessDecl = false;
2441 else if (NextToken().is(tok::identifier))
2442 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2444 isAccessDecl = NextToken().is(tok::kw_operator);
2447 // Collect the scope specifier token we annotated earlier.
2449 ParseOptionalCXXScopeSpecifier(SS, nullptr,
2450 /*EnteringContext=*/false);
2452 if (SS.isInvalid()) {
2453 SkipUntil(tok::semi);
2457 // Try to parse an unqualified-id.
2458 SourceLocation TemplateKWLoc;
2460 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2461 &TemplateKWLoc, Name)) {
2462 SkipUntil(tok::semi);
2466 // TODO: recover from mistakenly-qualified operator declarations.
2467 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2468 "access declaration")) {
2469 SkipUntil(tok::semi);
2473 // FIXME: We should do something with the 'template' keyword here.
2474 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2475 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2476 /*TypenameLoc*/ SourceLocation(), SS, Name,
2477 /*EllipsisLoc*/ SourceLocation(),
2478 /*AttrList*/ ParsedAttributesView())));
2482 // static_assert-declaration. A templated static_assert declaration is
2483 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2484 if (!TemplateInfo.Kind &&
2485 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2486 SourceLocation DeclEnd;
2487 return DeclGroupPtrTy::make(
2488 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2491 if (Tok.is(tok::kw_template)) {
2492 assert(!TemplateInfo.TemplateParams &&
2493 "Nested template improperly parsed?");
2494 ObjCDeclContextSwitch ObjCDC(*this);
2495 SourceLocation DeclEnd;
2496 return DeclGroupPtrTy::make(
2497 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2498 DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
2501 // Handle: member-declaration ::= '__extension__' member-declaration
2502 if (Tok.is(tok::kw___extension__)) {
2503 // __extension__ silences extension warnings in the subexpression.
2504 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2506 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2507 TemplateInfo, TemplateDiags);
2510 ParsedAttributesWithRange attrs(AttrFactory);
2511 ParsedAttributesViewWithRange FnAttrs;
2512 // Optional C++11 attribute-specifier
2513 MaybeParseCXX11Attributes(attrs);
2514 // We need to keep these attributes for future diagnostic
2515 // before they are taken over by declaration specifier.
2516 FnAttrs.addAll(attrs.begin(), attrs.end());
2517 FnAttrs.Range = attrs.Range;
2519 MaybeParseMicrosoftAttributes(attrs);
2521 if (Tok.is(tok::kw_using)) {
2522 ProhibitAttributes(attrs);
2525 SourceLocation UsingLoc = ConsumeToken();
2527 if (Tok.is(tok::kw_namespace)) {
2528 Diag(UsingLoc, diag::err_using_namespace_in_class);
2529 SkipUntil(tok::semi, StopBeforeMatch);
2532 SourceLocation DeclEnd;
2533 // Otherwise, it must be a using-declaration or an alias-declaration.
2534 return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
2535 UsingLoc, DeclEnd, AS);
2538 // Hold late-parsed attributes so we can attach a Decl to them later.
2539 LateParsedAttrList CommonLateParsedAttrs;
2541 // decl-specifier-seq:
2542 // Parse the common declaration-specifiers piece.
2543 ParsingDeclSpec DS(*this, TemplateDiags);
2544 DS.takeAttributesFrom(attrs);
2545 if (MalformedTypeSpec)
2546 DS.SetTypeSpecError();
2548 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
2549 &CommonLateParsedAttrs);
2551 // Turn off colon protection that was set for declspec.
2554 // If we had a free-standing type definition with a missing semicolon, we
2555 // may get this far before the problem becomes obvious.
2556 if (DS.hasTagDefinition() &&
2557 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2558 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
2559 &CommonLateParsedAttrs))
2562 MultiTemplateParamsArg TemplateParams(
2563 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2565 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2567 if (TryConsumeToken(tok::semi)) {
2568 if (DS.isFriendSpecified())
2569 ProhibitAttributes(FnAttrs);
2571 RecordDecl *AnonRecord = nullptr;
2572 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2573 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2574 DS.complete(TheDecl);
2576 Decl* decls[] = {AnonRecord, TheDecl};
2577 return Actions.BuildDeclaratorGroup(decls);
2579 return Actions.ConvertDeclToDeclGroup(TheDecl);
2582 ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
2585 // Hold late-parsed attributes so we can attach a Decl to them later.
2586 LateParsedAttrList LateParsedAttrs;
2588 SourceLocation EqualLoc;
2589 SourceLocation PureSpecLoc;
2591 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2592 if (Tok.isNot(tok::equal))
2595 auto &Zero = NextToken();
2596 SmallString<8> Buffer;
2597 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2598 PP.getSpelling(Zero, Buffer) != "0")
2601 auto &After = GetLookAheadToken(2);
2602 if (!After.isOneOf(tok::semi, tok::comma) &&
2603 !(AllowDefinition &&
2604 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2607 EqualLoc = ConsumeToken();
2608 PureSpecLoc = ConsumeToken();
2612 SmallVector<Decl *, 8> DeclsInGroup;
2613 ExprResult BitfieldSize;
2614 bool ExpectSemi = true;
2616 // Parse the first declarator.
2617 if (ParseCXXMemberDeclaratorBeforeInitializer(
2618 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2619 TryConsumeToken(tok::semi);
2623 // Check for a member function definition.
2624 if (BitfieldSize.isUnset()) {
2625 // MSVC permits pure specifier on inline functions defined at class scope.
2626 // Hence check for =0 before checking for function definition.
2627 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2628 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2630 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2631 // function-definition:
2633 // In C++11, a non-function declarator followed by an open brace is a
2634 // braced-init-list for an in-class member initialization, not an
2635 // erroneous function definition.
2636 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2637 DefinitionKind = FDK_Definition;
2638 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2639 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2640 DefinitionKind = FDK_Definition;
2641 } else if (Tok.is(tok::equal)) {
2642 const Token &KW = NextToken();
2643 if (KW.is(tok::kw_default))
2644 DefinitionKind = FDK_Defaulted;
2645 else if (KW.is(tok::kw_delete))
2646 DefinitionKind = FDK_Deleted;
2649 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2651 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2652 // to a friend declaration, that declaration shall be a definition.
2653 if (DeclaratorInfo.isFunctionDeclarator() &&
2654 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2655 // Diagnose attributes that appear before decl specifier:
2656 // [[]] friend int foo();
2657 ProhibitAttributes(FnAttrs);
2660 if (DefinitionKind != FDK_Declaration) {
2661 if (!DeclaratorInfo.isFunctionDeclarator()) {
2662 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2664 SkipUntil(tok::r_brace);
2666 // Consume the optional ';'
2667 TryConsumeToken(tok::semi);
2672 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2673 Diag(DeclaratorInfo.getIdentifierLoc(),
2674 diag::err_function_declared_typedef);
2676 // Recover by treating the 'typedef' as spurious.
2677 DS.ClearStorageClassSpecs();
2681 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2685 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2686 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2688 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2689 LateParsedAttrs[i]->addDecl(FunDecl);
2692 LateParsedAttrs.clear();
2694 // Consume the ';' - it's optional unless we have a delete or default
2695 if (Tok.is(tok::semi))
2696 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2698 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2702 // member-declarator-list:
2703 // member-declarator
2704 // member-declarator-list ',' member-declarator
2707 InClassInitStyle HasInClassInit = ICIS_NoInit;
2708 bool HasStaticInitializer = false;
2709 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2710 if (DeclaratorInfo.isDeclarationOfFunction()) {
2711 // It's a pure-specifier.
2712 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2713 // Parse it as an expression so that Sema can diagnose it.
2714 HasStaticInitializer = true;
2715 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2716 DeclSpec::SCS_static &&
2717 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2718 DeclSpec::SCS_typedef &&
2719 !DS.isFriendSpecified()) {
2720 // It's a default member initializer.
2721 if (BitfieldSize.get())
2722 Diag(Tok, getLangOpts().CPlusPlus2a
2723 ? diag::warn_cxx17_compat_bitfield_member_init
2724 : diag::ext_bitfield_member_init);
2725 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2727 HasStaticInitializer = true;
2731 // NOTE: If Sema is the Action module and declarator is an instance field,
2732 // this call will *not* return the created decl; It will return null.
2733 // See Sema::ActOnCXXMemberDeclarator for details.
2735 NamedDecl *ThisDecl = nullptr;
2736 if (DS.isFriendSpecified()) {
2737 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2738 // to a friend declaration, that declaration shall be a definition.
2740 // Diagnose attributes that appear in a friend member function declarator:
2741 // friend int foo [[]] ();
2742 SmallVector<SourceRange, 4> Ranges;
2743 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2744 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2745 E = Ranges.end(); I != E; ++I)
2746 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2748 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2751 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2755 VS, HasInClassInit);
2757 if (VarTemplateDecl *VT =
2758 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2759 // Re-direct this decl to refer to the templated decl so that we can
2761 ThisDecl = VT->getTemplatedDecl();
2764 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2767 // Error recovery might have converted a non-static member into a static
2769 if (HasInClassInit != ICIS_NoInit &&
2770 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2771 DeclSpec::SCS_static) {
2772 HasInClassInit = ICIS_NoInit;
2773 HasStaticInitializer = true;
2776 if (ThisDecl && PureSpecLoc.isValid())
2777 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2779 // Handle the initializer.
2780 if (HasInClassInit != ICIS_NoInit) {
2781 // The initializer was deferred; parse it and cache the tokens.
2782 Diag(Tok, getLangOpts().CPlusPlus11
2783 ? diag::warn_cxx98_compat_nonstatic_member_init
2784 : diag::ext_nonstatic_member_init);
2786 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2787 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2788 // declarator is followed by an initializer.
2790 // A brace-or-equal-initializer for a member-declarator is not an
2791 // initializer in the grammar, so this is ill-formed.
2792 Diag(Tok, diag::err_incomplete_array_member_init);
2793 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2795 // Avoid later warnings about a class member of incomplete type.
2797 ThisDecl->setInvalidDecl();
2799 ParseCXXNonStaticMemberInitializer(ThisDecl);
2800 } else if (HasStaticInitializer) {
2801 // Normal initializer.
2802 ExprResult Init = ParseCXXMemberInitializer(
2803 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2805 if (Init.isInvalid())
2806 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2808 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
2809 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2811 Actions.ActOnUninitializedDecl(ThisDecl);
2814 if (!ThisDecl->isInvalidDecl()) {
2815 // Set the Decl for any late parsed attributes
2816 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2817 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2819 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2820 LateParsedAttrs[i]->addDecl(ThisDecl);
2822 Actions.FinalizeDeclaration(ThisDecl);
2823 DeclsInGroup.push_back(ThisDecl);
2825 if (DeclaratorInfo.isFunctionDeclarator() &&
2826 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2827 DeclSpec::SCS_typedef)
2828 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2830 LateParsedAttrs.clear();
2832 DeclaratorInfo.complete(ThisDecl);
2834 // If we don't have a comma, it is either the end of the list (a ';')
2835 // or an error, bail out.
2836 SourceLocation CommaLoc;
2837 if (!TryConsumeToken(tok::comma, CommaLoc))
2840 if (Tok.isAtStartOfLine() &&
2841 !MightBeDeclarator(DeclaratorContext::MemberContext)) {
2842 // This comma was followed by a line-break and something which can't be
2843 // the start of a declarator. The comma was probably a typo for a
2845 Diag(CommaLoc, diag::err_expected_semi_declaration)
2846 << FixItHint::CreateReplacement(CommaLoc, ";");
2851 // Parse the next declarator.
2852 DeclaratorInfo.clear();
2854 BitfieldSize = ExprResult(/*Invalid=*/false);
2855 EqualLoc = PureSpecLoc = SourceLocation();
2856 DeclaratorInfo.setCommaLoc(CommaLoc);
2858 // GNU attributes are allowed before the second and subsequent declarator.
2859 MaybeParseGNUAttributes(DeclaratorInfo);
2861 if (ParseCXXMemberDeclaratorBeforeInitializer(
2862 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2867 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2868 // Skip to end of block or statement.
2869 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2870 // If we stopped at a ';', eat it.
2871 TryConsumeToken(tok::semi);
2875 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2878 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2879 /// Also detect and reject any attempted defaulted/deleted function definition.
2880 /// The location of the '=', if any, will be placed in EqualLoc.
2882 /// This does not check for a pure-specifier; that's handled elsewhere.
2884 /// brace-or-equal-initializer:
2885 /// '=' initializer-expression
2886 /// braced-init-list
2888 /// initializer-clause:
2889 /// assignment-expression
2890 /// braced-init-list
2892 /// defaulted/deleted function-definition:
2896 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2897 /// be a constant-expression.
2898 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2899 SourceLocation &EqualLoc) {
2900 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2901 && "Data member initializer not starting with '=' or '{'");
2903 EnterExpressionEvaluationContext Context(
2904 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
2905 if (TryConsumeToken(tok::equal, EqualLoc)) {
2906 if (Tok.is(tok::kw_delete)) {
2907 // In principle, an initializer of '= delete p;' is legal, but it will
2908 // never type-check. It's better to diagnose it as an ill-formed expression
2909 // than as an ill-formed deleted non-function member.
2910 // An initializer of '= delete p, foo' will never be parsed, because
2911 // a top-level comma always ends the initializer expression.
2912 const Token &Next = NextToken();
2913 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2915 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2918 Diag(ConsumeToken(), diag::err_deleted_non_function);
2921 } else if (Tok.is(tok::kw_default)) {
2923 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2926 Diag(ConsumeToken(), diag::err_default_special_members);
2930 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2931 Diag(Tok, diag::err_ms_property_initializer) << PD;
2934 return ParseInitializer();
2937 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2938 SourceLocation AttrFixitLoc,
2939 unsigned TagType, Decl *TagDecl) {
2940 // Skip the optional 'final' keyword.
2941 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2942 assert(isCXX11FinalKeyword() && "not a class definition");
2945 // Diagnose any C++11 attributes after 'final' keyword.
2946 // We deliberately discard these attributes.
2947 ParsedAttributesWithRange Attrs(AttrFactory);
2948 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2950 // This can only happen if we had malformed misplaced attributes;
2951 // we only get called if there is a colon or left-brace after the
2953 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2957 // Skip the base clauses. This requires actually parsing them, because
2958 // otherwise we can't be sure where they end (a left brace may appear
2959 // within a template argument).
2960 if (Tok.is(tok::colon)) {
2961 // Enter the scope of the class so that we can correctly parse its bases.
2962 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2963 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2964 TagType == DeclSpec::TST_interface);
2966 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2968 // Parse the bases but don't attach them to the class.
2969 ParseBaseClause(nullptr);
2971 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2973 if (!Tok.is(tok::l_brace)) {
2974 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2975 diag::err_expected_lbrace_after_base_specifiers);
2981 assert(Tok.is(tok::l_brace));
2982 BalancedDelimiterTracker T(*this, tok::l_brace);
2986 // Parse and discard any trailing attributes.
2987 ParsedAttributes Attrs(AttrFactory);
2988 if (Tok.is(tok::kw___attribute))
2989 MaybeParseGNUAttributes(Attrs);
2992 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
2993 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2994 DeclSpec::TST TagType, Decl *TagDecl) {
2995 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2997 switch (Tok.getKind()) {
2998 case tok::kw___if_exists:
2999 case tok::kw___if_not_exists:
3000 ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
3004 // Check for extraneous top-level semicolon.
3005 ConsumeExtraSemi(InsideStruct, TagType);
3008 // Handle pragmas that can appear as member declarations.
3009 case tok::annot_pragma_vis:
3010 HandlePragmaVisibility();
3012 case tok::annot_pragma_pack:
3015 case tok::annot_pragma_align:
3016 HandlePragmaAlign();
3018 case tok::annot_pragma_ms_pointers_to_members:
3019 HandlePragmaMSPointersToMembers();
3021 case tok::annot_pragma_ms_pragma:
3022 HandlePragmaMSPragma();
3024 case tok::annot_pragma_ms_vtordisp:
3025 HandlePragmaMSVtorDisp();
3027 case tok::annot_pragma_dump:
3031 case tok::kw_namespace:
3032 // If we see a namespace here, a close brace was missing somewhere.
3033 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3036 case tok::kw_public:
3037 case tok::kw_protected:
3038 case tok::kw_private: {
3039 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3040 assert(NewAS != AS_none);
3041 // Current token is a C++ access specifier.
3043 SourceLocation ASLoc = Tok.getLocation();
3044 unsigned TokLength = Tok.getLength();
3046 AccessAttrs.clear();
3047 MaybeParseGNUAttributes(AccessAttrs);
3049 SourceLocation EndLoc;
3050 if (TryConsumeToken(tok::colon, EndLoc)) {
3051 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3052 Diag(EndLoc, diag::err_expected)
3053 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3055 EndLoc = ASLoc.getLocWithOffset(TokLength);
3056 Diag(EndLoc, diag::err_expected)
3057 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3060 // The Microsoft extension __interface does not permit non-public
3061 // access specifiers.
3062 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3063 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3066 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
3067 // found another attribute than only annotations
3068 AccessAttrs.clear();
3074 case tok::annot_pragma_openmp:
3075 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3079 return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
3083 /// ParseCXXMemberSpecification - Parse the class definition.
3085 /// member-specification:
3086 /// member-declaration member-specification[opt]
3087 /// access-specifier ':' member-specification[opt]
3089 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3090 SourceLocation AttrFixitLoc,
3091 ParsedAttributesWithRange &Attrs,
3092 unsigned TagType, Decl *TagDecl) {
3093 assert((TagType == DeclSpec::TST_struct ||
3094 TagType == DeclSpec::TST_interface ||
3095 TagType == DeclSpec::TST_union ||
3096 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3098 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
3099 "parsing struct/union/class body");
3101 // Determine whether this is a non-nested class. Note that local
3102 // classes are *not* considered to be nested classes.
3103 bool NonNestedClass = true;
3104 if (!ClassStack.empty()) {
3105 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
3106 if (S->isClassScope()) {
3107 // We're inside a class scope, so this is a nested class.
3108 NonNestedClass = false;
3110 // The Microsoft extension __interface does not permit nested classes.
3111 if (getCurrentClass().IsInterface) {
3112 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3114 << (isa<NamedDecl>(TagDecl)
3115 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3121 if ((S->getFlags() & Scope::FnScope))
3122 // If we're in a function or function template then this is a local
3123 // class rather than a nested class.
3128 // Enter a scope for the class.
3129 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3131 // Note that we are parsing a new (potentially-nested) class definition.
3132 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3133 TagType == DeclSpec::TST_interface);
3136 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3138 SourceLocation FinalLoc;
3139 bool IsFinalSpelledSealed = false;
3141 // Parse the optional 'final' keyword.
3142 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3143 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3144 assert((Specifier == VirtSpecifiers::VS_Final ||
3145 Specifier == VirtSpecifiers::VS_GNU_Final ||
3146 Specifier == VirtSpecifiers::VS_Sealed) &&
3147 "not a class definition");
3148 FinalLoc = ConsumeToken();
3149 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
3151 if (TagType == DeclSpec::TST_interface)
3152 Diag(FinalLoc, diag::err_override_control_interface)
3153 << VirtSpecifiers::getSpecifierName(Specifier);
3154 else if (Specifier == VirtSpecifiers::VS_Final)
3155 Diag(FinalLoc, getLangOpts().CPlusPlus11
3156 ? diag::warn_cxx98_compat_override_control_keyword
3157 : diag::ext_override_control_keyword)
3158 << VirtSpecifiers::getSpecifierName(Specifier);
3159 else if (Specifier == VirtSpecifiers::VS_Sealed)
3160 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3161 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3162 Diag(FinalLoc, diag::ext_warn_gnu_final);
3164 // Parse any C++11 attributes after 'final' keyword.
3165 // These attributes are not allowed to appear here,
3166 // and the only possible place for them to appertain
3167 // to the class would be between class-key and class-name.
3168 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3170 // ParseClassSpecifier() does only a superficial check for attributes before
3171 // deciding to call this method. For example, for
3172 // `class C final alignas ([l) {` it will decide that this looks like a
3173 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3174 // attribute parsing code will try to parse the '[' as a constexpr lambda
3175 // and consume enough tokens that the alignas parsing code will eat the
3176 // opening '{'. So bail out if the next token isn't one we expect.
3177 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3179 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3184 if (Tok.is(tok::colon)) {
3185 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3186 Scope::ClassInheritanceScope);
3188 ParseBaseClause(TagDecl);
3189 if (!Tok.is(tok::l_brace)) {
3190 bool SuggestFixIt = false;
3191 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3192 if (Tok.isAtStartOfLine()) {
3193 switch (Tok.getKind()) {
3194 case tok::kw_private:
3195 case tok::kw_protected:
3196 case tok::kw_public:
3197 SuggestFixIt = NextToken().getKind() == tok::colon;
3199 case tok::kw_static_assert:
3202 // base-clause can have simple-template-id; 'template' can't be there
3203 case tok::kw_template:
3204 SuggestFixIt = true;
3206 case tok::identifier:
3207 SuggestFixIt = isConstructorDeclarator(true);
3210 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3214 DiagnosticBuilder LBraceDiag =
3215 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3217 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3218 // Try recovering from missing { after base-clause.
3220 Tok.setKind(tok::l_brace);
3223 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3229 assert(Tok.is(tok::l_brace));
3230 BalancedDelimiterTracker T(*this, tok::l_brace);
3234 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3235 IsFinalSpelledSealed,
3236 T.getOpenLocation());
3238 // C++ 11p3: Members of a class defined with the keyword class are private
3239 // by default. Members of a class defined with the keywords struct or union
3240 // are public by default.
3241 AccessSpecifier CurAS;
3242 if (TagType == DeclSpec::TST_class)
3246 ParsedAttributesWithRange AccessAttrs(AttrFactory);
3249 // While we still have something to read, read the member-declarations.
3250 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3251 Tok.isNot(tok::eof)) {
3252 // Each iteration of this loop reads one member-declaration.
3253 ParseCXXClassMemberDeclarationWithPragmas(
3254 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3258 SkipUntil(tok::r_brace);
3261 // If attributes exist after class contents, parse them.
3262 ParsedAttributes attrs(AttrFactory);
3263 MaybeParseGNUAttributes(attrs);
3266 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3267 T.getOpenLocation(),
3268 T.getCloseLocation(), attrs);
3270 // C++11 [class.mem]p2:
3271 // Within the class member-specification, the class is regarded as complete
3272 // within function bodies, default arguments, exception-specifications, and
3273 // brace-or-equal-initializers for non-static data members (including such
3274 // things in nested classes).
3275 if (TagDecl && NonNestedClass) {
3276 // We are not inside a nested class. This class and its nested classes
3277 // are complete and we can parse the delayed portions of method
3278 // declarations and the lexed inline method definitions, along with any
3279 // delayed attributes.
3280 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3281 ParseLexedAttributes(getCurrentClass());
3282 ParseLexedMethodDeclarations(getCurrentClass());
3284 // We've finished with all pending member declarations.
3285 Actions.ActOnFinishCXXMemberDecls();
3287 ParseLexedMemberInitializers(getCurrentClass());
3288 ParseLexedMethodDefs(getCurrentClass());
3289 PrevTokLocation = SavedPrevTokLocation;
3291 // We've finished parsing everything, including default argument
3293 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3297 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3299 // Leave the class scope.
3304 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3305 assert(Tok.is(tok::kw_namespace));
3307 // FIXME: Suggest where the close brace should have gone by looking
3308 // at indentation changes within the definition body.
3309 Diag(D->getLocation(),
3310 diag::err_missing_end_of_definition) << D;
3311 Diag(Tok.getLocation(),
3312 diag::note_missing_end_of_definition_before) << D;
3314 // Push '};' onto the token stream to recover.
3318 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3319 Tok.setKind(tok::semi);
3322 Tok.setKind(tok::r_brace);
3325 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3326 /// which explicitly initializes the members or base classes of a
3327 /// class (C++ [class.base.init]). For example, the three initializers
3328 /// after the ':' in the Derived constructor below:
3332 /// class Derived : Base {
3336 /// Derived(float f) : Base(), x(17), f(f) { }
3340 /// [C++] ctor-initializer:
3341 /// ':' mem-initializer-list
3343 /// [C++] mem-initializer-list:
3344 /// mem-initializer ...[opt]
3345 /// mem-initializer ...[opt] , mem-initializer-list
3346 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3347 assert(Tok.is(tok::colon) &&
3348 "Constructor initializer always starts with ':'");
3350 // Poison the SEH identifiers so they are flagged as illegal in constructor
3352 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3353 SourceLocation ColonLoc = ConsumeToken();
3355 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3356 bool AnyErrors = false;
3359 if (Tok.is(tok::code_completion)) {
3360 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3362 return cutOffParsing();
3365 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3366 if (!MemInit.isInvalid())
3367 MemInitializers.push_back(MemInit.get());
3371 if (Tok.is(tok::comma))
3373 else if (Tok.is(tok::l_brace))
3375 // If the previous initializer was valid and the next token looks like a
3376 // base or member initializer, assume that we're just missing a comma.
3377 else if (!MemInit.isInvalid() &&
3378 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3379 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3380 Diag(Loc, diag::err_ctor_init_missing_comma)
3381 << FixItHint::CreateInsertion(Loc, ", ");
3383 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3384 if (!MemInit.isInvalid())
3385 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3387 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3392 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3396 /// ParseMemInitializer - Parse a C++ member initializer, which is
3397 /// part of a constructor initializer that explicitly initializes one
3398 /// member or base class (C++ [class.base.init]). See
3399 /// ParseConstructorInitializer for an example.
3401 /// [C++] mem-initializer:
3402 /// mem-initializer-id '(' expression-list[opt] ')'
3403 /// [C++0x] mem-initializer-id braced-init-list
3405 /// [C++] mem-initializer-id:
3406 /// '::'[opt] nested-name-specifier[opt] class-name
3408 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3409 // parse '::'[opt] nested-name-specifier[opt]
3411 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
3414 IdentifierInfo *II = nullptr;
3415 SourceLocation IdLoc = Tok.getLocation();
3417 DeclSpec DS(AttrFactory);
3418 // : template_name<...>
3419 ParsedType TemplateTypeTy;
3421 if (Tok.is(tok::identifier)) {
3422 // Get the identifier. This may be a member name or a class name,
3423 // but we'll let the semantic analysis determine which it is.
3424 II = Tok.getIdentifierInfo();
3426 } else if (Tok.is(tok::annot_decltype)) {
3427 // Get the decltype expression, if there is one.
3428 // Uses of decltype will already have been converted to annot_decltype by
3429 // ParseOptionalCXXScopeSpecifier at this point.
3430 // FIXME: Can we get here with a scope specifier?
3431 ParseDecltypeSpecifier(DS);
3433 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3434 ? takeTemplateIdAnnotation(Tok)
3436 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3437 TemplateId->Kind == TNK_Dependent_template_name)) {
3438 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
3439 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3440 TemplateTypeTy = getTypeAnnotation(Tok);
3441 ConsumeAnnotationToken();
3443 Diag(Tok, diag::err_expected_member_or_base_name);
3449 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3450 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3452 ExprResult InitList = ParseBraceInitializer();
3453 if (InitList.isInvalid())
3456 SourceLocation EllipsisLoc;
3457 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3459 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3460 TemplateTypeTy, DS, IdLoc,
3461 InitList.get(), EllipsisLoc);
3462 } else if(Tok.is(tok::l_paren)) {
3463 BalancedDelimiterTracker T(*this, tok::l_paren);
3466 // Parse the optional expression-list.
3467 ExprVector ArgExprs;
3468 CommaLocsTy CommaLocs;
3469 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
3470 SkipUntil(tok::r_paren, StopAtSemi);
3476 SourceLocation EllipsisLoc;
3477 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3479 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3480 TemplateTypeTy, DS, IdLoc,
3481 T.getOpenLocation(), ArgExprs,
3482 T.getCloseLocation(), EllipsisLoc);
3485 if (getLangOpts().CPlusPlus11)
3486 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3488 return Diag(Tok, diag::err_expected) << tok::l_paren;
3491 /// Parse a C++ exception-specification if present (C++0x [except.spec]).
3493 /// exception-specification:
3494 /// dynamic-exception-specification
3495 /// noexcept-specification
3497 /// noexcept-specification:
3499 /// 'noexcept' '(' constant-expression ')'
3500 ExceptionSpecificationType
3501 Parser::tryParseExceptionSpecification(bool Delayed,
3502 SourceRange &SpecificationRange,
3503 SmallVectorImpl<ParsedType> &DynamicExceptions,
3504 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3505 ExprResult &NoexceptExpr,
3506 CachedTokens *&ExceptionSpecTokens) {
3507 ExceptionSpecificationType Result = EST_None;
3508 ExceptionSpecTokens = nullptr;
3510 // Handle delayed parsing of exception-specifications.
3512 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3515 // Consume and cache the starting token.
3516 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3517 Token StartTok = Tok;
3518 SpecificationRange = SourceRange(ConsumeToken());
3521 if (!Tok.is(tok::l_paren)) {
3522 // If this is a bare 'noexcept', we're done.
3524 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3525 NoexceptExpr = nullptr;
3526 return EST_BasicNoexcept;
3529 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3530 return EST_DynamicNone;
3533 // Cache the tokens for the exception-specification.
3534 ExceptionSpecTokens = new CachedTokens;
3535 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3536 ExceptionSpecTokens->push_back(Tok); // '('
3537 SpecificationRange.setEnd(ConsumeParen()); // '('
3539 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3540 /*StopAtSemi=*/true,
3541 /*ConsumeFinalToken=*/true);
3542 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3544 return EST_Unparsed;
3547 // See if there's a dynamic specification.
3548 if (Tok.is(tok::kw_throw)) {
3549 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3551 DynamicExceptionRanges);
3552 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3553 "Produced different number of exception types and ranges.");
3556 // If there's no noexcept specification, we're done.
3557 if (Tok.isNot(tok::kw_noexcept))
3560 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3562 // If we already had a dynamic specification, parse the noexcept for,
3563 // recovery, but emit a diagnostic and don't store the results.
3564 SourceRange NoexceptRange;
3565 ExceptionSpecificationType NoexceptType = EST_None;
3567 SourceLocation KeywordLoc = ConsumeToken();
3568 if (Tok.is(tok::l_paren)) {
3569 // There is an argument.
3570 BalancedDelimiterTracker T(*this, tok::l_paren);
3572 NoexceptExpr = ParseConstantExpression();
3574 if (!NoexceptExpr.isInvalid()) {
3575 NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
3577 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3579 NoexceptType = EST_BasicNoexcept;
3582 // There is no argument.
3583 NoexceptType = EST_BasicNoexcept;
3584 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3587 if (Result == EST_None) {
3588 SpecificationRange = NoexceptRange;
3589 Result = NoexceptType;
3591 // If there's a dynamic specification after a noexcept specification,
3592 // parse that and ignore the results.
3593 if (Tok.is(tok::kw_throw)) {
3594 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3595 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3596 DynamicExceptionRanges);
3599 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3605 static void diagnoseDynamicExceptionSpecification(
3606 Parser &P, SourceRange Range, bool IsNoexcept) {
3607 if (P.getLangOpts().CPlusPlus11) {
3608 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3609 P.Diag(Range.getBegin(),
3610 P.getLangOpts().CPlusPlus17 && !IsNoexcept
3611 ? diag::ext_dynamic_exception_spec
3612 : diag::warn_exception_spec_deprecated)
3614 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3615 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3619 /// ParseDynamicExceptionSpecification - Parse a C++
3620 /// dynamic-exception-specification (C++ [except.spec]).
3622 /// dynamic-exception-specification:
3623 /// 'throw' '(' type-id-list [opt] ')'
3624 /// [MS] 'throw' '(' '...' ')'
3627 /// type-id ... [opt]
3628 /// type-id-list ',' type-id ... [opt]
3630 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3631 SourceRange &SpecificationRange,
3632 SmallVectorImpl<ParsedType> &Exceptions,
3633 SmallVectorImpl<SourceRange> &Ranges) {
3634 assert(Tok.is(tok::kw_throw) && "expected throw");
3636 SpecificationRange.setBegin(ConsumeToken());
3637 BalancedDelimiterTracker T(*this, tok::l_paren);
3638 if (T.consumeOpen()) {
3639 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3640 SpecificationRange.setEnd(SpecificationRange.getBegin());
3641 return EST_DynamicNone;
3644 // Parse throw(...), a Microsoft extension that means "this function
3645 // can throw anything".
3646 if (Tok.is(tok::ellipsis)) {
3647 SourceLocation EllipsisLoc = ConsumeToken();
3648 if (!getLangOpts().MicrosoftExt)
3649 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3651 SpecificationRange.setEnd(T.getCloseLocation());
3652 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3656 // Parse the sequence of type-ids.
3658 while (Tok.isNot(tok::r_paren)) {
3659 TypeResult Res(ParseTypeName(&Range));
3661 if (Tok.is(tok::ellipsis)) {
3662 // C++0x [temp.variadic]p5:
3663 // - In a dynamic-exception-specification (15.4); the pattern is a
3665 SourceLocation Ellipsis = ConsumeToken();
3666 Range.setEnd(Ellipsis);
3667 if (!Res.isInvalid())
3668 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3671 if (!Res.isInvalid()) {
3672 Exceptions.push_back(Res.get());
3673 Ranges.push_back(Range);
3676 if (!TryConsumeToken(tok::comma))
3681 SpecificationRange.setEnd(T.getCloseLocation());
3682 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3683 Exceptions.empty());
3684 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3687 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3688 /// function declaration.
3689 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
3690 bool MayBeFollowedByDirectInit) {
3691 assert(Tok.is(tok::arrow) && "expected arrow");
3695 return ParseTypeName(&Range, MayBeFollowedByDirectInit
3696 ? DeclaratorContext::TrailingReturnVarContext
3697 : DeclaratorContext::TrailingReturnContext);
3700 /// We have just started parsing the definition of a new class,
3701 /// so push that class onto our stack of classes that is currently
3703 Sema::ParsingClassState
3704 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3706 assert((NonNestedClass || !ClassStack.empty()) &&
3707 "Nested class without outer class");
3708 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3709 return Actions.PushParsingClass();
3712 /// Deallocate the given parsed class and all of its nested
3714 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3715 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3716 delete Class->LateParsedDeclarations[I];
3720 /// Pop the top class of the stack of classes that are
3721 /// currently being parsed.
3723 /// This routine should be called when we have finished parsing the
3724 /// definition of a class, but have not yet popped the Scope
3725 /// associated with the class's definition.
3726 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3727 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3729 Actions.PopParsingClass(state);
3731 ParsingClass *Victim = ClassStack.top();
3733 if (Victim->TopLevelClass) {
3734 // Deallocate all of the nested classes of this class,
3735 // recursively: we don't need to keep any of this information.
3736 DeallocateParsedClasses(Victim);
3739 assert(!ClassStack.empty() && "Missing top-level class?");
3741 if (Victim->LateParsedDeclarations.empty()) {
3742 // The victim is a nested class, but we will not need to perform
3743 // any processing after the definition of this class since it has
3744 // no members whose handling was delayed. Therefore, we can just
3745 // remove this nested class.
3746 DeallocateParsedClasses(Victim);
3750 // This nested class has some members that will need to be processed
3751 // after the top-level class is completely defined. Therefore, add
3752 // it to the list of nested classes within its parent.
3753 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3754 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3755 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3758 /// Try to parse an 'identifier' which appears within an attribute-token.
3760 /// \return the parsed identifier on success, and 0 if the next token is not an
3761 /// attribute-token.
3763 /// C++11 [dcl.attr.grammar]p3:
3764 /// If a keyword or an alternative token that satisfies the syntactic
3765 /// requirements of an identifier is contained in an attribute-token,
3766 /// it is considered an identifier.
3767 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3768 switch (Tok.getKind()) {
3770 // Identifiers and keywords have identifier info attached.
3771 if (!Tok.isAnnotation()) {
3772 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3773 Loc = ConsumeToken();
3779 case tok::ampamp: // 'and'
3780 case tok::pipe: // 'bitor'
3781 case tok::pipepipe: // 'or'
3782 case tok::caret: // 'xor'
3783 case tok::tilde: // 'compl'
3784 case tok::amp: // 'bitand'
3785 case tok::ampequal: // 'and_eq'
3786 case tok::pipeequal: // 'or_eq'
3787 case tok::caretequal: // 'xor_eq'
3788 case tok::exclaim: // 'not'
3789 case tok::exclaimequal: // 'not_eq'
3790 // Alternative tokens do not have identifier info, but their spelling
3791 // starts with an alphabetical character.
3792 SmallString<8> SpellingBuf;
3793 SourceLocation SpellingLoc =
3794 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3795 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3796 if (isLetter(Spelling[0])) {
3797 Loc = ConsumeToken();
3798 return &PP.getIdentifierTable().get(Spelling);
3804 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3805 IdentifierInfo *ScopeName) {
3806 switch (ParsedAttr::getKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
3807 case ParsedAttr::AT_CarriesDependency:
3808 case ParsedAttr::AT_Deprecated:
3809 case ParsedAttr::AT_FallThrough:
3810 case ParsedAttr::AT_CXX11NoReturn:
3812 case ParsedAttr::AT_WarnUnusedResult:
3813 return !ScopeName && AttrName->getName().equals("nodiscard");
3814 case ParsedAttr::AT_Unused:
3815 return !ScopeName && AttrName->getName().equals("maybe_unused");
3821 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3823 /// [C++11] attribute-argument-clause:
3824 /// '(' balanced-token-seq ')'
3826 /// [C++11] balanced-token-seq:
3828 /// balanced-token-seq balanced-token
3830 /// [C++11] balanced-token:
3831 /// '(' balanced-token-seq ')'
3832 /// '[' balanced-token-seq ']'
3833 /// '{' balanced-token-seq '}'
3834 /// any token but '(', ')', '[', ']', '{', or '}'
3835 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3836 SourceLocation AttrNameLoc,
3837 ParsedAttributes &Attrs,
3838 SourceLocation *EndLoc,
3839 IdentifierInfo *ScopeName,
3840 SourceLocation ScopeLoc) {
3841 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3842 SourceLocation LParenLoc = Tok.getLocation();
3843 const LangOptions &LO = getLangOpts();
3844 ParsedAttr::Syntax Syntax =
3845 LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
3847 // If the attribute isn't known, we will not attempt to parse any
3849 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3850 AttrName, getTargetInfo(), getLangOpts())) {
3851 // Eat the left paren, then skip to the ending right paren.
3853 SkipUntil(tok::r_paren);
3857 if (ScopeName && ScopeName->getName() == "gnu") {
3858 // GNU-scoped attributes have some special cases to handle GNU-specific
3860 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3861 ScopeLoc, Syntax, nullptr);
3866 // Some Clang-scoped attributes have some special parsing behavior.
3867 if (ScopeName && ScopeName->getName() == "clang")
3869 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3873 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3874 ScopeName, ScopeLoc, Syntax);
3876 if (!Attrs.empty() &&
3877 IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3878 ParsedAttr &Attr = *Attrs.begin();
3879 // If the attribute is a standard or built-in attribute and we are
3880 // parsing an argument list, we need to determine whether this attribute
3881 // was allowed to have an argument list (such as [[deprecated]]), and how
3882 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3883 if (Attr.getMaxArgs() && !NumArgs) {
3884 // The attribute was allowed to have arguments, but none were provided
3885 // even though the attribute parsed successfully. This is an error.
3886 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3887 Attr.setInvalid(true);
3888 } else if (!Attr.getMaxArgs()) {
3889 // The attribute parsed successfully, but was not allowed to have any
3890 // arguments. It doesn't matter whether any were provided -- the
3891 // presence of the argument list (even if empty) is diagnosed.
3892 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3894 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3895 Attr.setInvalid(true);
3901 /// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
3903 /// [C++11] attribute-specifier:
3904 /// '[' '[' attribute-list ']' ']'
3905 /// alignment-specifier
3907 /// [C++11] attribute-list:
3909 /// attribute-list ',' attribute[opt]
3911 /// attribute-list ',' attribute '...'
3913 /// [C++11] attribute:
3914 /// attribute-token attribute-argument-clause[opt]
3916 /// [C++11] attribute-token:
3918 /// attribute-scoped-token
3920 /// [C++11] attribute-scoped-token:
3921 /// attribute-namespace '::' identifier
3923 /// [C++11] attribute-namespace:
3925 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3926 SourceLocation *endLoc) {
3927 if (Tok.is(tok::kw_alignas)) {
3928 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3929 ParseAlignmentSpecifier(attrs, endLoc);
3933 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3934 "Not a double square bracket attribute list");
3936 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3941 SourceLocation CommonScopeLoc;
3942 IdentifierInfo *CommonScopeName = nullptr;
3943 if (Tok.is(tok::kw_using)) {
3944 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
3945 ? diag::warn_cxx14_compat_using_attribute_ns
3946 : diag::ext_using_attribute_ns);
3949 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3950 if (!CommonScopeName) {
3951 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3952 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3954 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3955 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3958 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3960 while (Tok.isNot(tok::r_square)) {
3961 // attribute not present
3962 if (TryConsumeToken(tok::comma))
3965 SourceLocation ScopeLoc, AttrLoc;
3966 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3968 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3970 // Break out to the "expected ']'" diagnostic.
3974 if (TryConsumeToken(tok::coloncolon)) {
3975 ScopeName = AttrName;
3978 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3980 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3981 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3986 if (CommonScopeName) {
3988 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
3989 << SourceRange(CommonScopeLoc);
3991 ScopeName = CommonScopeName;
3992 ScopeLoc = CommonScopeLoc;
3996 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
3997 bool AttrParsed = false;
4000 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4001 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
4002 << AttrName << SourceRange(SeenAttrs[AttrName]);
4004 // Parse attribute arguments
4005 if (Tok.is(tok::l_paren))
4006 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4007 ScopeName, ScopeLoc);
4012 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4013 ScopeName, ScopeLoc, nullptr, 0,
4014 getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
4016 if (TryConsumeToken(tok::ellipsis))
4017 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4021 if (ExpectAndConsume(tok::r_square))
4022 SkipUntil(tok::r_square);
4024 *endLoc = Tok.getLocation();
4025 if (ExpectAndConsume(tok::r_square))
4026 SkipUntil(tok::r_square);
4029 /// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
4031 /// attribute-specifier-seq:
4032 /// attribute-specifier-seq[opt] attribute-specifier
4033 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
4034 SourceLocation *endLoc) {
4035 assert(standardAttributesAllowed());
4037 SourceLocation StartLoc = Tok.getLocation(), Loc;
4042 ParseCXX11AttributeSpecifier(attrs, endLoc);
4043 } while (isCXX11AttributeSpecifier());
4045 attrs.Range = SourceRange(StartLoc, *endLoc);
4048 void Parser::DiagnoseAndSkipCXX11Attributes() {
4049 // Start and end location of an attribute or an attribute list.
4050 SourceLocation StartLoc = Tok.getLocation();
4051 SourceLocation EndLoc = SkipCXX11Attributes();
4053 if (EndLoc.isValid()) {
4054 SourceRange Range(StartLoc, EndLoc);
4055 Diag(StartLoc, diag::err_attributes_not_allowed)
4060 SourceLocation Parser::SkipCXX11Attributes() {
4061 SourceLocation EndLoc;
4063 if (!isCXX11AttributeSpecifier())
4067 if (Tok.is(tok::l_square)) {
4068 BalancedDelimiterTracker T(*this, tok::l_square);
4071 EndLoc = T.getCloseLocation();
4073 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4075 BalancedDelimiterTracker T(*this, tok::l_paren);
4076 if (!T.consumeOpen())
4078 EndLoc = T.getCloseLocation();
4080 } while (isCXX11AttributeSpecifier());
4085 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4086 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4087 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4088 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4089 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4091 SourceLocation UuidLoc = Tok.getLocation();
4094 // Ignore the left paren location for now.
4095 BalancedDelimiterTracker T(*this, tok::l_paren);
4096 if (T.consumeOpen()) {
4097 Diag(Tok, diag::err_expected) << tok::l_paren;
4101 ArgsVector ArgExprs;
4102 if (Tok.is(tok::string_literal)) {
4103 // Easy case: uuid("...") -- quoted string.
4104 ExprResult StringResult = ParseStringLiteralExpression();
4105 if (StringResult.isInvalid())
4107 ArgExprs.push_back(StringResult.get());
4109 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4110 // quotes in the parens. Just append the spelling of all tokens encountered
4111 // until the closing paren.
4113 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4116 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4117 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4118 // tok::numeric_constant (0000) should be enough. But the spelling of the
4119 // uuid argument is checked later anyways, so there's no harm in accepting
4120 // almost anything here.
4121 // cl is very strict about whitespace in this form and errors out if any
4122 // is present, so check the space flags on the tokens.
4123 SourceLocation StartLoc = Tok.getLocation();
4124 while (Tok.isNot(tok::r_paren)) {
4125 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4126 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4127 SkipUntil(tok::r_paren, StopAtSemi);
4130 SmallString<16> SpellingBuffer;
4131 SpellingBuffer.resize(Tok.getLength() + 1);
4132 bool Invalid = false;
4133 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4135 SkipUntil(tok::r_paren, StopAtSemi);
4138 StrBuffer += TokSpelling;
4143 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4144 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4149 // Pretend the user wrote the appropriate string literal here.
4150 // ActOnStringLiteral() copies the string data into the literal, so it's
4151 // ok that the Token points to StrBuffer.
4153 Toks[0].startToken();
4154 Toks[0].setKind(tok::string_literal);
4155 Toks[0].setLocation(StartLoc);
4156 Toks[0].setLiteralData(StrBuffer.data());
4157 Toks[0].setLength(StrBuffer.size());
4158 StringLiteral *UuidString =
4159 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4160 ArgExprs.push_back(UuidString);
4163 if (!T.consumeClose()) {
4164 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4165 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4166 ParsedAttr::AS_Microsoft);
4170 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4172 /// [MS] ms-attribute:
4173 /// '[' token-seq ']'
4175 /// [MS] ms-attribute-seq:
4176 /// ms-attribute[opt]
4177 /// ms-attribute ms-attribute-seq
4178 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4179 SourceLocation *endLoc) {
4180 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4183 // FIXME: If this is actually a C++11 attribute, parse it as one.
4184 BalancedDelimiterTracker T(*this, tok::l_square);
4187 // Skip most ms attributes except for a whitelist.
4189 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4190 if (Tok.isNot(tok::identifier)) // ']', but also eof
4192 if (Tok.getIdentifierInfo()->getName() == "uuid")
4193 ParseMicrosoftUuidAttributeArgs(attrs);
4200 *endLoc = T.getCloseLocation();
4201 } while (Tok.is(tok::l_square));
4204 void Parser::ParseMicrosoftIfExistsClassDeclaration(
4205 DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
4206 AccessSpecifier &CurAS) {
4207 IfExistsCondition Result;
4208 if (ParseMicrosoftIfExistsCondition(Result))
4211 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4212 if (Braces.consumeOpen()) {
4213 Diag(Tok, diag::err_expected) << tok::l_brace;
4217 switch (Result.Behavior) {
4219 // Parse the declarations below.
4223 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4224 << Result.IsIfExists;
4225 // Fall through to skip.
4233 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4234 // __if_exists, __if_not_exists can nest.
4235 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4236 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType,
4237 AccessAttrs, CurAS);
4241 // Check for extraneous top-level semicolon.
4242 if (Tok.is(tok::semi)) {
4243 ConsumeExtraSemi(InsideStruct, TagType);
4247 AccessSpecifier AS = getAccessSpecifierIfPresent();
4248 if (AS != AS_none) {
4249 // Current token is a C++ access specifier.
4251 SourceLocation ASLoc = Tok.getLocation();
4253 if (Tok.is(tok::colon))
4254 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
4255 ParsedAttributesView{});
4257 Diag(Tok, diag::err_expected) << tok::colon;
4262 // Parse all the comma separated declarators.
4263 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
4266 Braces.consumeClose();