1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++ Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/Basic/Attributes.h"
18 #include "clang/Basic/CharInfo.h"
19 #include "clang/Basic/OperatorKinds.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Parse/ParseDiagnostic.h"
22 #include "clang/Parse/RAIIObjectsForParser.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/SmallString.h"
30 using namespace clang;
32 /// ParseNamespace - We know that the current token is a namespace keyword. This
33 /// may either be a top level namespace or a block-level namespace alias. If
34 /// there was an inline keyword, it has already been parsed.
36 /// namespace-definition: [C++ 7.3: basic.namespace]
37 /// named-namespace-definition
38 /// unnamed-namespace-definition
40 /// unnamed-namespace-definition:
41 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
43 /// named-namespace-definition:
44 /// original-namespace-definition
45 /// extension-namespace-definition
47 /// original-namespace-definition:
48 /// 'inline'[opt] 'namespace' identifier attributes[opt]
49 /// '{' namespace-body '}'
51 /// extension-namespace-definition:
52 /// 'inline'[opt] 'namespace' original-namespace-name
53 /// '{' namespace-body '}'
55 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
56 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
58 Parser::DeclGroupPtrTy Parser::ParseNamespace(unsigned Context,
59 SourceLocation &DeclEnd,
60 SourceLocation InlineLoc) {
61 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
62 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
63 ObjCDeclContextSwitch ObjCDC(*this);
65 if (Tok.is(tok::code_completion)) {
66 Actions.CodeCompleteNamespaceDecl(getCurScope());
71 SourceLocation IdentLoc;
72 IdentifierInfo *Ident = nullptr;
73 std::vector<SourceLocation> ExtraIdentLoc;
74 std::vector<IdentifierInfo*> ExtraIdent;
75 std::vector<SourceLocation> ExtraNamespaceLoc;
77 ParsedAttributesWithRange attrs(AttrFactory);
78 SourceLocation attrLoc;
79 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
80 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
81 ? diag::warn_cxx14_compat_ns_enum_attribute
82 : diag::ext_ns_enum_attribute)
84 attrLoc = Tok.getLocation();
85 ParseCXX11Attributes(attrs);
88 if (Tok.is(tok::identifier)) {
89 Ident = Tok.getIdentifierInfo();
90 IdentLoc = ConsumeToken(); // eat the identifier.
91 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
92 ExtraNamespaceLoc.push_back(ConsumeToken());
93 ExtraIdent.push_back(Tok.getIdentifierInfo());
94 ExtraIdentLoc.push_back(ConsumeToken());
98 // A nested namespace definition cannot have attributes.
99 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
100 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
102 // Read label attributes, if present.
103 if (Tok.is(tok::kw___attribute)) {
104 attrLoc = Tok.getLocation();
105 ParseGNUAttributes(attrs);
108 if (Tok.is(tok::equal)) {
110 Diag(Tok, diag::err_expected) << tok::identifier;
111 // Skip to end of the definition and eat the ';'.
112 SkipUntil(tok::semi);
115 if (attrLoc.isValid())
116 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
117 if (InlineLoc.isValid())
118 Diag(InlineLoc, diag::err_inline_namespace_alias)
119 << FixItHint::CreateRemoval(InlineLoc);
120 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
121 return Actions.ConvertDeclToDeclGroup(NSAlias);
124 BalancedDelimiterTracker T(*this, tok::l_brace);
125 if (T.consumeOpen()) {
127 Diag(Tok, diag::err_expected) << tok::l_brace;
129 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
133 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
134 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
135 getCurScope()->getFnParent()) {
136 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
137 SkipUntil(tok::r_brace);
141 if (ExtraIdent.empty()) {
142 // Normal namespace definition, not a nested-namespace-definition.
143 } else if (InlineLoc.isValid()) {
144 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
145 } else if (getLangOpts().CPlusPlus17) {
146 Diag(ExtraNamespaceLoc[0],
147 diag::warn_cxx14_compat_nested_namespace_definition);
149 TentativeParsingAction TPA(*this);
150 SkipUntil(tok::r_brace, StopBeforeMatch);
151 Token rBraceToken = Tok;
154 if (!rBraceToken.is(tok::r_brace)) {
155 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
156 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
158 std::string NamespaceFix;
159 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
160 E = ExtraIdent.end(); I != E; ++I) {
161 NamespaceFix += " { namespace ";
162 NamespaceFix += (*I)->getName();
166 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
169 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
170 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
171 ExtraIdentLoc.back()),
173 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
177 // If we're still good, complain about inline namespaces in non-C++0x now.
178 if (InlineLoc.isValid())
179 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
180 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
182 // Enter a scope for the namespace.
183 ParseScope NamespaceScope(this, Scope::DeclScope);
185 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
187 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
188 IdentLoc, Ident, T.getOpenLocation(),
189 attrs.getList(), ImplicitUsingDirectiveDecl);
191 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
192 "parsing namespace");
194 // Parse the contents of the namespace. This includes parsing recovery on
195 // any improperly nested namespaces.
196 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
197 InlineLoc, attrs, T);
199 // Leave the namespace scope.
200 NamespaceScope.Exit();
202 DeclEnd = T.getCloseLocation();
203 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
205 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
206 ImplicitUsingDirectiveDecl);
209 /// ParseInnerNamespace - Parse the contents of a namespace.
210 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
211 std::vector<IdentifierInfo *> &Ident,
212 std::vector<SourceLocation> &NamespaceLoc,
213 unsigned int index, SourceLocation &InlineLoc,
214 ParsedAttributes &attrs,
215 BalancedDelimiterTracker &Tracker) {
216 if (index == Ident.size()) {
217 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
218 Tok.isNot(tok::eof)) {
219 ParsedAttributesWithRange attrs(AttrFactory);
220 MaybeParseCXX11Attributes(attrs);
221 ParseExternalDeclaration(attrs);
224 // The caller is what called check -- we are simply calling
226 Tracker.consumeClose();
231 // Handle a nested namespace definition.
232 // FIXME: Preserve the source information through to the AST rather than
233 // desugaring it here.
234 ParseScope NamespaceScope(this, Scope::DeclScope);
235 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
237 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
238 NamespaceLoc[index], IdentLoc[index],
239 Ident[index], Tracker.getOpenLocation(),
240 attrs.getList(), ImplicitUsingDirectiveDecl);
241 assert(!ImplicitUsingDirectiveDecl &&
242 "nested namespace definition cannot define anonymous namespace");
244 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
247 NamespaceScope.Exit();
248 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
251 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
252 /// alias definition.
254 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
255 SourceLocation AliasLoc,
256 IdentifierInfo *Alias,
257 SourceLocation &DeclEnd) {
258 assert(Tok.is(tok::equal) && "Not equal token");
260 ConsumeToken(); // eat the '='.
262 if (Tok.is(tok::code_completion)) {
263 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
269 // Parse (optional) nested-name-specifier.
270 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
271 /*MayBePseudoDestructor=*/nullptr,
272 /*IsTypename=*/false,
274 /*OnlyNamespace=*/true);
276 if (Tok.isNot(tok::identifier)) {
277 Diag(Tok, diag::err_expected_namespace_name);
278 // Skip to end of the definition and eat the ';'.
279 SkipUntil(tok::semi);
283 if (SS.isInvalid()) {
284 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
285 // Skip to end of the definition and eat the ';'.
286 SkipUntil(tok::semi);
291 IdentifierInfo *Ident = Tok.getIdentifierInfo();
292 SourceLocation IdentLoc = ConsumeToken();
295 DeclEnd = Tok.getLocation();
296 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
297 SkipUntil(tok::semi);
299 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
300 Alias, SS, IdentLoc, Ident);
303 /// ParseLinkage - We know that the current token is a string_literal
304 /// and just before that, that extern was seen.
306 /// linkage-specification: [C++ 7.5p2: dcl.link]
307 /// 'extern' string-literal '{' declaration-seq[opt] '}'
308 /// 'extern' string-literal declaration
310 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
311 assert(isTokenStringLiteral() && "Not a string literal!");
312 ExprResult Lang = ParseStringLiteralExpression(false);
314 ParseScope LinkageScope(this, Scope::DeclScope);
318 : Actions.ActOnStartLinkageSpecification(
319 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
320 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
322 ParsedAttributesWithRange attrs(AttrFactory);
323 MaybeParseCXX11Attributes(attrs);
325 if (Tok.isNot(tok::l_brace)) {
326 // Reset the source range in DS, as the leading "extern"
327 // does not really belong to the inner declaration ...
328 DS.SetRangeStart(SourceLocation());
329 DS.SetRangeEnd(SourceLocation());
330 // ... but anyway remember that such an "extern" was seen.
331 DS.setExternInLinkageSpec(true);
332 ParseExternalDeclaration(attrs, &DS);
333 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
334 getCurScope(), LinkageSpec, SourceLocation())
340 ProhibitAttributes(attrs);
342 BalancedDelimiterTracker T(*this, tok::l_brace);
345 unsigned NestedModules = 0;
347 switch (Tok.getKind()) {
348 case tok::annot_module_begin:
353 case tok::annot_module_end:
360 case tok::annot_module_include:
372 ParsedAttributesWithRange attrs(AttrFactory);
373 MaybeParseCXX11Attributes(attrs);
374 ParseExternalDeclaration(attrs);
382 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
383 getCurScope(), LinkageSpec, T.getCloseLocation())
387 /// Parse a C++ Modules TS export-declaration.
389 /// export-declaration:
390 /// 'export' declaration
391 /// 'export' '{' declaration-seq[opt] '}'
393 Decl *Parser::ParseExportDeclaration() {
394 assert(Tok.is(tok::kw_export));
395 SourceLocation ExportLoc = ConsumeToken();
397 ParseScope ExportScope(this, Scope::DeclScope);
398 Decl *ExportDecl = Actions.ActOnStartExportDecl(
399 getCurScope(), ExportLoc,
400 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
402 if (Tok.isNot(tok::l_brace)) {
403 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
404 ParsedAttributesWithRange Attrs(AttrFactory);
405 MaybeParseCXX11Attributes(Attrs);
406 MaybeParseMicrosoftAttributes(Attrs);
407 ParseExternalDeclaration(Attrs);
408 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
412 BalancedDelimiterTracker T(*this, tok::l_brace);
415 // The Modules TS draft says "An export-declaration shall declare at least one
416 // entity", but the intent is that it shall contain at least one declaration.
417 if (Tok.is(tok::r_brace))
418 Diag(ExportLoc, diag::err_export_empty)
419 << SourceRange(ExportLoc, Tok.getLocation());
421 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
422 Tok.isNot(tok::eof)) {
423 ParsedAttributesWithRange Attrs(AttrFactory);
424 MaybeParseCXX11Attributes(Attrs);
425 MaybeParseMicrosoftAttributes(Attrs);
426 ParseExternalDeclaration(Attrs);
430 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
431 T.getCloseLocation());
434 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
435 /// using-directive. Assumes that current token is 'using'.
436 Parser::DeclGroupPtrTy
437 Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
438 const ParsedTemplateInfo &TemplateInfo,
439 SourceLocation &DeclEnd,
440 ParsedAttributesWithRange &attrs) {
441 assert(Tok.is(tok::kw_using) && "Not using token");
442 ObjCDeclContextSwitch ObjCDC(*this);
445 SourceLocation UsingLoc = ConsumeToken();
447 if (Tok.is(tok::code_completion)) {
448 Actions.CodeCompleteUsing(getCurScope());
453 // 'using namespace' means this is a using-directive.
454 if (Tok.is(tok::kw_namespace)) {
455 // Template parameters are always an error here.
456 if (TemplateInfo.Kind) {
457 SourceRange R = TemplateInfo.getSourceRange();
458 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
459 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
462 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
463 return Actions.ConvertDeclToDeclGroup(UsingDir);
466 // Otherwise, it must be a using-declaration or an alias-declaration.
468 // Using declarations can't have attributes.
469 ProhibitAttributes(attrs);
471 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
475 /// ParseUsingDirective - Parse C++ using-directive, assumes
476 /// that current token is 'namespace' and 'using' was already parsed.
478 /// using-directive: [C++ 7.3.p4: namespace.udir]
479 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
481 /// [GNU] using-directive:
482 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
483 /// namespace-name attributes[opt] ;
485 Decl *Parser::ParseUsingDirective(unsigned Context,
486 SourceLocation UsingLoc,
487 SourceLocation &DeclEnd,
488 ParsedAttributes &attrs) {
489 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
492 SourceLocation NamespcLoc = ConsumeToken();
494 if (Tok.is(tok::code_completion)) {
495 Actions.CodeCompleteUsingDirective(getCurScope());
501 // Parse (optional) nested-name-specifier.
502 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
503 /*MayBePseudoDestructor=*/nullptr,
504 /*IsTypename=*/false,
506 /*OnlyNamespace=*/true);
508 IdentifierInfo *NamespcName = nullptr;
509 SourceLocation IdentLoc = SourceLocation();
511 // Parse namespace-name.
512 if (Tok.isNot(tok::identifier)) {
513 Diag(Tok, diag::err_expected_namespace_name);
514 // If there was invalid namespace name, skip to end of decl, and eat ';'.
515 SkipUntil(tok::semi);
516 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
520 if (SS.isInvalid()) {
521 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
522 // Skip to end of the definition and eat the ';'.
523 SkipUntil(tok::semi);
528 NamespcName = Tok.getIdentifierInfo();
529 IdentLoc = ConsumeToken();
531 // Parse (optional) attributes (most likely GNU strong-using extension).
532 bool GNUAttr = false;
533 if (Tok.is(tok::kw___attribute)) {
535 ParseGNUAttributes(attrs);
539 DeclEnd = Tok.getLocation();
540 if (ExpectAndConsume(tok::semi,
541 GNUAttr ? diag::err_expected_semi_after_attribute_list
542 : diag::err_expected_semi_after_namespace_name))
543 SkipUntil(tok::semi);
545 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
546 IdentLoc, NamespcName, attrs.getList());
549 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
551 /// using-declarator:
552 /// 'typename'[opt] nested-name-specifier unqualified-id
554 bool Parser::ParseUsingDeclarator(unsigned Context, UsingDeclarator &D) {
557 // Ignore optional 'typename'.
558 // FIXME: This is wrong; we should parse this as a typename-specifier.
559 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
561 if (Tok.is(tok::kw___super)) {
562 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
566 // Parse nested-name-specifier.
567 IdentifierInfo *LastII = nullptr;
568 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
569 /*MayBePseudoDtor=*/nullptr,
570 /*IsTypename=*/false,
572 if (D.SS.isInvalid())
575 // Parse the unqualified-id. We allow parsing of both constructor and
576 // destructor names and allow the action module to diagnose any semantic
579 // C++11 [class.qual]p2:
580 // [...] in a using-declaration that is a member-declaration, if the name
581 // specified after the nested-name-specifier is the same as the identifier
582 // or the simple-template-id's template-name in the last component of the
583 // nested-name-specifier, the name is [...] considered to name the
585 if (getLangOpts().CPlusPlus11 && Context == Declarator::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, D.TemplateKWLoc, 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(unsigned 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() != UnqualifiedId::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.getList());
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() == UnqualifiedId::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() != UnqualifiedId::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 =
795 ParseTypeName(nullptr,
796 TemplateInfo.Kind ? Declarator::AliasTemplateContext
797 : Declarator::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.getList(),
815 TypeAlias, DeclFromDeclSpec);
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 /*IsDecltype=*/true);
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, Declarator::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, Declarator::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 AttributeList::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 DSC_type_specifier or DSC_alias_declaration.
1617 // If there are attributes after class name, parse them.
1618 MaybeParseCXX11Attributes(Attributes);
1620 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1621 Sema::TagUseKind TUK;
1622 if (DSC == DSC_trailing)
1623 TUK = Sema::TUK_Reference;
1624 else if (Tok.is(tok::l_brace) ||
1625 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1626 (isCXX11FinalKeyword() &&
1627 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1628 if (DS.isFriendSpecified()) {
1629 // C++ [class.friend]p2:
1630 // A class shall not be defined in a friend declaration.
1631 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1632 << SourceRange(DS.getFriendSpecLoc());
1634 // Skip everything up to the semicolon, so that this looks like a proper
1635 // friend class (or template thereof) declaration.
1636 SkipUntil(tok::semi, StopBeforeMatch);
1637 TUK = Sema::TUK_Friend;
1639 // Okay, this is a class definition.
1640 TUK = Sema::TUK_Definition;
1642 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1643 NextToken().is(tok::kw_alignas))) {
1644 // We can't tell if this is a definition or reference
1645 // until we skipped the 'final' and C++11 attribute specifiers.
1646 TentativeParsingAction PA(*this);
1648 // Skip the 'final' keyword.
1651 // Skip C++11 attribute specifiers.
1653 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1655 if (!SkipUntil(tok::r_square, StopAtSemi))
1657 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1660 if (!SkipUntil(tok::r_paren, StopAtSemi))
1667 if (Tok.isOneOf(tok::l_brace, tok::colon))
1668 TUK = Sema::TUK_Definition;
1670 TUK = Sema::TUK_Reference;
1673 } else if (!isTypeSpecifier(DSC) &&
1674 (Tok.is(tok::semi) ||
1675 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1676 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1677 if (Tok.isNot(tok::semi)) {
1678 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1679 // A semicolon was missing after this declaration. Diagnose and recover.
1680 ExpectAndConsume(tok::semi, diag::err_expected_after,
1681 DeclSpec::getSpecifierName(TagType, PPol));
1683 Tok.setKind(tok::semi);
1686 TUK = Sema::TUK_Reference;
1688 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1689 // to caller to handle.
1690 if (TUK != Sema::TUK_Reference) {
1691 // If this is not a reference, then the only possible
1692 // valid place for C++11 attributes to appear here
1693 // is between class-key and class-name. If there are
1694 // any attributes after class-name, we try a fixit to move
1695 // them to the right place.
1696 SourceRange AttrRange = Attributes.Range;
1697 if (AttrRange.isValid()) {
1698 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1700 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1701 CharSourceRange(AttrRange, true))
1702 << FixItHint::CreateRemoval(AttrRange);
1704 // Recover by adding misplaced attributes to the attribute list
1705 // of the class so they can be applied on the class later.
1706 attrs.takeAllFrom(Attributes);
1710 // If this is an elaborated type specifier, and we delayed
1711 // diagnostics before, just merge them into the current pool.
1712 if (shouldDelayDiagsInTag) {
1713 diagsFromTag.done();
1714 if (TUK == Sema::TUK_Reference)
1715 diagsFromTag.redelay();
1718 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1719 TUK != Sema::TUK_Definition)) {
1720 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1721 // We have a declaration or reference to an anonymous class.
1722 Diag(StartLoc, diag::err_anon_type_definition)
1723 << DeclSpec::getSpecifierName(TagType, Policy);
1726 // If we are parsing a definition and stop at a base-clause, continue on
1727 // until the semicolon. Continuing from the comma will just trick us into
1728 // thinking we are seeing a variable declaration.
1729 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1730 SkipUntil(tok::semi, StopBeforeMatch);
1732 SkipUntil(tok::comma, StopAtSemi);
1736 // Create the tag portion of the class or class template.
1737 DeclResult TagOrTempResult = true; // invalid
1738 TypeResult TypeResult = true; // invalid
1741 Sema::SkipBodyInfo SkipBody;
1743 // Explicit specialization, class template partial specialization,
1744 // or explicit instantiation.
1745 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1746 TemplateId->NumArgs);
1747 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1748 TUK == Sema::TUK_Declaration) {
1749 // This is an explicit instantiation of a class template.
1750 ProhibitAttributes(attrs);
1753 = Actions.ActOnExplicitInstantiation(getCurScope(),
1754 TemplateInfo.ExternLoc,
1755 TemplateInfo.TemplateLoc,
1759 TemplateId->Template,
1760 TemplateId->TemplateNameLoc,
1761 TemplateId->LAngleLoc,
1763 TemplateId->RAngleLoc,
1766 // Friend template-ids are treated as references unless
1767 // they have template headers, in which case they're ill-formed
1768 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1769 // We diagnose this error in ActOnClassTemplateSpecialization.
1770 } else if (TUK == Sema::TUK_Reference ||
1771 (TUK == Sema::TUK_Friend &&
1772 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1773 ProhibitAttributes(attrs);
1774 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1776 TemplateId->TemplateKWLoc,
1777 TemplateId->Template,
1778 TemplateId->TemplateNameLoc,
1779 TemplateId->LAngleLoc,
1781 TemplateId->RAngleLoc);
1783 // This is an explicit specialization or a class template
1784 // partial specialization.
1785 TemplateParameterLists FakedParamLists;
1786 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1787 // This looks like an explicit instantiation, because we have
1790 // template class Foo<X>
1792 // but it actually has a definition. Most likely, this was
1793 // meant to be an explicit specialization, but the user forgot
1794 // the '<>' after 'template'.
1795 // It this is friend declaration however, since it cannot have a
1796 // template header, it is most likely that the user meant to
1797 // remove the 'template' keyword.
1798 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1799 "Expected a definition here");
1801 if (TUK == Sema::TUK_Friend) {
1802 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1803 TemplateParams = nullptr;
1805 SourceLocation LAngleLoc =
1806 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1807 Diag(TemplateId->TemplateNameLoc,
1808 diag::err_explicit_instantiation_with_definition)
1809 << SourceRange(TemplateInfo.TemplateLoc)
1810 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1812 // Create a fake template parameter list that contains only
1813 // "template<>", so that we treat this construct as a class
1814 // template specialization.
1815 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1816 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1817 LAngleLoc, nullptr));
1818 TemplateParams = &FakedParamLists;
1822 // Build the class template specialization.
1823 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1824 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1825 *TemplateId, attrs.getList(),
1826 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1828 TemplateParams ? TemplateParams->size() : 0),
1831 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1832 TUK == Sema::TUK_Declaration) {
1833 // Explicit instantiation of a member of a class template
1834 // specialization, e.g.,
1836 // template struct Outer<int>::Inner;
1838 ProhibitAttributes(attrs);
1841 = Actions.ActOnExplicitInstantiation(getCurScope(),
1842 TemplateInfo.ExternLoc,
1843 TemplateInfo.TemplateLoc,
1844 TagType, StartLoc, SS, Name,
1845 NameLoc, attrs.getList());
1846 } else if (TUK == Sema::TUK_Friend &&
1847 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1848 ProhibitAttributes(attrs);
1851 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1852 TagType, StartLoc, SS,
1853 Name, NameLoc, attrs.getList(),
1854 MultiTemplateParamsArg(
1855 TemplateParams? &(*TemplateParams)[0]
1857 TemplateParams? TemplateParams->size() : 0));
1859 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1860 ProhibitAttributes(attrs);
1862 if (TUK == Sema::TUK_Definition &&
1863 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1864 // If the declarator-id is not a template-id, issue a diagnostic and
1865 // recover by ignoring the 'template' keyword.
1866 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1867 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1868 TemplateParams = nullptr;
1871 bool IsDependent = false;
1873 // Don't pass down template parameter lists if this is just a tag
1874 // reference. For example, we don't need the template parameters here:
1875 // template <class T> class A *makeA(T t);
1876 MultiTemplateParamsArg TParams;
1877 if (TUK != Sema::TUK_Reference && TemplateParams)
1879 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1881 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
1883 // Declaration or definition of a class type
1884 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1885 SS, Name, NameLoc, attrs.getList(), AS,
1886 DS.getModulePrivateSpecLoc(),
1887 TParams, Owned, IsDependent,
1888 SourceLocation(), false,
1889 clang::TypeResult(),
1890 DSC == DSC_type_specifier,
1891 DSC == DSC_template_param ||
1892 DSC == DSC_template_type_arg, &SkipBody);
1894 // If ActOnTag said the type was dependent, try again with the
1895 // less common call.
1897 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1898 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1899 SS, Name, StartLoc, NameLoc);
1903 // If there is a body, parse it and inform the actions module.
1904 if (TUK == Sema::TUK_Definition) {
1905 assert(Tok.is(tok::l_brace) ||
1906 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1907 isCXX11FinalKeyword());
1908 if (SkipBody.ShouldSkip)
1909 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1910 TagOrTempResult.get());
1911 else if (getLangOpts().CPlusPlus)
1912 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1913 TagOrTempResult.get());
1916 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1917 // Parse the definition body.
1918 ParseStructUnionBody(StartLoc, TagType, D);
1919 if (SkipBody.CheckSameAsPrevious &&
1920 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1922 DS.SetTypeSpecError();
1928 if (!TagOrTempResult.isInvalid())
1929 // Delayed processing of attributes.
1930 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1932 const char *PrevSpec = nullptr;
1935 if (!TypeResult.isInvalid()) {
1936 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1937 NameLoc.isValid() ? NameLoc : StartLoc,
1938 PrevSpec, DiagID, TypeResult.get(), Policy);
1939 } else if (!TagOrTempResult.isInvalid()) {
1940 Result = DS.SetTypeSpecType(TagType, StartLoc,
1941 NameLoc.isValid() ? NameLoc : StartLoc,
1942 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1945 DS.SetTypeSpecError();
1950 Diag(StartLoc, DiagID) << PrevSpec;
1952 // At this point, we've successfully parsed a class-specifier in 'definition'
1953 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1954 // going to look at what comes after it to improve error recovery. If an
1955 // impossible token occurs next, we assume that the programmer forgot a ; at
1956 // the end of the declaration and recover that way.
1958 // Also enforce C++ [temp]p3:
1959 // In a template-declaration which defines a class, no declarator
1962 // After a type-specifier, we don't expect a semicolon. This only happens in
1963 // C, since definitions are not permitted in this context in C++.
1964 if (TUK == Sema::TUK_Definition &&
1965 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1966 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1967 if (Tok.isNot(tok::semi)) {
1968 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1969 ExpectAndConsume(tok::semi, diag::err_expected_after,
1970 DeclSpec::getSpecifierName(TagType, PPol));
1971 // Push this token back into the preprocessor and change our current token
1972 // to ';' so that the rest of the code recovers as though there were an
1973 // ';' after the definition.
1975 Tok.setKind(tok::semi);
1980 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1982 /// base-clause : [C++ class.derived]
1983 /// ':' base-specifier-list
1984 /// base-specifier-list:
1985 /// base-specifier '...'[opt]
1986 /// base-specifier-list ',' base-specifier '...'[opt]
1987 void Parser::ParseBaseClause(Decl *ClassDecl) {
1988 assert(Tok.is(tok::colon) && "Not a base clause");
1991 // Build up an array of parsed base specifiers.
1992 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1995 // Parse a base-specifier.
1996 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1997 if (Result.isInvalid()) {
1998 // Skip the rest of this base specifier, up until the comma or
2000 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2002 // Add this to our array of base specifiers.
2003 BaseInfo.push_back(Result.get());
2006 // If the next token is a comma, consume it and keep reading
2008 if (!TryConsumeToken(tok::comma))
2012 // Attach the base specifiers
2013 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2016 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2017 /// one entry in the base class list of a class specifier, for example:
2018 /// class foo : public bar, virtual private baz {
2019 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2021 /// base-specifier: [C++ class.derived]
2022 /// attribute-specifier-seq[opt] base-type-specifier
2023 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2024 /// base-type-specifier
2025 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2026 /// base-type-specifier
2027 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2028 bool IsVirtual = false;
2029 SourceLocation StartLoc = Tok.getLocation();
2031 ParsedAttributesWithRange Attributes(AttrFactory);
2032 MaybeParseCXX11Attributes(Attributes);
2034 // Parse the 'virtual' keyword.
2035 if (TryConsumeToken(tok::kw_virtual))
2038 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2040 // Parse an (optional) access specifier.
2041 AccessSpecifier Access = getAccessSpecifierIfPresent();
2042 if (Access != AS_none)
2045 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2047 // Parse the 'virtual' keyword (again!), in case it came after the
2048 // access specifier.
2049 if (Tok.is(tok::kw_virtual)) {
2050 SourceLocation VirtualLoc = ConsumeToken();
2052 // Complain about duplicate 'virtual'
2053 Diag(VirtualLoc, diag::err_dup_virtual)
2054 << FixItHint::CreateRemoval(VirtualLoc);
2060 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2062 // Parse the class-name.
2064 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2065 // implementation for VS2013 uses _Atomic as an identifier for one of the
2066 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2067 // parsing the class-name for a base specifier.
2068 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2069 NextToken().is(tok::less))
2070 Tok.setKind(tok::identifier);
2072 SourceLocation EndLocation;
2073 SourceLocation BaseLoc;
2074 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2075 if (BaseType.isInvalid())
2078 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2079 // actually part of the base-specifier-list grammar productions, but we
2080 // parse it here for convenience.
2081 SourceLocation EllipsisLoc;
2082 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2084 // Find the complete source range for the base-specifier.
2085 SourceRange Range(StartLoc, EndLocation);
2087 // Notify semantic analysis that we have parsed a complete
2089 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2090 Access, BaseType.get(), BaseLoc,
2094 /// getAccessSpecifierIfPresent - Determine whether the next token is
2095 /// a C++ access-specifier.
2097 /// access-specifier: [C++ class.derived]
2101 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2102 switch (Tok.getKind()) {
2103 default: return AS_none;
2104 case tok::kw_private: return AS_private;
2105 case tok::kw_protected: return AS_protected;
2106 case tok::kw_public: return AS_public;
2110 /// \brief If the given declarator has any parts for which parsing has to be
2111 /// delayed, e.g., default arguments or an exception-specification, create a
2112 /// late-parsed method declaration record to handle the parsing at the end of
2113 /// the class definition.
2114 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2116 DeclaratorChunk::FunctionTypeInfo &FTI
2117 = DeclaratorInfo.getFunctionTypeInfo();
2118 // If there was a late-parsed exception-specification, we'll need a
2120 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2122 if (!NeedLateParse) {
2123 // Look ahead to see if there are any default args
2124 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2125 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2126 if (Param->hasUnparsedDefaultArg()) {
2127 NeedLateParse = true;
2133 if (NeedLateParse) {
2134 // Push this method onto the stack of late-parsed method
2136 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2137 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2138 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2140 // Stash the exception-specification tokens in the late-pased method.
2141 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2142 FTI.ExceptionSpecTokens = nullptr;
2144 // Push tokens for each parameter. Those that do not have
2145 // defaults will be NULL.
2146 LateMethod->DefaultArgs.reserve(FTI.NumParams);
2147 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2148 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2149 FTI.Params[ParamIdx].Param,
2150 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2154 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2161 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2162 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2163 return VirtSpecifiers::VS_None;
2165 IdentifierInfo *II = Tok.getIdentifierInfo();
2167 // Initialize the contextual keywords.
2169 Ident_final = &PP.getIdentifierTable().get("final");
2170 if (getLangOpts().GNUKeywords)
2171 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2172 if (getLangOpts().MicrosoftExt)
2173 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2174 Ident_override = &PP.getIdentifierTable().get("override");
2177 if (II == Ident_override)
2178 return VirtSpecifiers::VS_Override;
2180 if (II == Ident_sealed)
2181 return VirtSpecifiers::VS_Sealed;
2183 if (II == Ident_final)
2184 return VirtSpecifiers::VS_Final;
2186 if (II == Ident_GNU_final)
2187 return VirtSpecifiers::VS_GNU_Final;
2189 return VirtSpecifiers::VS_None;
2192 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2194 /// virt-specifier-seq:
2196 /// virt-specifier-seq virt-specifier
2197 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2199 SourceLocation FriendLoc) {
2201 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2202 if (Specifier == VirtSpecifiers::VS_None)
2205 if (FriendLoc.isValid()) {
2206 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2207 << VirtSpecifiers::getSpecifierName(Specifier)
2208 << FixItHint::CreateRemoval(Tok.getLocation())
2209 << SourceRange(FriendLoc, FriendLoc);
2214 // C++ [class.mem]p8:
2215 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2216 const char *PrevSpec = nullptr;
2217 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2218 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2220 << FixItHint::CreateRemoval(Tok.getLocation());
2222 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2223 Specifier == VirtSpecifiers::VS_Sealed)) {
2224 Diag(Tok.getLocation(), diag::err_override_control_interface)
2225 << VirtSpecifiers::getSpecifierName(Specifier);
2226 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2227 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2228 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2229 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2231 Diag(Tok.getLocation(),
2232 getLangOpts().CPlusPlus11
2233 ? diag::warn_cxx98_compat_override_control_keyword
2234 : diag::ext_override_control_keyword)
2235 << VirtSpecifiers::getSpecifierName(Specifier);
2241 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2242 /// 'final' or Microsoft 'sealed' contextual keyword.
2243 bool Parser::isCXX11FinalKeyword() const {
2244 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2245 return Specifier == VirtSpecifiers::VS_Final ||
2246 Specifier == VirtSpecifiers::VS_GNU_Final ||
2247 Specifier == VirtSpecifiers::VS_Sealed;
2250 /// \brief Parse a C++ member-declarator up to, but not including, the optional
2251 /// brace-or-equal-initializer or pure-specifier.
2252 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2253 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2254 LateParsedAttrList &LateParsedAttrs) {
2255 // member-declarator:
2256 // declarator pure-specifier[opt]
2257 // declarator brace-or-equal-initializer[opt]
2258 // identifier[opt] ':' constant-expression
2259 if (Tok.isNot(tok::colon))
2260 ParseDeclarator(DeclaratorInfo);
2262 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2264 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2265 assert(DeclaratorInfo.isPastIdentifier() &&
2266 "don't know where identifier would go yet?");
2267 BitfieldSize = ParseConstantExpression();
2268 if (BitfieldSize.isInvalid())
2269 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2271 ParseOptionalCXX11VirtSpecifierSeq(
2272 VS, getCurrentClass().IsInterface,
2273 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2275 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2278 // If a simple-asm-expr is present, parse it.
2279 if (Tok.is(tok::kw_asm)) {
2281 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2282 if (AsmLabel.isInvalid())
2283 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2285 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2286 DeclaratorInfo.SetRangeEnd(Loc);
2289 // If attributes exist after the declarator, but before an '{', parse them.
2290 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2292 // For compatibility with code written to older Clang, also accept a
2293 // virt-specifier *after* the GNU attributes.
2294 if (BitfieldSize.isUnset() && VS.isUnset()) {
2295 ParseOptionalCXX11VirtSpecifierSeq(
2296 VS, getCurrentClass().IsInterface,
2297 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2298 if (!VS.isUnset()) {
2299 // If we saw any GNU-style attributes that are known to GCC followed by a
2300 // virt-specifier, issue a GCC-compat warning.
2301 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2303 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2304 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2305 Attr = Attr->getNext();
2307 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2311 // If this has neither a name nor a bit width, something has gone seriously
2312 // wrong. Skip until the semi-colon or }.
2313 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2314 // If so, skip until the semi-colon or a }.
2315 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2321 /// \brief Look for declaration specifiers possibly occurring after C++11
2322 /// virt-specifier-seq and diagnose them.
2323 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2325 VirtSpecifiers &VS) {
2326 DeclSpec DS(AttrFactory);
2328 // GNU-style and C++11 attributes are not allowed here, but they will be
2329 // handled by the caller. Diagnose everything else.
2330 ParseTypeQualifierListOpt(
2331 DS, AR_NoAttributesParsed, false,
2332 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2333 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2335 D.ExtendWithDeclSpec(DS);
2337 if (D.isFunctionDeclarator()) {
2338 auto &Function = D.getFunctionTypeInfo();
2339 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2340 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2341 const char *FixItName,
2342 SourceLocation SpecLoc,
2343 unsigned* QualifierLoc) {
2344 FixItHint Insertion;
2345 if (DS.getTypeQualifiers() & TypeQual) {
2346 if (!(Function.TypeQuals & TypeQual)) {
2347 std::string Name(FixItName);
2349 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2350 Function.TypeQuals |= TypeQual;
2351 *QualifierLoc = SpecLoc.getRawEncoding();
2353 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2355 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2356 << FixItHint::CreateRemoval(SpecLoc)
2360 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2361 &Function.ConstQualifierLoc);
2362 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2363 &Function.VolatileQualifierLoc);
2364 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2365 &Function.RestrictQualifierLoc);
2368 // Parse ref-qualifiers.
2369 bool RefQualifierIsLValueRef = true;
2370 SourceLocation RefQualifierLoc;
2371 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2372 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2373 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2374 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2375 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2377 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2378 << (RefQualifierIsLValueRef ? "&" : "&&")
2379 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2380 << FixItHint::CreateRemoval(RefQualifierLoc)
2382 D.SetRangeEnd(RefQualifierLoc);
2387 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2389 /// member-declaration:
2390 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2391 /// function-definition ';'[opt]
2392 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2393 /// using-declaration [TODO]
2394 /// [C++0x] static_assert-declaration
2395 /// template-declaration
2396 /// [GNU] '__extension__' member-declaration
2398 /// member-declarator-list:
2399 /// member-declarator
2400 /// member-declarator-list ',' member-declarator
2402 /// member-declarator:
2403 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2404 /// declarator constant-initializer[opt]
2405 /// [C++11] declarator brace-or-equal-initializer[opt]
2406 /// identifier[opt] ':' constant-expression
2408 /// virt-specifier-seq:
2410 /// virt-specifier-seq virt-specifier
2420 /// constant-initializer:
2421 /// '=' constant-expression
2423 Parser::DeclGroupPtrTy
2424 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2425 AttributeList *AccessAttrs,
2426 const ParsedTemplateInfo &TemplateInfo,
2427 ParsingDeclRAIIObject *TemplateDiags) {
2428 if (Tok.is(tok::at)) {
2429 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2430 Diag(Tok, diag::err_at_defs_cxx);
2432 Diag(Tok, diag::err_at_in_class);
2435 SkipUntil(tok::r_brace, StopAtSemi);
2439 // Turn on colon protection early, while parsing declspec, although there is
2440 // nothing to protect there. It prevents from false errors if error recovery
2441 // incorrectly determines where the declspec ends, as in the example:
2442 // struct A { enum class B { C }; };
2444 // struct D { A::B : C; };
2445 ColonProtectionRAIIObject X(*this);
2447 // Access declarations.
2448 bool MalformedTypeSpec = false;
2449 if (!TemplateInfo.Kind &&
2450 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2451 if (TryAnnotateCXXScopeToken())
2452 MalformedTypeSpec = true;
2455 if (Tok.isNot(tok::annot_cxxscope))
2456 isAccessDecl = false;
2457 else if (NextToken().is(tok::identifier))
2458 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2460 isAccessDecl = NextToken().is(tok::kw_operator);
2463 // Collect the scope specifier token we annotated earlier.
2465 ParseOptionalCXXScopeSpecifier(SS, nullptr,
2466 /*EnteringContext=*/false);
2468 if (SS.isInvalid()) {
2469 SkipUntil(tok::semi);
2473 // Try to parse an unqualified-id.
2474 SourceLocation TemplateKWLoc;
2476 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2477 TemplateKWLoc, Name)) {
2478 SkipUntil(tok::semi);
2482 // TODO: recover from mistakenly-qualified operator declarations.
2483 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2484 "access declaration")) {
2485 SkipUntil(tok::semi);
2489 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2490 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2491 /*TypenameLoc*/ SourceLocation(), SS, Name,
2492 /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
2496 // static_assert-declaration. A templated static_assert declaration is
2497 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2498 if (!TemplateInfo.Kind &&
2499 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2500 SourceLocation DeclEnd;
2501 return DeclGroupPtrTy::make(
2502 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2505 if (Tok.is(tok::kw_template)) {
2506 assert(!TemplateInfo.TemplateParams &&
2507 "Nested template improperly parsed?");
2508 ObjCDeclContextSwitch ObjCDC(*this);
2509 SourceLocation DeclEnd;
2510 return DeclGroupPtrTy::make(
2511 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2512 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
2515 // Handle: member-declaration ::= '__extension__' member-declaration
2516 if (Tok.is(tok::kw___extension__)) {
2517 // __extension__ silences extension warnings in the subexpression.
2518 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2520 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2521 TemplateInfo, TemplateDiags);
2524 ParsedAttributesWithRange attrs(AttrFactory);
2525 ParsedAttributesWithRange FnAttrs(AttrFactory);
2526 // Optional C++11 attribute-specifier
2527 MaybeParseCXX11Attributes(attrs);
2528 // We need to keep these attributes for future diagnostic
2529 // before they are taken over by declaration specifier.
2530 FnAttrs.addAll(attrs.getList());
2531 FnAttrs.Range = attrs.Range;
2533 MaybeParseMicrosoftAttributes(attrs);
2535 if (Tok.is(tok::kw_using)) {
2536 ProhibitAttributes(attrs);
2539 SourceLocation UsingLoc = ConsumeToken();
2541 if (Tok.is(tok::kw_namespace)) {
2542 Diag(UsingLoc, diag::err_using_namespace_in_class);
2543 SkipUntil(tok::semi, StopBeforeMatch);
2546 SourceLocation DeclEnd;
2547 // Otherwise, it must be a using-declaration or an alias-declaration.
2548 return ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2549 UsingLoc, DeclEnd, AS);
2552 // Hold late-parsed attributes so we can attach a Decl to them later.
2553 LateParsedAttrList CommonLateParsedAttrs;
2555 // decl-specifier-seq:
2556 // Parse the common declaration-specifiers piece.
2557 ParsingDeclSpec DS(*this, TemplateDiags);
2558 DS.takeAttributesFrom(attrs);
2559 if (MalformedTypeSpec)
2560 DS.SetTypeSpecError();
2562 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2563 &CommonLateParsedAttrs);
2565 // Turn off colon protection that was set for declspec.
2568 // If we had a free-standing type definition with a missing semicolon, we
2569 // may get this far before the problem becomes obvious.
2570 if (DS.hasTagDefinition() &&
2571 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2572 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2573 &CommonLateParsedAttrs))
2576 MultiTemplateParamsArg TemplateParams(
2577 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2579 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2581 if (TryConsumeToken(tok::semi)) {
2582 if (DS.isFriendSpecified())
2583 ProhibitAttributes(FnAttrs);
2585 RecordDecl *AnonRecord = nullptr;
2586 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2587 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2588 DS.complete(TheDecl);
2590 Decl* decls[] = {AnonRecord, TheDecl};
2591 return Actions.BuildDeclaratorGroup(decls);
2593 return Actions.ConvertDeclToDeclGroup(TheDecl);
2596 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2599 // Hold late-parsed attributes so we can attach a Decl to them later.
2600 LateParsedAttrList LateParsedAttrs;
2602 SourceLocation EqualLoc;
2603 SourceLocation PureSpecLoc;
2605 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2606 if (Tok.isNot(tok::equal))
2609 auto &Zero = NextToken();
2610 SmallString<8> Buffer;
2611 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2612 PP.getSpelling(Zero, Buffer) != "0")
2615 auto &After = GetLookAheadToken(2);
2616 if (!After.isOneOf(tok::semi, tok::comma) &&
2617 !(AllowDefinition &&
2618 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2621 EqualLoc = ConsumeToken();
2622 PureSpecLoc = ConsumeToken();
2626 SmallVector<Decl *, 8> DeclsInGroup;
2627 ExprResult BitfieldSize;
2628 bool ExpectSemi = true;
2630 // Parse the first declarator.
2631 if (ParseCXXMemberDeclaratorBeforeInitializer(
2632 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2633 TryConsumeToken(tok::semi);
2637 // Check for a member function definition.
2638 if (BitfieldSize.isUnset()) {
2639 // MSVC permits pure specifier on inline functions defined at class scope.
2640 // Hence check for =0 before checking for function definition.
2641 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2642 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2644 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2645 // function-definition:
2647 // In C++11, a non-function declarator followed by an open brace is a
2648 // braced-init-list for an in-class member initialization, not an
2649 // erroneous function definition.
2650 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2651 DefinitionKind = FDK_Definition;
2652 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2653 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2654 DefinitionKind = FDK_Definition;
2655 } else if (Tok.is(tok::equal)) {
2656 const Token &KW = NextToken();
2657 if (KW.is(tok::kw_default))
2658 DefinitionKind = FDK_Defaulted;
2659 else if (KW.is(tok::kw_delete))
2660 DefinitionKind = FDK_Deleted;
2663 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2665 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2666 // to a friend declaration, that declaration shall be a definition.
2667 if (DeclaratorInfo.isFunctionDeclarator() &&
2668 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2669 // Diagnose attributes that appear before decl specifier:
2670 // [[]] friend int foo();
2671 ProhibitAttributes(FnAttrs);
2674 if (DefinitionKind != FDK_Declaration) {
2675 if (!DeclaratorInfo.isFunctionDeclarator()) {
2676 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2678 SkipUntil(tok::r_brace);
2680 // Consume the optional ';'
2681 TryConsumeToken(tok::semi);
2686 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2687 Diag(DeclaratorInfo.getIdentifierLoc(),
2688 diag::err_function_declared_typedef);
2690 // Recover by treating the 'typedef' as spurious.
2691 DS.ClearStorageClassSpecs();
2695 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2699 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2700 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2702 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2703 LateParsedAttrs[i]->addDecl(FunDecl);
2706 LateParsedAttrs.clear();
2708 // Consume the ';' - it's optional unless we have a delete or default
2709 if (Tok.is(tok::semi))
2710 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2712 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2716 // member-declarator-list:
2717 // member-declarator
2718 // member-declarator-list ',' member-declarator
2721 InClassInitStyle HasInClassInit = ICIS_NoInit;
2722 bool HasStaticInitializer = false;
2723 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2724 if (DeclaratorInfo.isDeclarationOfFunction()) {
2725 // It's a pure-specifier.
2726 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2727 // Parse it as an expression so that Sema can diagnose it.
2728 HasStaticInitializer = true;
2729 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2730 DeclSpec::SCS_static &&
2731 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2732 DeclSpec::SCS_typedef &&
2733 !DS.isFriendSpecified()) {
2734 // It's a default member initializer.
2735 if (BitfieldSize.get())
2736 Diag(Tok, getLangOpts().CPlusPlus2a
2737 ? diag::warn_cxx17_compat_bitfield_member_init
2738 : diag::ext_bitfield_member_init);
2739 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2741 HasStaticInitializer = true;
2745 // NOTE: If Sema is the Action module and declarator is an instance field,
2746 // this call will *not* return the created decl; It will return null.
2747 // See Sema::ActOnCXXMemberDeclarator for details.
2749 NamedDecl *ThisDecl = nullptr;
2750 if (DS.isFriendSpecified()) {
2751 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2752 // to a friend declaration, that declaration shall be a definition.
2754 // Diagnose attributes that appear in a friend member function declarator:
2755 // friend int foo [[]] ();
2756 SmallVector<SourceRange, 4> Ranges;
2757 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2758 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2759 E = Ranges.end(); I != E; ++I)
2760 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2762 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2765 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2769 VS, HasInClassInit);
2771 if (VarTemplateDecl *VT =
2772 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2773 // Re-direct this decl to refer to the templated decl so that we can
2775 ThisDecl = VT->getTemplatedDecl();
2777 if (ThisDecl && AccessAttrs)
2778 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2781 // Error recovery might have converted a non-static member into a static
2783 if (HasInClassInit != ICIS_NoInit &&
2784 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2785 DeclSpec::SCS_static) {
2786 HasInClassInit = ICIS_NoInit;
2787 HasStaticInitializer = true;
2790 if (ThisDecl && PureSpecLoc.isValid())
2791 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2793 // Handle the initializer.
2794 if (HasInClassInit != ICIS_NoInit) {
2795 // The initializer was deferred; parse it and cache the tokens.
2796 Diag(Tok, getLangOpts().CPlusPlus11
2797 ? diag::warn_cxx98_compat_nonstatic_member_init
2798 : diag::ext_nonstatic_member_init);
2800 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2801 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2802 // declarator is followed by an initializer.
2804 // A brace-or-equal-initializer for a member-declarator is not an
2805 // initializer in the grammar, so this is ill-formed.
2806 Diag(Tok, diag::err_incomplete_array_member_init);
2807 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2809 // Avoid later warnings about a class member of incomplete type.
2811 ThisDecl->setInvalidDecl();
2813 ParseCXXNonStaticMemberInitializer(ThisDecl);
2814 } else if (HasStaticInitializer) {
2815 // Normal initializer.
2816 ExprResult Init = ParseCXXMemberInitializer(
2817 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2819 if (Init.isInvalid())
2820 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2822 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
2823 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2825 Actions.ActOnUninitializedDecl(ThisDecl);
2828 if (!ThisDecl->isInvalidDecl()) {
2829 // Set the Decl for any late parsed attributes
2830 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2831 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2833 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2834 LateParsedAttrs[i]->addDecl(ThisDecl);
2836 Actions.FinalizeDeclaration(ThisDecl);
2837 DeclsInGroup.push_back(ThisDecl);
2839 if (DeclaratorInfo.isFunctionDeclarator() &&
2840 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2841 DeclSpec::SCS_typedef)
2842 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2844 LateParsedAttrs.clear();
2846 DeclaratorInfo.complete(ThisDecl);
2848 // If we don't have a comma, it is either the end of the list (a ';')
2849 // or an error, bail out.
2850 SourceLocation CommaLoc;
2851 if (!TryConsumeToken(tok::comma, CommaLoc))
2854 if (Tok.isAtStartOfLine() &&
2855 !MightBeDeclarator(Declarator::MemberContext)) {
2856 // This comma was followed by a line-break and something which can't be
2857 // the start of a declarator. The comma was probably a typo for a
2859 Diag(CommaLoc, diag::err_expected_semi_declaration)
2860 << FixItHint::CreateReplacement(CommaLoc, ";");
2865 // Parse the next declarator.
2866 DeclaratorInfo.clear();
2868 BitfieldSize = ExprResult(/*Invalid=*/false);
2869 EqualLoc = PureSpecLoc = SourceLocation();
2870 DeclaratorInfo.setCommaLoc(CommaLoc);
2872 // GNU attributes are allowed before the second and subsequent declarator.
2873 MaybeParseGNUAttributes(DeclaratorInfo);
2875 if (ParseCXXMemberDeclaratorBeforeInitializer(
2876 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2881 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2882 // Skip to end of block or statement.
2883 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2884 // If we stopped at a ';', eat it.
2885 TryConsumeToken(tok::semi);
2889 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2892 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2893 /// Also detect and reject any attempted defaulted/deleted function definition.
2894 /// The location of the '=', if any, will be placed in EqualLoc.
2896 /// This does not check for a pure-specifier; that's handled elsewhere.
2898 /// brace-or-equal-initializer:
2899 /// '=' initializer-expression
2900 /// braced-init-list
2902 /// initializer-clause:
2903 /// assignment-expression
2904 /// braced-init-list
2906 /// defaulted/deleted function-definition:
2910 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2911 /// be a constant-expression.
2912 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2913 SourceLocation &EqualLoc) {
2914 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2915 && "Data member initializer not starting with '=' or '{'");
2917 EnterExpressionEvaluationContext Context(
2918 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
2919 if (TryConsumeToken(tok::equal, EqualLoc)) {
2920 if (Tok.is(tok::kw_delete)) {
2921 // In principle, an initializer of '= delete p;' is legal, but it will
2922 // never type-check. It's better to diagnose it as an ill-formed expression
2923 // than as an ill-formed deleted non-function member.
2924 // An initializer of '= delete p, foo' will never be parsed, because
2925 // a top-level comma always ends the initializer expression.
2926 const Token &Next = NextToken();
2927 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2929 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2932 Diag(ConsumeToken(), diag::err_deleted_non_function);
2935 } else if (Tok.is(tok::kw_default)) {
2937 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2940 Diag(ConsumeToken(), diag::err_default_special_members);
2944 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2945 Diag(Tok, diag::err_ms_property_initializer) << PD;
2948 return ParseInitializer();
2951 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2952 SourceLocation AttrFixitLoc,
2953 unsigned TagType, Decl *TagDecl) {
2954 // Skip the optional 'final' keyword.
2955 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2956 assert(isCXX11FinalKeyword() && "not a class definition");
2959 // Diagnose any C++11 attributes after 'final' keyword.
2960 // We deliberately discard these attributes.
2961 ParsedAttributesWithRange Attrs(AttrFactory);
2962 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2964 // This can only happen if we had malformed misplaced attributes;
2965 // we only get called if there is a colon or left-brace after the
2967 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2971 // Skip the base clauses. This requires actually parsing them, because
2972 // otherwise we can't be sure where they end (a left brace may appear
2973 // within a template argument).
2974 if (Tok.is(tok::colon)) {
2975 // Enter the scope of the class so that we can correctly parse its bases.
2976 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2977 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2978 TagType == DeclSpec::TST_interface);
2980 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2982 // Parse the bases but don't attach them to the class.
2983 ParseBaseClause(nullptr);
2985 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2987 if (!Tok.is(tok::l_brace)) {
2988 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2989 diag::err_expected_lbrace_after_base_specifiers);
2995 assert(Tok.is(tok::l_brace));
2996 BalancedDelimiterTracker T(*this, tok::l_brace);
3000 // Parse and discard any trailing attributes.
3001 ParsedAttributes Attrs(AttrFactory);
3002 if (Tok.is(tok::kw___attribute))
3003 MaybeParseGNUAttributes(Attrs);
3006 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3007 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3008 DeclSpec::TST TagType, Decl *TagDecl) {
3009 switch (Tok.getKind()) {
3010 case tok::kw___if_exists:
3011 case tok::kw___if_not_exists:
3012 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
3016 // Check for extraneous top-level semicolon.
3017 ConsumeExtraSemi(InsideStruct, TagType);
3020 // Handle pragmas that can appear as member declarations.
3021 case tok::annot_pragma_vis:
3022 HandlePragmaVisibility();
3024 case tok::annot_pragma_pack:
3027 case tok::annot_pragma_align:
3028 HandlePragmaAlign();
3030 case tok::annot_pragma_ms_pointers_to_members:
3031 HandlePragmaMSPointersToMembers();
3033 case tok::annot_pragma_ms_pragma:
3034 HandlePragmaMSPragma();
3036 case tok::annot_pragma_ms_vtordisp:
3037 HandlePragmaMSVtorDisp();
3039 case tok::annot_pragma_dump:
3043 case tok::kw_namespace:
3044 // If we see a namespace here, a close brace was missing somewhere.
3045 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3048 case tok::kw_public:
3049 case tok::kw_protected:
3050 case tok::kw_private: {
3051 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3052 assert(NewAS != AS_none);
3053 // Current token is a C++ access specifier.
3055 SourceLocation ASLoc = Tok.getLocation();
3056 unsigned TokLength = Tok.getLength();
3058 AccessAttrs.clear();
3059 MaybeParseGNUAttributes(AccessAttrs);
3061 SourceLocation EndLoc;
3062 if (TryConsumeToken(tok::colon, EndLoc)) {
3063 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3064 Diag(EndLoc, diag::err_expected)
3065 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3067 EndLoc = ASLoc.getLocWithOffset(TokLength);
3068 Diag(EndLoc, diag::err_expected)
3069 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3072 // The Microsoft extension __interface does not permit non-public
3073 // access specifiers.
3074 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3075 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3078 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3079 AccessAttrs.getList())) {
3080 // found another attribute than only annotations
3081 AccessAttrs.clear();
3087 case tok::annot_pragma_openmp:
3088 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3092 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3096 /// ParseCXXMemberSpecification - Parse the class definition.
3098 /// member-specification:
3099 /// member-declaration member-specification[opt]
3100 /// access-specifier ':' member-specification[opt]
3102 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3103 SourceLocation AttrFixitLoc,
3104 ParsedAttributesWithRange &Attrs,
3105 unsigned TagType, Decl *TagDecl) {
3106 assert((TagType == DeclSpec::TST_struct ||
3107 TagType == DeclSpec::TST_interface ||
3108 TagType == DeclSpec::TST_union ||
3109 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3111 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3112 "parsing struct/union/class body");
3114 // Determine whether this is a non-nested class. Note that local
3115 // classes are *not* considered to be nested classes.
3116 bool NonNestedClass = true;
3117 if (!ClassStack.empty()) {
3118 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
3119 if (S->isClassScope()) {
3120 // We're inside a class scope, so this is a nested class.
3121 NonNestedClass = false;
3123 // The Microsoft extension __interface does not permit nested classes.
3124 if (getCurrentClass().IsInterface) {
3125 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3127 << (isa<NamedDecl>(TagDecl)
3128 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3134 if ((S->getFlags() & Scope::FnScope))
3135 // If we're in a function or function template then this is a local
3136 // class rather than a nested class.
3141 // Enter a scope for the class.
3142 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3144 // Note that we are parsing a new (potentially-nested) class definition.
3145 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3146 TagType == DeclSpec::TST_interface);
3149 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3151 SourceLocation FinalLoc;
3152 bool IsFinalSpelledSealed = false;
3154 // Parse the optional 'final' keyword.
3155 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3156 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3157 assert((Specifier == VirtSpecifiers::VS_Final ||
3158 Specifier == VirtSpecifiers::VS_GNU_Final ||
3159 Specifier == VirtSpecifiers::VS_Sealed) &&
3160 "not a class definition");
3161 FinalLoc = ConsumeToken();
3162 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
3164 if (TagType == DeclSpec::TST_interface)
3165 Diag(FinalLoc, diag::err_override_control_interface)
3166 << VirtSpecifiers::getSpecifierName(Specifier);
3167 else if (Specifier == VirtSpecifiers::VS_Final)
3168 Diag(FinalLoc, getLangOpts().CPlusPlus11
3169 ? diag::warn_cxx98_compat_override_control_keyword
3170 : diag::ext_override_control_keyword)
3171 << VirtSpecifiers::getSpecifierName(Specifier);
3172 else if (Specifier == VirtSpecifiers::VS_Sealed)
3173 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3174 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3175 Diag(FinalLoc, diag::ext_warn_gnu_final);
3177 // Parse any C++11 attributes after 'final' keyword.
3178 // These attributes are not allowed to appear here,
3179 // and the only possible place for them to appertain
3180 // to the class would be between class-key and class-name.
3181 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3183 // ParseClassSpecifier() does only a superficial check for attributes before
3184 // deciding to call this method. For example, for
3185 // `class C final alignas ([l) {` it will decide that this looks like a
3186 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3187 // attribute parsing code will try to parse the '[' as a constexpr lambda
3188 // and consume enough tokens that the alignas parsing code will eat the
3189 // opening '{'. So bail out if the next token isn't one we expect.
3190 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3192 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3197 if (Tok.is(tok::colon)) {
3198 ParseScope InheritanceScope(this, getCurScope()->getFlags() |
3199 Scope::ClassInheritanceScope);
3201 ParseBaseClause(TagDecl);
3202 if (!Tok.is(tok::l_brace)) {
3203 bool SuggestFixIt = false;
3204 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3205 if (Tok.isAtStartOfLine()) {
3206 switch (Tok.getKind()) {
3207 case tok::kw_private:
3208 case tok::kw_protected:
3209 case tok::kw_public:
3210 SuggestFixIt = NextToken().getKind() == tok::colon;
3212 case tok::kw_static_assert:
3215 // base-clause can have simple-template-id; 'template' can't be there
3216 case tok::kw_template:
3217 SuggestFixIt = true;
3219 case tok::identifier:
3220 SuggestFixIt = isConstructorDeclarator(true);
3223 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3227 DiagnosticBuilder LBraceDiag =
3228 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3230 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3231 // Try recovering from missing { after base-clause.
3233 Tok.setKind(tok::l_brace);
3236 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3242 assert(Tok.is(tok::l_brace));
3243 BalancedDelimiterTracker T(*this, tok::l_brace);
3247 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3248 IsFinalSpelledSealed,
3249 T.getOpenLocation());
3251 // C++ 11p3: Members of a class defined with the keyword class are private
3252 // by default. Members of a class defined with the keywords struct or union
3253 // are public by default.
3254 AccessSpecifier CurAS;
3255 if (TagType == DeclSpec::TST_class)
3259 ParsedAttributesWithRange AccessAttrs(AttrFactory);
3262 // While we still have something to read, read the member-declarations.
3263 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3264 Tok.isNot(tok::eof)) {
3265 // Each iteration of this loop reads one member-declaration.
3266 ParseCXXClassMemberDeclarationWithPragmas(
3267 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3271 SkipUntil(tok::r_brace);
3274 // If attributes exist after class contents, parse them.
3275 ParsedAttributes attrs(AttrFactory);
3276 MaybeParseGNUAttributes(attrs);
3279 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3280 T.getOpenLocation(),
3281 T.getCloseLocation(),
3284 // C++11 [class.mem]p2:
3285 // Within the class member-specification, the class is regarded as complete
3286 // within function bodies, default arguments, exception-specifications, and
3287 // brace-or-equal-initializers for non-static data members (including such
3288 // things in nested classes).
3289 if (TagDecl && NonNestedClass) {
3290 // We are not inside a nested class. This class and its nested classes
3291 // are complete and we can parse the delayed portions of method
3292 // declarations and the lexed inline method definitions, along with any
3293 // delayed attributes.
3294 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3295 ParseLexedAttributes(getCurrentClass());
3296 ParseLexedMethodDeclarations(getCurrentClass());
3298 // We've finished with all pending member declarations.
3299 Actions.ActOnFinishCXXMemberDecls();
3301 ParseLexedMemberInitializers(getCurrentClass());
3302 ParseLexedMethodDefs(getCurrentClass());
3303 PrevTokLocation = SavedPrevTokLocation;
3305 // We've finished parsing everything, including default argument
3307 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3311 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3313 // Leave the class scope.
3318 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3319 assert(Tok.is(tok::kw_namespace));
3321 // FIXME: Suggest where the close brace should have gone by looking
3322 // at indentation changes within the definition body.
3323 Diag(D->getLocation(),
3324 diag::err_missing_end_of_definition) << D;
3325 Diag(Tok.getLocation(),
3326 diag::note_missing_end_of_definition_before) << D;
3328 // Push '};' onto the token stream to recover.
3332 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3333 Tok.setKind(tok::semi);
3336 Tok.setKind(tok::r_brace);
3339 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3340 /// which explicitly initializes the members or base classes of a
3341 /// class (C++ [class.base.init]). For example, the three initializers
3342 /// after the ':' in the Derived constructor below:
3346 /// class Derived : Base {
3350 /// Derived(float f) : Base(), x(17), f(f) { }
3354 /// [C++] ctor-initializer:
3355 /// ':' mem-initializer-list
3357 /// [C++] mem-initializer-list:
3358 /// mem-initializer ...[opt]
3359 /// mem-initializer ...[opt] , mem-initializer-list
3360 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3361 assert(Tok.is(tok::colon) &&
3362 "Constructor initializer always starts with ':'");
3364 // Poison the SEH identifiers so they are flagged as illegal in constructor
3366 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3367 SourceLocation ColonLoc = ConsumeToken();
3369 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3370 bool AnyErrors = false;
3373 if (Tok.is(tok::code_completion)) {
3374 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3376 return cutOffParsing();
3379 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3380 if (!MemInit.isInvalid())
3381 MemInitializers.push_back(MemInit.get());
3385 if (Tok.is(tok::comma))
3387 else if (Tok.is(tok::l_brace))
3389 // If the previous initializer was valid and the next token looks like a
3390 // base or member initializer, assume that we're just missing a comma.
3391 else if (!MemInit.isInvalid() &&
3392 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3393 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3394 Diag(Loc, diag::err_ctor_init_missing_comma)
3395 << FixItHint::CreateInsertion(Loc, ", ");
3397 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3398 if (!MemInit.isInvalid())
3399 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3401 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3406 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3410 /// ParseMemInitializer - Parse a C++ member initializer, which is
3411 /// part of a constructor initializer that explicitly initializes one
3412 /// member or base class (C++ [class.base.init]). See
3413 /// ParseConstructorInitializer for an example.
3415 /// [C++] mem-initializer:
3416 /// mem-initializer-id '(' expression-list[opt] ')'
3417 /// [C++0x] mem-initializer-id braced-init-list
3419 /// [C++] mem-initializer-id:
3420 /// '::'[opt] nested-name-specifier[opt] class-name
3422 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3423 // parse '::'[opt] nested-name-specifier[opt]
3425 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
3428 IdentifierInfo *II = nullptr;
3429 SourceLocation IdLoc = Tok.getLocation();
3431 DeclSpec DS(AttrFactory);
3432 // : template_name<...>
3433 ParsedType TemplateTypeTy;
3435 if (Tok.is(tok::identifier)) {
3436 // Get the identifier. This may be a member name or a class name,
3437 // but we'll let the semantic analysis determine which it is.
3438 II = Tok.getIdentifierInfo();
3440 } else if (Tok.is(tok::annot_decltype)) {
3441 // Get the decltype expression, if there is one.
3442 // Uses of decltype will already have been converted to annot_decltype by
3443 // ParseOptionalCXXScopeSpecifier at this point.
3444 // FIXME: Can we get here with a scope specifier?
3445 ParseDecltypeSpecifier(DS);
3447 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3448 ? takeTemplateIdAnnotation(Tok)
3450 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3451 TemplateId->Kind == TNK_Dependent_template_name)) {
3452 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
3453 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3454 TemplateTypeTy = getTypeAnnotation(Tok);
3455 ConsumeAnnotationToken();
3457 Diag(Tok, diag::err_expected_member_or_base_name);
3463 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3464 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3466 ExprResult InitList = ParseBraceInitializer();
3467 if (InitList.isInvalid())
3470 SourceLocation EllipsisLoc;
3471 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3473 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3474 TemplateTypeTy, DS, IdLoc,
3475 InitList.get(), EllipsisLoc);
3476 } else if(Tok.is(tok::l_paren)) {
3477 BalancedDelimiterTracker T(*this, tok::l_paren);
3480 // Parse the optional expression-list.
3481 ExprVector ArgExprs;
3482 CommaLocsTy CommaLocs;
3483 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
3484 SkipUntil(tok::r_paren, StopAtSemi);
3490 SourceLocation EllipsisLoc;
3491 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3493 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3494 TemplateTypeTy, DS, IdLoc,
3495 T.getOpenLocation(), ArgExprs,
3496 T.getCloseLocation(), EllipsisLoc);
3499 if (getLangOpts().CPlusPlus11)
3500 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3502 return Diag(Tok, diag::err_expected) << tok::l_paren;
3505 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
3507 /// exception-specification:
3508 /// dynamic-exception-specification
3509 /// noexcept-specification
3511 /// noexcept-specification:
3513 /// 'noexcept' '(' constant-expression ')'
3514 ExceptionSpecificationType
3515 Parser::tryParseExceptionSpecification(bool Delayed,
3516 SourceRange &SpecificationRange,
3517 SmallVectorImpl<ParsedType> &DynamicExceptions,
3518 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3519 ExprResult &NoexceptExpr,
3520 CachedTokens *&ExceptionSpecTokens) {
3521 ExceptionSpecificationType Result = EST_None;
3522 ExceptionSpecTokens = nullptr;
3524 // Handle delayed parsing of exception-specifications.
3526 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3529 // Consume and cache the starting token.
3530 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3531 Token StartTok = Tok;
3532 SpecificationRange = SourceRange(ConsumeToken());
3535 if (!Tok.is(tok::l_paren)) {
3536 // If this is a bare 'noexcept', we're done.
3538 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3539 NoexceptExpr = nullptr;
3540 return EST_BasicNoexcept;
3543 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3544 return EST_DynamicNone;
3547 // Cache the tokens for the exception-specification.
3548 ExceptionSpecTokens = new CachedTokens;
3549 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3550 ExceptionSpecTokens->push_back(Tok); // '('
3551 SpecificationRange.setEnd(ConsumeParen()); // '('
3553 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3554 /*StopAtSemi=*/true,
3555 /*ConsumeFinalToken=*/true);
3556 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3558 return EST_Unparsed;
3561 // See if there's a dynamic specification.
3562 if (Tok.is(tok::kw_throw)) {
3563 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3565 DynamicExceptionRanges);
3566 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3567 "Produced different number of exception types and ranges.");
3570 // If there's no noexcept specification, we're done.
3571 if (Tok.isNot(tok::kw_noexcept))
3574 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3576 // If we already had a dynamic specification, parse the noexcept for,
3577 // recovery, but emit a diagnostic and don't store the results.
3578 SourceRange NoexceptRange;
3579 ExceptionSpecificationType NoexceptType = EST_None;
3581 SourceLocation KeywordLoc = ConsumeToken();
3582 if (Tok.is(tok::l_paren)) {
3583 // There is an argument.
3584 BalancedDelimiterTracker T(*this, tok::l_paren);
3586 NoexceptType = EST_ComputedNoexcept;
3587 NoexceptExpr = ParseConstantExpression();
3589 // The argument must be contextually convertible to bool. We use
3590 // CheckBooleanCondition for this purpose.
3591 // FIXME: Add a proper Sema entry point for this.
3592 if (!NoexceptExpr.isInvalid()) {
3594 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
3595 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3597 NoexceptType = EST_BasicNoexcept;
3600 // There is no argument.
3601 NoexceptType = EST_BasicNoexcept;
3602 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3605 if (Result == EST_None) {
3606 SpecificationRange = NoexceptRange;
3607 Result = NoexceptType;
3609 // If there's a dynamic specification after a noexcept specification,
3610 // parse that and ignore the results.
3611 if (Tok.is(tok::kw_throw)) {
3612 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3613 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3614 DynamicExceptionRanges);
3617 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3623 static void diagnoseDynamicExceptionSpecification(
3624 Parser &P, SourceRange Range, bool IsNoexcept) {
3625 if (P.getLangOpts().CPlusPlus11) {
3626 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3627 P.Diag(Range.getBegin(),
3628 P.getLangOpts().CPlusPlus17 && !IsNoexcept
3629 ? diag::ext_dynamic_exception_spec
3630 : diag::warn_exception_spec_deprecated)
3632 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3633 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3637 /// ParseDynamicExceptionSpecification - Parse a C++
3638 /// dynamic-exception-specification (C++ [except.spec]).
3640 /// dynamic-exception-specification:
3641 /// 'throw' '(' type-id-list [opt] ')'
3642 /// [MS] 'throw' '(' '...' ')'
3645 /// type-id ... [opt]
3646 /// type-id-list ',' type-id ... [opt]
3648 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3649 SourceRange &SpecificationRange,
3650 SmallVectorImpl<ParsedType> &Exceptions,
3651 SmallVectorImpl<SourceRange> &Ranges) {
3652 assert(Tok.is(tok::kw_throw) && "expected throw");
3654 SpecificationRange.setBegin(ConsumeToken());
3655 BalancedDelimiterTracker T(*this, tok::l_paren);
3656 if (T.consumeOpen()) {
3657 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3658 SpecificationRange.setEnd(SpecificationRange.getBegin());
3659 return EST_DynamicNone;
3662 // Parse throw(...), a Microsoft extension that means "this function
3663 // can throw anything".
3664 if (Tok.is(tok::ellipsis)) {
3665 SourceLocation EllipsisLoc = ConsumeToken();
3666 if (!getLangOpts().MicrosoftExt)
3667 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3669 SpecificationRange.setEnd(T.getCloseLocation());
3670 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3674 // Parse the sequence of type-ids.
3676 while (Tok.isNot(tok::r_paren)) {
3677 TypeResult Res(ParseTypeName(&Range));
3679 if (Tok.is(tok::ellipsis)) {
3680 // C++0x [temp.variadic]p5:
3681 // - In a dynamic-exception-specification (15.4); the pattern is a
3683 SourceLocation Ellipsis = ConsumeToken();
3684 Range.setEnd(Ellipsis);
3685 if (!Res.isInvalid())
3686 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3689 if (!Res.isInvalid()) {
3690 Exceptions.push_back(Res.get());
3691 Ranges.push_back(Range);
3694 if (!TryConsumeToken(tok::comma))
3699 SpecificationRange.setEnd(T.getCloseLocation());
3700 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3701 Exceptions.empty());
3702 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3705 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3706 /// function declaration.
3707 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3708 assert(Tok.is(tok::arrow) && "expected arrow");
3712 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3715 /// \brief We have just started parsing the definition of a new class,
3716 /// so push that class onto our stack of classes that is currently
3718 Sema::ParsingClassState
3719 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3721 assert((NonNestedClass || !ClassStack.empty()) &&
3722 "Nested class without outer class");
3723 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3724 return Actions.PushParsingClass();
3727 /// \brief Deallocate the given parsed class and all of its nested
3729 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3730 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3731 delete Class->LateParsedDeclarations[I];
3735 /// \brief Pop the top class of the stack of classes that are
3736 /// currently being parsed.
3738 /// This routine should be called when we have finished parsing the
3739 /// definition of a class, but have not yet popped the Scope
3740 /// associated with the class's definition.
3741 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3742 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3744 Actions.PopParsingClass(state);
3746 ParsingClass *Victim = ClassStack.top();
3748 if (Victim->TopLevelClass) {
3749 // Deallocate all of the nested classes of this class,
3750 // recursively: we don't need to keep any of this information.
3751 DeallocateParsedClasses(Victim);
3754 assert(!ClassStack.empty() && "Missing top-level class?");
3756 if (Victim->LateParsedDeclarations.empty()) {
3757 // The victim is a nested class, but we will not need to perform
3758 // any processing after the definition of this class since it has
3759 // no members whose handling was delayed. Therefore, we can just
3760 // remove this nested class.
3761 DeallocateParsedClasses(Victim);
3765 // This nested class has some members that will need to be processed
3766 // after the top-level class is completely defined. Therefore, add
3767 // it to the list of nested classes within its parent.
3768 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3769 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3770 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3773 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3775 /// \return the parsed identifier on success, and 0 if the next token is not an
3776 /// attribute-token.
3778 /// C++11 [dcl.attr.grammar]p3:
3779 /// If a keyword or an alternative token that satisfies the syntactic
3780 /// requirements of an identifier is contained in an attribute-token,
3781 /// it is considered an identifier.
3782 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3783 switch (Tok.getKind()) {
3785 // Identifiers and keywords have identifier info attached.
3786 if (!Tok.isAnnotation()) {
3787 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3788 Loc = ConsumeToken();
3794 case tok::ampamp: // 'and'
3795 case tok::pipe: // 'bitor'
3796 case tok::pipepipe: // 'or'
3797 case tok::caret: // 'xor'
3798 case tok::tilde: // 'compl'
3799 case tok::amp: // 'bitand'
3800 case tok::ampequal: // 'and_eq'
3801 case tok::pipeequal: // 'or_eq'
3802 case tok::caretequal: // 'xor_eq'
3803 case tok::exclaim: // 'not'
3804 case tok::exclaimequal: // 'not_eq'
3805 // Alternative tokens do not have identifier info, but their spelling
3806 // starts with an alphabetical character.
3807 SmallString<8> SpellingBuf;
3808 SourceLocation SpellingLoc =
3809 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3810 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3811 if (isLetter(Spelling[0])) {
3812 Loc = ConsumeToken();
3813 return &PP.getIdentifierTable().get(Spelling);
3819 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3820 IdentifierInfo *ScopeName) {
3821 switch (AttributeList::getKind(AttrName, ScopeName,
3822 AttributeList::AS_CXX11)) {
3823 case AttributeList::AT_CarriesDependency:
3824 case AttributeList::AT_Deprecated:
3825 case AttributeList::AT_FallThrough:
3826 case AttributeList::AT_CXX11NoReturn:
3828 case AttributeList::AT_WarnUnusedResult:
3829 return !ScopeName && AttrName->getName().equals("nodiscard");
3830 case AttributeList::AT_Unused:
3831 return !ScopeName && AttrName->getName().equals("maybe_unused");
3837 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3839 /// [C++11] attribute-argument-clause:
3840 /// '(' balanced-token-seq ')'
3842 /// [C++11] balanced-token-seq:
3844 /// balanced-token-seq balanced-token
3846 /// [C++11] balanced-token:
3847 /// '(' balanced-token-seq ')'
3848 /// '[' balanced-token-seq ']'
3849 /// '{' balanced-token-seq '}'
3850 /// any token but '(', ')', '[', ']', '{', or '}'
3851 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3852 SourceLocation AttrNameLoc,
3853 ParsedAttributes &Attrs,
3854 SourceLocation *EndLoc,
3855 IdentifierInfo *ScopeName,
3856 SourceLocation ScopeLoc) {
3857 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3858 SourceLocation LParenLoc = Tok.getLocation();
3859 const LangOptions &LO = getLangOpts();
3860 AttributeList::Syntax Syntax =
3861 LO.CPlusPlus ? AttributeList::AS_CXX11 : AttributeList::AS_C2x;
3863 // If the attribute isn't known, we will not attempt to parse any
3865 if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
3866 AttrName, getTargetInfo(), getLangOpts())) {
3867 // Eat the left paren, then skip to the ending right paren.
3869 SkipUntil(tok::r_paren);
3873 if (ScopeName && ScopeName->getName() == "gnu") {
3874 // GNU-scoped attributes have some special cases to handle GNU-specific
3876 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3877 ScopeLoc, Syntax, nullptr);
3882 // Some Clang-scoped attributes have some special parsing behavior.
3883 if (ScopeName && ScopeName->getName() == "clang")
3885 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3889 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3890 ScopeName, ScopeLoc, Syntax);
3892 const AttributeList *Attr = Attrs.getList();
3893 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3894 // If the attribute is a standard or built-in attribute and we are
3895 // parsing an argument list, we need to determine whether this attribute
3896 // was allowed to have an argument list (such as [[deprecated]]), and how
3897 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3898 if (Attr->getMaxArgs() && !NumArgs) {
3899 // The attribute was allowed to have arguments, but none were provided
3900 // even though the attribute parsed successfully. This is an error.
3901 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3902 Attr->setInvalid(true);
3903 } else if (!Attr->getMaxArgs()) {
3904 // The attribute parsed successfully, but was not allowed to have any
3905 // arguments. It doesn't matter whether any were provided -- the
3906 // presence of the argument list (even if empty) is diagnosed.
3907 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3909 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3910 Attr->setInvalid(true);
3916 /// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
3918 /// [C++11] attribute-specifier:
3919 /// '[' '[' attribute-list ']' ']'
3920 /// alignment-specifier
3922 /// [C++11] attribute-list:
3924 /// attribute-list ',' attribute[opt]
3926 /// attribute-list ',' attribute '...'
3928 /// [C++11] attribute:
3929 /// attribute-token attribute-argument-clause[opt]
3931 /// [C++11] attribute-token:
3933 /// attribute-scoped-token
3935 /// [C++11] attribute-scoped-token:
3936 /// attribute-namespace '::' identifier
3938 /// [C++11] attribute-namespace:
3940 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3941 SourceLocation *endLoc) {
3942 if (Tok.is(tok::kw_alignas)) {
3943 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3944 ParseAlignmentSpecifier(attrs, endLoc);
3948 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
3949 "Not a double square bracket attribute list");
3951 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3956 SourceLocation CommonScopeLoc;
3957 IdentifierInfo *CommonScopeName = nullptr;
3958 if (Tok.is(tok::kw_using)) {
3959 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
3960 ? diag::warn_cxx14_compat_using_attribute_ns
3961 : diag::ext_using_attribute_ns);
3964 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3965 if (!CommonScopeName) {
3966 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3967 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3969 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3970 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3973 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3975 while (Tok.isNot(tok::r_square)) {
3976 // attribute not present
3977 if (TryConsumeToken(tok::comma))
3980 SourceLocation ScopeLoc, AttrLoc;
3981 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3983 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3985 // Break out to the "expected ']'" diagnostic.
3989 if (TryConsumeToken(tok::coloncolon)) {
3990 ScopeName = AttrName;
3993 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3995 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3996 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
4001 if (CommonScopeName) {
4003 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
4004 << SourceRange(CommonScopeLoc);
4006 ScopeName = CommonScopeName;
4007 ScopeLoc = CommonScopeLoc;
4011 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
4012 bool AttrParsed = false;
4015 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4016 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
4017 << AttrName << SourceRange(SeenAttrs[AttrName]);
4019 // Parse attribute arguments
4020 if (Tok.is(tok::l_paren))
4021 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4022 ScopeName, ScopeLoc);
4027 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
4028 ScopeName, ScopeLoc, nullptr, 0,
4029 getLangOpts().CPlusPlus ? AttributeList::AS_CXX11
4030 : AttributeList::AS_C2x);
4032 if (TryConsumeToken(tok::ellipsis))
4033 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4034 << AttrName->getName();
4037 if (ExpectAndConsume(tok::r_square))
4038 SkipUntil(tok::r_square);
4040 *endLoc = Tok.getLocation();
4041 if (ExpectAndConsume(tok::r_square))
4042 SkipUntil(tok::r_square);
4045 /// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
4047 /// attribute-specifier-seq:
4048 /// attribute-specifier-seq[opt] attribute-specifier
4049 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
4050 SourceLocation *endLoc) {
4051 assert(standardAttributesAllowed());
4053 SourceLocation StartLoc = Tok.getLocation(), Loc;
4058 ParseCXX11AttributeSpecifier(attrs, endLoc);
4059 } while (isCXX11AttributeSpecifier());
4061 attrs.Range = SourceRange(StartLoc, *endLoc);
4064 void Parser::DiagnoseAndSkipCXX11Attributes() {
4065 // Start and end location of an attribute or an attribute list.
4066 SourceLocation StartLoc = Tok.getLocation();
4067 SourceLocation EndLoc = SkipCXX11Attributes();
4069 if (EndLoc.isValid()) {
4070 SourceRange Range(StartLoc, EndLoc);
4071 Diag(StartLoc, diag::err_attributes_not_allowed)
4076 SourceLocation Parser::SkipCXX11Attributes() {
4077 SourceLocation EndLoc;
4079 if (!isCXX11AttributeSpecifier())
4083 if (Tok.is(tok::l_square)) {
4084 BalancedDelimiterTracker T(*this, tok::l_square);
4087 EndLoc = T.getCloseLocation();
4089 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4091 BalancedDelimiterTracker T(*this, tok::l_paren);
4092 if (!T.consumeOpen())
4094 EndLoc = T.getCloseLocation();
4096 } while (isCXX11AttributeSpecifier());
4101 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4102 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4103 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4104 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4105 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4107 SourceLocation UuidLoc = Tok.getLocation();
4110 // Ignore the left paren location for now.
4111 BalancedDelimiterTracker T(*this, tok::l_paren);
4112 if (T.consumeOpen()) {
4113 Diag(Tok, diag::err_expected) << tok::l_paren;
4117 ArgsVector ArgExprs;
4118 if (Tok.is(tok::string_literal)) {
4119 // Easy case: uuid("...") -- quoted string.
4120 ExprResult StringResult = ParseStringLiteralExpression();
4121 if (StringResult.isInvalid())
4123 ArgExprs.push_back(StringResult.get());
4125 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4126 // quotes in the parens. Just append the spelling of all tokens encountered
4127 // until the closing paren.
4129 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4132 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4133 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4134 // tok::numeric_constant (0000) should be enough. But the spelling of the
4135 // uuid argument is checked later anyways, so there's no harm in accepting
4136 // almost anything here.
4137 // cl is very strict about whitespace in this form and errors out if any
4138 // is present, so check the space flags on the tokens.
4139 SourceLocation StartLoc = Tok.getLocation();
4140 while (Tok.isNot(tok::r_paren)) {
4141 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4142 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4143 SkipUntil(tok::r_paren, StopAtSemi);
4146 SmallString<16> SpellingBuffer;
4147 SpellingBuffer.resize(Tok.getLength() + 1);
4148 bool Invalid = false;
4149 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4151 SkipUntil(tok::r_paren, StopAtSemi);
4154 StrBuffer += TokSpelling;
4159 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4160 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4165 // Pretend the user wrote the appropriate string literal here.
4166 // ActOnStringLiteral() copies the string data into the literal, so it's
4167 // ok that the Token points to StrBuffer.
4169 Toks[0].startToken();
4170 Toks[0].setKind(tok::string_literal);
4171 Toks[0].setLocation(StartLoc);
4172 Toks[0].setLiteralData(StrBuffer.data());
4173 Toks[0].setLength(StrBuffer.size());
4174 StringLiteral *UuidString =
4175 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4176 ArgExprs.push_back(UuidString);
4179 if (!T.consumeClose()) {
4180 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4181 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4182 AttributeList::AS_Microsoft);
4186 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4188 /// [MS] ms-attribute:
4189 /// '[' token-seq ']'
4191 /// [MS] ms-attribute-seq:
4192 /// ms-attribute[opt]
4193 /// ms-attribute ms-attribute-seq
4194 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4195 SourceLocation *endLoc) {
4196 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4199 // FIXME: If this is actually a C++11 attribute, parse it as one.
4200 BalancedDelimiterTracker T(*this, tok::l_square);
4203 // Skip most ms attributes except for a whitelist.
4205 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4206 if (Tok.isNot(tok::identifier)) // ']', but also eof
4208 if (Tok.getIdentifierInfo()->getName() == "uuid")
4209 ParseMicrosoftUuidAttributeArgs(attrs);
4216 *endLoc = T.getCloseLocation();
4217 } while (Tok.is(tok::l_square));
4220 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4221 AccessSpecifier& CurAS) {
4222 IfExistsCondition Result;
4223 if (ParseMicrosoftIfExistsCondition(Result))
4226 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4227 if (Braces.consumeOpen()) {
4228 Diag(Tok, diag::err_expected) << tok::l_brace;
4232 switch (Result.Behavior) {
4234 // Parse the declarations below.
4238 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4239 << Result.IsIfExists;
4240 // Fall through to skip.
4248 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4249 // __if_exists, __if_not_exists can nest.
4250 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4251 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4255 // Check for extraneous top-level semicolon.
4256 if (Tok.is(tok::semi)) {
4257 ConsumeExtraSemi(InsideStruct, TagType);
4261 AccessSpecifier AS = getAccessSpecifierIfPresent();
4262 if (AS != AS_none) {
4263 // Current token is a C++ access specifier.
4265 SourceLocation ASLoc = Tok.getLocation();
4267 if (Tok.is(tok::colon))
4268 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4270 Diag(Tok, diag::err_expected) << tok::colon;
4275 // Parse all the comma separated declarators.
4276 ParseCXXClassMemberDeclaration(CurAS, nullptr);
4279 Braces.consumeClose();