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 if (!getLangOpts().CPlusPlus1z)
81 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
83 attrLoc = Tok.getLocation();
84 ParseCXX11Attributes(attrs);
87 if (Tok.is(tok::identifier)) {
88 Ident = Tok.getIdentifierInfo();
89 IdentLoc = ConsumeToken(); // eat the identifier.
90 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
91 ExtraNamespaceLoc.push_back(ConsumeToken());
92 ExtraIdent.push_back(Tok.getIdentifierInfo());
93 ExtraIdentLoc.push_back(ConsumeToken());
97 // A nested namespace definition cannot have attributes.
98 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
99 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
101 // Read label attributes, if present.
102 if (Tok.is(tok::kw___attribute)) {
103 attrLoc = Tok.getLocation();
104 ParseGNUAttributes(attrs);
107 if (Tok.is(tok::equal)) {
109 Diag(Tok, diag::err_expected) << tok::identifier;
110 // Skip to end of the definition and eat the ';'.
111 SkipUntil(tok::semi);
114 if (attrLoc.isValid())
115 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
116 if (InlineLoc.isValid())
117 Diag(InlineLoc, diag::err_inline_namespace_alias)
118 << FixItHint::CreateRemoval(InlineLoc);
119 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
120 return Actions.ConvertDeclToDeclGroup(NSAlias);
123 BalancedDelimiterTracker T(*this, tok::l_brace);
124 if (T.consumeOpen()) {
126 Diag(Tok, diag::err_expected) << tok::l_brace;
128 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
132 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
133 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
134 getCurScope()->getFnParent()) {
135 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
136 SkipUntil(tok::r_brace);
140 if (ExtraIdent.empty()) {
141 // Normal namespace definition, not a nested-namespace-definition.
142 } else if (InlineLoc.isValid()) {
143 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
144 } else if (getLangOpts().CPlusPlus1z) {
145 Diag(ExtraNamespaceLoc[0],
146 diag::warn_cxx14_compat_nested_namespace_definition);
148 TentativeParsingAction TPA(*this);
149 SkipUntil(tok::r_brace, StopBeforeMatch);
150 Token rBraceToken = Tok;
153 if (!rBraceToken.is(tok::r_brace)) {
154 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
155 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
157 std::string NamespaceFix;
158 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
159 E = ExtraIdent.end(); I != E; ++I) {
160 NamespaceFix += " { namespace ";
161 NamespaceFix += (*I)->getName();
165 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
168 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
169 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
170 ExtraIdentLoc.back()),
172 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
176 // If we're still good, complain about inline namespaces in non-C++0x now.
177 if (InlineLoc.isValid())
178 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
179 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
181 // Enter a scope for the namespace.
182 ParseScope NamespaceScope(this, Scope::DeclScope);
184 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
186 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
187 IdentLoc, Ident, T.getOpenLocation(),
188 attrs.getList(), ImplicitUsingDirectiveDecl);
190 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
191 "parsing namespace");
193 // Parse the contents of the namespace. This includes parsing recovery on
194 // any improperly nested namespaces.
195 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
196 InlineLoc, attrs, T);
198 // Leave the namespace scope.
199 NamespaceScope.Exit();
201 DeclEnd = T.getCloseLocation();
202 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
204 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
205 ImplicitUsingDirectiveDecl);
208 /// ParseInnerNamespace - Parse the contents of a namespace.
209 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
210 std::vector<IdentifierInfo *> &Ident,
211 std::vector<SourceLocation> &NamespaceLoc,
212 unsigned int index, SourceLocation &InlineLoc,
213 ParsedAttributes &attrs,
214 BalancedDelimiterTracker &Tracker) {
215 if (index == Ident.size()) {
216 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
217 Tok.isNot(tok::eof)) {
218 ParsedAttributesWithRange attrs(AttrFactory);
219 MaybeParseCXX11Attributes(attrs);
220 ParseExternalDeclaration(attrs);
223 // The caller is what called check -- we are simply calling
225 Tracker.consumeClose();
230 // Handle a nested namespace definition.
231 // FIXME: Preserve the source information through to the AST rather than
232 // desugaring it here.
233 ParseScope NamespaceScope(this, Scope::DeclScope);
234 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
236 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
237 NamespaceLoc[index], IdentLoc[index],
238 Ident[index], Tracker.getOpenLocation(),
239 attrs.getList(), ImplicitUsingDirectiveDecl);
240 assert(!ImplicitUsingDirectiveDecl &&
241 "nested namespace definition cannot define anonymous namespace");
243 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
246 NamespaceScope.Exit();
247 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
250 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
251 /// alias definition.
253 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
254 SourceLocation AliasLoc,
255 IdentifierInfo *Alias,
256 SourceLocation &DeclEnd) {
257 assert(Tok.is(tok::equal) && "Not equal token");
259 ConsumeToken(); // eat the '='.
261 if (Tok.is(tok::code_completion)) {
262 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
268 // Parse (optional) nested-name-specifier.
269 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
270 /*MayBePseudoDestructor=*/nullptr,
271 /*IsTypename=*/false,
273 /*OnlyNamespace=*/true);
275 if (Tok.isNot(tok::identifier)) {
276 Diag(Tok, diag::err_expected_namespace_name);
277 // Skip to end of the definition and eat the ';'.
278 SkipUntil(tok::semi);
282 if (SS.isInvalid()) {
283 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
284 // Skip to end of the definition and eat the ';'.
285 SkipUntil(tok::semi);
290 IdentifierInfo *Ident = Tok.getIdentifierInfo();
291 SourceLocation IdentLoc = ConsumeToken();
294 DeclEnd = Tok.getLocation();
295 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
296 SkipUntil(tok::semi);
298 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
299 Alias, SS, IdentLoc, Ident);
302 /// ParseLinkage - We know that the current token is a string_literal
303 /// and just before that, that extern was seen.
305 /// linkage-specification: [C++ 7.5p2: dcl.link]
306 /// 'extern' string-literal '{' declaration-seq[opt] '}'
307 /// 'extern' string-literal declaration
309 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
310 assert(isTokenStringLiteral() && "Not a string literal!");
311 ExprResult Lang = ParseStringLiteralExpression(false);
313 ParseScope LinkageScope(this, Scope::DeclScope);
317 : Actions.ActOnStartLinkageSpecification(
318 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
319 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
321 ParsedAttributesWithRange attrs(AttrFactory);
322 MaybeParseCXX11Attributes(attrs);
324 if (Tok.isNot(tok::l_brace)) {
325 // Reset the source range in DS, as the leading "extern"
326 // does not really belong to the inner declaration ...
327 DS.SetRangeStart(SourceLocation());
328 DS.SetRangeEnd(SourceLocation());
329 // ... but anyway remember that such an "extern" was seen.
330 DS.setExternInLinkageSpec(true);
331 ParseExternalDeclaration(attrs, &DS);
332 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
333 getCurScope(), LinkageSpec, SourceLocation())
339 ProhibitAttributes(attrs);
341 BalancedDelimiterTracker T(*this, tok::l_brace);
344 unsigned NestedModules = 0;
346 switch (Tok.getKind()) {
347 case tok::annot_module_begin:
352 case tok::annot_module_end:
359 case tok::annot_module_include:
371 ParsedAttributesWithRange attrs(AttrFactory);
372 MaybeParseCXX11Attributes(attrs);
373 ParseExternalDeclaration(attrs);
381 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
382 getCurScope(), LinkageSpec, T.getCloseLocation())
386 /// Parse a C++ Modules TS export-declaration.
388 /// export-declaration:
389 /// 'export' declaration
390 /// 'export' '{' declaration-seq[opt] '}'
392 Decl *Parser::ParseExportDeclaration() {
393 assert(Tok.is(tok::kw_export));
394 SourceLocation ExportLoc = ConsumeToken();
396 ParseScope ExportScope(this, Scope::DeclScope);
397 Decl *ExportDecl = Actions.ActOnStartExportDecl(
398 getCurScope(), ExportLoc,
399 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
401 if (Tok.isNot(tok::l_brace)) {
402 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
403 ParsedAttributesWithRange Attrs(AttrFactory);
404 MaybeParseCXX11Attributes(Attrs);
405 MaybeParseMicrosoftAttributes(Attrs);
406 ParseExternalDeclaration(Attrs);
407 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
411 BalancedDelimiterTracker T(*this, tok::l_brace);
414 // The Modules TS draft says "An export-declaration shall declare at least one
415 // entity", but the intent is that it shall contain at least one declaration.
416 if (Tok.is(tok::r_brace))
417 Diag(ExportLoc, diag::err_export_empty)
418 << SourceRange(ExportLoc, Tok.getLocation());
420 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
421 Tok.isNot(tok::eof)) {
422 ParsedAttributesWithRange Attrs(AttrFactory);
423 MaybeParseCXX11Attributes(Attrs);
424 MaybeParseMicrosoftAttributes(Attrs);
425 ParseExternalDeclaration(Attrs);
429 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
430 T.getCloseLocation());
433 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
434 /// using-directive. Assumes that current token is 'using'.
435 Parser::DeclGroupPtrTy
436 Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
437 const ParsedTemplateInfo &TemplateInfo,
438 SourceLocation &DeclEnd,
439 ParsedAttributesWithRange &attrs) {
440 assert(Tok.is(tok::kw_using) && "Not using token");
441 ObjCDeclContextSwitch ObjCDC(*this);
444 SourceLocation UsingLoc = ConsumeToken();
446 if (Tok.is(tok::code_completion)) {
447 Actions.CodeCompleteUsing(getCurScope());
452 // 'using namespace' means this is a using-directive.
453 if (Tok.is(tok::kw_namespace)) {
454 // Template parameters are always an error here.
455 if (TemplateInfo.Kind) {
456 SourceRange R = TemplateInfo.getSourceRange();
457 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
458 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
461 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
462 return Actions.ConvertDeclToDeclGroup(UsingDir);
465 // Otherwise, it must be a using-declaration or an alias-declaration.
467 // Using declarations can't have attributes.
468 ProhibitAttributes(attrs);
470 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
474 /// ParseUsingDirective - Parse C++ using-directive, assumes
475 /// that current token is 'namespace' and 'using' was already parsed.
477 /// using-directive: [C++ 7.3.p4: namespace.udir]
478 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
480 /// [GNU] using-directive:
481 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
482 /// namespace-name attributes[opt] ;
484 Decl *Parser::ParseUsingDirective(unsigned Context,
485 SourceLocation UsingLoc,
486 SourceLocation &DeclEnd,
487 ParsedAttributes &attrs) {
488 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
491 SourceLocation NamespcLoc = ConsumeToken();
493 if (Tok.is(tok::code_completion)) {
494 Actions.CodeCompleteUsingDirective(getCurScope());
500 // Parse (optional) nested-name-specifier.
501 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
502 /*MayBePseudoDestructor=*/nullptr,
503 /*IsTypename=*/false,
505 /*OnlyNamespace=*/true);
507 IdentifierInfo *NamespcName = nullptr;
508 SourceLocation IdentLoc = SourceLocation();
510 // Parse namespace-name.
511 if (Tok.isNot(tok::identifier)) {
512 Diag(Tok, diag::err_expected_namespace_name);
513 // If there was invalid namespace name, skip to end of decl, and eat ';'.
514 SkipUntil(tok::semi);
515 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
519 if (SS.isInvalid()) {
520 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
521 // Skip to end of the definition and eat the ';'.
522 SkipUntil(tok::semi);
527 NamespcName = Tok.getIdentifierInfo();
528 IdentLoc = ConsumeToken();
530 // Parse (optional) attributes (most likely GNU strong-using extension).
531 bool GNUAttr = false;
532 if (Tok.is(tok::kw___attribute)) {
534 ParseGNUAttributes(attrs);
538 DeclEnd = Tok.getLocation();
539 if (ExpectAndConsume(tok::semi,
540 GNUAttr ? diag::err_expected_semi_after_attribute_list
541 : diag::err_expected_semi_after_namespace_name))
542 SkipUntil(tok::semi);
544 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
545 IdentLoc, NamespcName, attrs.getList());
548 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
550 /// using-declarator:
551 /// 'typename'[opt] nested-name-specifier unqualified-id
553 bool Parser::ParseUsingDeclarator(unsigned Context, UsingDeclarator &D) {
556 // Ignore optional 'typename'.
557 // FIXME: This is wrong; we should parse this as a typename-specifier.
558 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
560 if (Tok.is(tok::kw___super)) {
561 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
565 // Parse nested-name-specifier.
566 IdentifierInfo *LastII = nullptr;
567 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
568 /*MayBePseudoDtor=*/nullptr,
569 /*IsTypename=*/false,
571 if (D.SS.isInvalid())
574 // Parse the unqualified-id. We allow parsing of both constructor and
575 // destructor names and allow the action module to diagnose any semantic
578 // C++11 [class.qual]p2:
579 // [...] in a using-declaration that is a member-declaration, if the name
580 // specified after the nested-name-specifier is the same as the identifier
581 // or the simple-template-id's template-name in the last component of the
582 // nested-name-specifier, the name is [...] considered to name the
584 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
585 Tok.is(tok::identifier) &&
586 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
587 NextToken().is(tok::ellipsis)) &&
588 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
589 !D.SS.getScopeRep()->getAsNamespace() &&
590 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
591 SourceLocation IdLoc = ConsumeToken();
593 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
594 D.Name.setConstructorName(Type, IdLoc, IdLoc);
596 if (ParseUnqualifiedId(
597 D.SS, /*EnteringContext=*/false,
598 /*AllowDestructorName=*/true,
599 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
600 NextToken().is(tok::equal)),
601 /*AllowDeductionGuide=*/false,
602 nullptr, D.TemplateKWLoc, D.Name))
606 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
607 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z ?
608 diag::warn_cxx1z_compat_using_declaration_pack :
609 diag::ext_using_declaration_pack);
614 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
615 /// Assumes that 'using' was already seen.
617 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
618 /// 'using' using-declarator-list[opt] ;
620 /// using-declarator-list: [C++1z]
621 /// using-declarator '...'[opt]
622 /// using-declarator-list ',' using-declarator '...'[opt]
624 /// using-declarator-list: [C++98-14]
627 /// alias-declaration: C++11 [dcl.dcl]p1
628 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
630 Parser::DeclGroupPtrTy
631 Parser::ParseUsingDeclaration(unsigned Context,
632 const ParsedTemplateInfo &TemplateInfo,
633 SourceLocation UsingLoc, SourceLocation &DeclEnd,
634 AccessSpecifier AS) {
635 // Check for misplaced attributes before the identifier in an
636 // alias-declaration.
637 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
638 MaybeParseCXX11Attributes(MisplacedAttrs);
641 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
643 ParsedAttributesWithRange Attrs(AttrFactory);
644 MaybeParseGNUAttributes(Attrs);
645 MaybeParseCXX11Attributes(Attrs);
647 // Maybe this is an alias-declaration.
648 if (Tok.is(tok::equal)) {
649 if (InvalidDeclarator) {
650 SkipUntil(tok::semi);
654 // If we had any misplaced attributes from earlier, this is where they
655 // should have been written.
656 if (MisplacedAttrs.Range.isValid()) {
657 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
658 << FixItHint::CreateInsertionFromRange(
660 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
661 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
662 Attrs.takeAllFrom(MisplacedAttrs);
665 Decl *DeclFromDeclSpec = nullptr;
666 Decl *AD = ParseAliasDeclarationAfterDeclarator(
667 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
668 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
671 // C++11 attributes are not allowed on a using-declaration, but GNU ones
673 ProhibitAttributes(MisplacedAttrs);
674 ProhibitAttributes(Attrs);
676 // Diagnose an attempt to declare a templated using-declaration.
677 // In C++11, alias-declarations can be templates:
678 // template <...> using id = type;
679 if (TemplateInfo.Kind) {
680 SourceRange R = TemplateInfo.getSourceRange();
681 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
682 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
684 // Unfortunately, we have to bail out instead of recovering by
685 // ignoring the parameters, just in case the nested name specifier
686 // depends on the parameters.
690 SmallVector<Decl *, 8> DeclsInGroup;
692 // Parse (optional) attributes (most likely GNU strong-using extension).
693 MaybeParseGNUAttributes(Attrs);
695 if (InvalidDeclarator)
696 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
698 // "typename" keyword is allowed for identifiers only,
699 // because it may be a type definition.
700 if (D.TypenameLoc.isValid() &&
701 D.Name.getKind() != UnqualifiedId::IK_Identifier) {
702 Diag(D.Name.getSourceRange().getBegin(),
703 diag::err_typename_identifiers_only)
704 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
705 // Proceed parsing, but discard the typename keyword.
706 D.TypenameLoc = SourceLocation();
709 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
710 D.TypenameLoc, D.SS, D.Name,
711 D.EllipsisLoc, Attrs.getList());
713 DeclsInGroup.push_back(UD);
716 if (!TryConsumeToken(tok::comma))
719 // Parse another using-declarator.
721 InvalidDeclarator = ParseUsingDeclarator(Context, D);
724 if (DeclsInGroup.size() > 1)
725 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z ?
726 diag::warn_cxx1z_compat_multi_using_declaration :
727 diag::ext_multi_using_declaration);
730 DeclEnd = Tok.getLocation();
731 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
732 !Attrs.empty() ? "attributes list"
733 : "using declaration"))
734 SkipUntil(tok::semi);
736 return Actions.BuildDeclaratorGroup(DeclsInGroup);
739 Decl *Parser::ParseAliasDeclarationAfterDeclarator(
740 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
741 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
742 ParsedAttributes &Attrs, Decl **OwnedType) {
743 if (ExpectAndConsume(tok::equal)) {
744 SkipUntil(tok::semi);
748 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
749 diag::warn_cxx98_compat_alias_declaration :
750 diag::ext_alias_declaration);
752 // Type alias templates cannot be specialized.
754 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
755 D.Name.getKind() == UnqualifiedId::IK_TemplateId)
757 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
759 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
761 if (SpecKind != -1) {
764 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
765 D.Name.TemplateId->RAngleLoc);
767 Range = TemplateInfo.getSourceRange();
768 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
769 << SpecKind << Range;
770 SkipUntil(tok::semi);
774 // Name must be an identifier.
775 if (D.Name.getKind() != UnqualifiedId::IK_Identifier) {
776 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
777 // No removal fixit: can't recover from this.
778 SkipUntil(tok::semi);
780 } else if (D.TypenameLoc.isValid())
781 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
782 << FixItHint::CreateRemoval(SourceRange(
784 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
785 else if (D.SS.isNotEmpty())
786 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
787 << FixItHint::CreateRemoval(D.SS.getRange());
788 if (D.EllipsisLoc.isValid())
789 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
790 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
792 Decl *DeclFromDeclSpec = nullptr;
793 TypeResult TypeAlias =
794 ParseTypeName(nullptr,
795 TemplateInfo.Kind ? Declarator::AliasTemplateContext
796 : Declarator::AliasDeclContext,
797 AS, &DeclFromDeclSpec, &Attrs);
799 *OwnedType = DeclFromDeclSpec;
802 DeclEnd = Tok.getLocation();
803 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
804 !Attrs.empty() ? "attributes list"
805 : "alias declaration"))
806 SkipUntil(tok::semi);
808 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
809 MultiTemplateParamsArg TemplateParamsArg(
810 TemplateParams ? TemplateParams->data() : nullptr,
811 TemplateParams ? TemplateParams->size() : 0);
812 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
813 UsingLoc, D.Name, Attrs.getList(),
814 TypeAlias, DeclFromDeclSpec);
817 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
819 /// [C++0x] static_assert-declaration:
820 /// static_assert ( constant-expression , string-literal ) ;
822 /// [C11] static_assert-declaration:
823 /// _Static_assert ( constant-expression , string-literal ) ;
825 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
826 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
827 "Not a static_assert declaration");
829 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
830 Diag(Tok, diag::ext_c11_static_assert);
831 if (Tok.is(tok::kw_static_assert))
832 Diag(Tok, diag::warn_cxx98_compat_static_assert);
834 SourceLocation StaticAssertLoc = ConsumeToken();
836 BalancedDelimiterTracker T(*this, tok::l_paren);
837 if (T.consumeOpen()) {
838 Diag(Tok, diag::err_expected) << tok::l_paren;
843 ExprResult AssertExpr(ParseConstantExpression());
844 if (AssertExpr.isInvalid()) {
849 ExprResult AssertMessage;
850 if (Tok.is(tok::r_paren)) {
851 Diag(Tok, getLangOpts().CPlusPlus1z
852 ? diag::warn_cxx14_compat_static_assert_no_message
853 : diag::ext_static_assert_no_message)
854 << (getLangOpts().CPlusPlus1z
856 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
858 if (ExpectAndConsume(tok::comma)) {
859 SkipUntil(tok::semi);
863 if (!isTokenStringLiteral()) {
864 Diag(Tok, diag::err_expected_string_literal)
865 << /*Source='static_assert'*/1;
870 AssertMessage = ParseStringLiteralExpression();
871 if (AssertMessage.isInvalid()) {
879 DeclEnd = Tok.getLocation();
880 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
882 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
885 T.getCloseLocation());
888 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
890 /// 'decltype' ( expression )
891 /// 'decltype' ( 'auto' ) [C++1y]
893 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
894 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
895 && "Not a decltype specifier");
898 SourceLocation StartLoc = Tok.getLocation();
899 SourceLocation EndLoc;
901 if (Tok.is(tok::annot_decltype)) {
902 Result = getExprAnnotation(Tok);
903 EndLoc = Tok.getAnnotationEndLoc();
904 ConsumeAnnotationToken();
905 if (Result.isInvalid()) {
906 DS.SetTypeSpecError();
910 if (Tok.getIdentifierInfo()->isStr("decltype"))
911 Diag(Tok, diag::warn_cxx98_compat_decltype);
915 BalancedDelimiterTracker T(*this, tok::l_paren);
916 if (T.expectAndConsume(diag::err_expected_lparen_after,
917 "decltype", tok::r_paren)) {
918 DS.SetTypeSpecError();
919 return T.getOpenLocation() == Tok.getLocation() ?
920 StartLoc : T.getOpenLocation();
923 // Check for C++1y 'decltype(auto)'.
924 if (Tok.is(tok::kw_auto)) {
925 // No need to disambiguate here: an expression can't start with 'auto',
926 // because the typename-specifier in a function-style cast operation can't
928 Diag(Tok.getLocation(),
929 getLangOpts().CPlusPlus14
930 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
931 : diag::ext_decltype_auto_type_specifier);
934 // Parse the expression
936 // C++11 [dcl.type.simple]p4:
937 // The operand of the decltype specifier is an unevaluated operand.
938 EnterExpressionEvaluationContext Unevaluated(
939 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
940 /*IsDecltype=*/true);
942 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
943 return E->hasPlaceholderType() ? ExprError() : E;
945 if (Result.isInvalid()) {
946 DS.SetTypeSpecError();
947 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
948 EndLoc = ConsumeParen();
950 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
951 // Backtrack to get the location of the last token before the semi.
952 PP.RevertCachedTokens(2);
953 ConsumeToken(); // the semi.
954 EndLoc = ConsumeAnyToken();
955 assert(Tok.is(tok::semi));
957 EndLoc = Tok.getLocation();
963 Result = Actions.ActOnDecltypeExpression(Result.get());
968 if (T.getCloseLocation().isInvalid()) {
969 DS.SetTypeSpecError();
970 // FIXME: this should return the location of the last token
971 // that was consumed (by "consumeClose()")
972 return T.getCloseLocation();
975 if (Result.isInvalid()) {
976 DS.SetTypeSpecError();
977 return T.getCloseLocation();
980 EndLoc = T.getCloseLocation();
982 assert(!Result.isInvalid());
984 const char *PrevSpec = nullptr;
986 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
987 // Check for duplicate type specifiers (e.g. "int decltype(a)").
989 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
990 DiagID, Result.get(), Policy)
991 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
993 Diag(StartLoc, DiagID) << PrevSpec;
994 DS.SetTypeSpecError();
999 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1000 SourceLocation StartLoc,
1001 SourceLocation EndLoc) {
1002 // make sure we have a token we can turn into an annotation token
1003 if (PP.isBacktrackEnabled())
1004 PP.RevertCachedTokens(1);
1008 Tok.setKind(tok::annot_decltype);
1009 setExprAnnotation(Tok,
1010 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1011 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1013 Tok.setAnnotationEndLoc(EndLoc);
1014 Tok.setLocation(StartLoc);
1015 PP.AnnotateCachedTokens(Tok);
1018 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1019 assert(Tok.is(tok::kw___underlying_type) &&
1020 "Not an underlying type specifier");
1022 SourceLocation StartLoc = ConsumeToken();
1023 BalancedDelimiterTracker T(*this, tok::l_paren);
1024 if (T.expectAndConsume(diag::err_expected_lparen_after,
1025 "__underlying_type", tok::r_paren)) {
1029 TypeResult Result = ParseTypeName();
1030 if (Result.isInvalid()) {
1031 SkipUntil(tok::r_paren, StopAtSemi);
1037 if (T.getCloseLocation().isInvalid())
1040 const char *PrevSpec = nullptr;
1042 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
1043 DiagID, Result.get(),
1044 Actions.getASTContext().getPrintingPolicy()))
1045 Diag(StartLoc, DiagID) << PrevSpec;
1046 DS.setTypeofParensRange(T.getRange());
1049 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1050 /// class name or decltype-specifier. Note that we only check that the result
1051 /// names a type; semantic analysis will need to verify that the type names a
1052 /// class. The result is either a type or null, depending on whether a type
1055 /// base-type-specifier: [C++11 class.derived]
1056 /// class-or-decltype
1057 /// class-or-decltype: [C++11 class.derived]
1058 /// nested-name-specifier[opt] class-name
1059 /// decltype-specifier
1060 /// class-name: [C++ class.name]
1062 /// simple-template-id
1064 /// In C++98, instead of base-type-specifier, we have:
1066 /// ::[opt] nested-name-specifier[opt] class-name
1067 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1068 SourceLocation &EndLocation) {
1069 // Ignore attempts to use typename
1070 if (Tok.is(tok::kw_typename)) {
1071 Diag(Tok, diag::err_expected_class_name_not_template)
1072 << FixItHint::CreateRemoval(Tok.getLocation());
1076 // Parse optional nested-name-specifier
1078 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
1080 BaseLoc = Tok.getLocation();
1082 // Parse decltype-specifier
1083 // tok == kw_decltype is just error recovery, it can only happen when SS
1085 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
1086 if (SS.isNotEmpty())
1087 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1088 << FixItHint::CreateRemoval(SS.getRange());
1089 // Fake up a Declarator to use with ActOnTypeName.
1090 DeclSpec DS(AttrFactory);
1092 EndLocation = ParseDecltypeSpecifier(DS);
1094 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1095 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1098 // Check whether we have a template-id that names a type.
1099 if (Tok.is(tok::annot_template_id)) {
1100 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1101 if (TemplateId->Kind == TNK_Type_template ||
1102 TemplateId->Kind == TNK_Dependent_template_name) {
1103 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1105 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1106 ParsedType Type = getTypeAnnotation(Tok);
1107 EndLocation = Tok.getAnnotationEndLoc();
1108 ConsumeAnnotationToken();
1115 // Fall through to produce an error below.
1118 if (Tok.isNot(tok::identifier)) {
1119 Diag(Tok, diag::err_expected_class_name);
1123 IdentifierInfo *Id = Tok.getIdentifierInfo();
1124 SourceLocation IdLoc = ConsumeToken();
1126 if (Tok.is(tok::less)) {
1127 // It looks the user intended to write a template-id here, but the
1128 // template-name was wrong. Try to fix that.
1129 TemplateNameKind TNK = TNK_Type_template;
1130 TemplateTy Template;
1131 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
1132 &SS, Template, TNK)) {
1133 Diag(IdLoc, diag::err_unknown_template_name)
1138 TemplateArgList TemplateArgs;
1139 SourceLocation LAngleLoc, RAngleLoc;
1140 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1145 // Form the template name
1146 UnqualifiedId TemplateName;
1147 TemplateName.setIdentifier(Id, IdLoc);
1149 // Parse the full template-id, then turn it into a type.
1150 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1153 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1154 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1156 // If we didn't end up with a typename token, there's nothing more we
1158 if (Tok.isNot(tok::annot_typename))
1161 // Retrieve the type from the annotation token, consume that token, and
1163 EndLocation = Tok.getAnnotationEndLoc();
1164 ParsedType Type = getTypeAnnotation(Tok);
1165 ConsumeAnnotationToken();
1169 // We have an identifier; check whether it is actually a type.
1170 IdentifierInfo *CorrectedII = nullptr;
1171 ParsedType Type = Actions.getTypeName(
1172 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
1173 /*IsCtorOrDtorName=*/false,
1174 /*NonTrivialTypeSourceInfo=*/true,
1175 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
1177 Diag(IdLoc, diag::err_expected_class_name);
1181 // Consume the identifier.
1182 EndLocation = IdLoc;
1184 // Fake up a Declarator to use with ActOnTypeName.
1185 DeclSpec DS(AttrFactory);
1186 DS.SetRangeStart(IdLoc);
1187 DS.SetRangeEnd(EndLocation);
1188 DS.getTypeSpecScope() = SS;
1190 const char *PrevSpec = nullptr;
1192 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1193 Actions.getASTContext().getPrintingPolicy());
1195 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1196 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1199 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1200 while (Tok.isOneOf(tok::kw___single_inheritance,
1201 tok::kw___multiple_inheritance,
1202 tok::kw___virtual_inheritance)) {
1203 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1204 SourceLocation AttrNameLoc = ConsumeToken();
1205 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1206 AttributeList::AS_Keyword);
1210 /// Determine whether the following tokens are valid after a type-specifier
1211 /// which could be a standalone declaration. This will conservatively return
1212 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1213 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1214 // This switch enumerates the valid "follow" set for type-specifiers.
1215 switch (Tok.getKind()) {
1217 case tok::semi: // struct foo {...} ;
1218 case tok::star: // struct foo {...} * P;
1219 case tok::amp: // struct foo {...} & R = ...
1220 case tok::ampamp: // struct foo {...} && R = ...
1221 case tok::identifier: // struct foo {...} V ;
1222 case tok::r_paren: //(struct foo {...} ) {4}
1223 case tok::annot_cxxscope: // struct foo {...} a:: b;
1224 case tok::annot_typename: // struct foo {...} a ::b;
1225 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1226 case tok::l_paren: // struct foo {...} ( x);
1227 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1228 case tok::kw_operator: // struct foo operator ++() {...}
1229 case tok::kw___declspec: // struct foo {...} __declspec(...)
1230 case tok::l_square: // void f(struct f [ 3])
1231 case tok::ellipsis: // void f(struct f ... [Ns])
1232 // FIXME: we should emit semantic diagnostic when declaration
1233 // attribute is in type attribute position.
1234 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1235 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1236 // struct foo {...} _Pragma(section(...));
1237 case tok::annot_pragma_ms_pragma:
1238 // struct foo {...} _Pragma(vtordisp(pop));
1239 case tok::annot_pragma_ms_vtordisp:
1240 // struct foo {...} _Pragma(pointers_to_members(...));
1241 case tok::annot_pragma_ms_pointers_to_members:
1244 return CouldBeBitfield; // enum E { ... } : 2;
1245 // Microsoft compatibility
1246 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1247 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1248 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1249 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1250 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1251 // We will diagnose these calling-convention specifiers on non-function
1252 // declarations later, so claim they are valid after a type specifier.
1253 return getLangOpts().MicrosoftExt;
1255 case tok::kw_const: // struct foo {...} const x;
1256 case tok::kw_volatile: // struct foo {...} volatile x;
1257 case tok::kw_restrict: // struct foo {...} restrict x;
1258 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1259 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1260 // Function specifiers
1261 // Note, no 'explicit'. An explicit function must be either a conversion
1262 // operator or a constructor. Either way, it can't have a return type.
1263 case tok::kw_inline: // struct foo inline f();
1264 case tok::kw_virtual: // struct foo virtual f();
1265 case tok::kw_friend: // struct foo friend f();
1266 // Storage-class specifiers
1267 case tok::kw_static: // struct foo {...} static x;
1268 case tok::kw_extern: // struct foo {...} extern x;
1269 case tok::kw_typedef: // struct foo {...} typedef x;
1270 case tok::kw_register: // struct foo {...} register x;
1271 case tok::kw_auto: // struct foo {...} auto x;
1272 case tok::kw_mutable: // struct foo {...} mutable x;
1273 case tok::kw_thread_local: // struct foo {...} thread_local x;
1274 case tok::kw_constexpr: // struct foo {...} constexpr x;
1275 // As shown above, type qualifiers and storage class specifiers absolutely
1276 // can occur after class specifiers according to the grammar. However,
1277 // almost no one actually writes code like this. If we see one of these,
1278 // it is much more likely that someone missed a semi colon and the
1279 // type/storage class specifier we're seeing is part of the *next*
1280 // intended declaration, as in:
1282 // struct foo { ... }
1285 // We'd really like to emit a missing semicolon error instead of emitting
1286 // an error on the 'int' saying that you can't have two type specifiers in
1287 // the same declaration of X. Because of this, we look ahead past this
1288 // token to see if it's a type specifier. If so, we know the code is
1289 // otherwise invalid, so we can produce the expected semi error.
1290 if (!isKnownToBeTypeSpecifier(NextToken()))
1293 case tok::r_brace: // struct bar { struct foo {...} }
1294 // Missing ';' at end of struct is accepted as an extension in C mode.
1295 if (!getLangOpts().CPlusPlus)
1299 // template<class T = class X>
1300 return getLangOpts().CPlusPlus;
1305 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1306 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1307 /// until we reach the start of a definition or see a token that
1308 /// cannot start a definition.
1310 /// class-specifier: [C++ class]
1311 /// class-head '{' member-specification[opt] '}'
1312 /// class-head '{' member-specification[opt] '}' attributes[opt]
1314 /// class-key identifier[opt] base-clause[opt]
1315 /// class-key nested-name-specifier identifier base-clause[opt]
1316 /// class-key nested-name-specifier[opt] simple-template-id
1317 /// base-clause[opt]
1318 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1319 /// [GNU] class-key attributes[opt] nested-name-specifier
1320 /// identifier base-clause[opt]
1321 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1322 /// simple-template-id base-clause[opt]
1328 /// elaborated-type-specifier: [C++ dcl.type.elab]
1329 /// class-key ::[opt] nested-name-specifier[opt] identifier
1330 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1331 /// simple-template-id
1333 /// Note that the C++ class-specifier and elaborated-type-specifier,
1334 /// together, subsume the C99 struct-or-union-specifier:
1336 /// struct-or-union-specifier: [C99 6.7.2.1]
1337 /// struct-or-union identifier[opt] '{' struct-contents '}'
1338 /// struct-or-union identifier
1339 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1340 /// '}' attributes[opt]
1341 /// [GNU] struct-or-union attributes[opt] identifier
1342 /// struct-or-union:
1345 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1346 SourceLocation StartLoc, DeclSpec &DS,
1347 const ParsedTemplateInfo &TemplateInfo,
1349 bool EnteringContext, DeclSpecContext DSC,
1350 ParsedAttributesWithRange &Attributes) {
1351 DeclSpec::TST TagType;
1352 if (TagTokKind == tok::kw_struct)
1353 TagType = DeclSpec::TST_struct;
1354 else if (TagTokKind == tok::kw___interface)
1355 TagType = DeclSpec::TST_interface;
1356 else if (TagTokKind == tok::kw_class)
1357 TagType = DeclSpec::TST_class;
1359 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1360 TagType = DeclSpec::TST_union;
1363 if (Tok.is(tok::code_completion)) {
1364 // Code completion for a struct, class, or union name.
1365 Actions.CodeCompleteTag(getCurScope(), TagType);
1366 return cutOffParsing();
1369 // C++03 [temp.explicit] 14.7.2/8:
1370 // The usual access checking rules do not apply to names used to specify
1371 // explicit instantiations.
1373 // As an extension we do not perform access checking on the names used to
1374 // specify explicit specializations either. This is important to allow
1375 // specializing traits classes for private types.
1377 // Note that we don't suppress if this turns out to be an elaborated
1379 bool shouldDelayDiagsInTag =
1380 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1381 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1382 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1384 ParsedAttributesWithRange attrs(AttrFactory);
1385 // If attributes exist after tag, parse them.
1386 MaybeParseGNUAttributes(attrs);
1387 MaybeParseMicrosoftDeclSpecs(attrs);
1389 // Parse inheritance specifiers.
1390 if (Tok.isOneOf(tok::kw___single_inheritance,
1391 tok::kw___multiple_inheritance,
1392 tok::kw___virtual_inheritance))
1393 ParseMicrosoftInheritanceClassAttributes(attrs);
1395 // If C++0x attributes exist here, parse them.
1396 // FIXME: Are we consistent with the ordering of parsing of different
1397 // styles of attributes?
1398 MaybeParseCXX11Attributes(attrs);
1400 // Source location used by FIXIT to insert misplaced
1402 SourceLocation AttrFixitLoc = Tok.getLocation();
1404 if (TagType == DeclSpec::TST_struct &&
1405 Tok.isNot(tok::identifier) &&
1406 !Tok.isAnnotation() &&
1407 Tok.getIdentifierInfo() &&
1408 Tok.isOneOf(tok::kw___is_abstract,
1409 tok::kw___is_aggregate,
1410 tok::kw___is_arithmetic,
1412 tok::kw___is_assignable,
1413 tok::kw___is_base_of,
1415 tok::kw___is_complete_type,
1416 tok::kw___is_compound,
1418 tok::kw___is_constructible,
1419 tok::kw___is_convertible,
1420 tok::kw___is_convertible_to,
1421 tok::kw___is_destructible,
1424 tok::kw___is_floating_point,
1426 tok::kw___is_function,
1427 tok::kw___is_fundamental,
1428 tok::kw___is_integral,
1429 tok::kw___is_interface_class,
1430 tok::kw___is_literal,
1431 tok::kw___is_lvalue_expr,
1432 tok::kw___is_lvalue_reference,
1433 tok::kw___is_member_function_pointer,
1434 tok::kw___is_member_object_pointer,
1435 tok::kw___is_member_pointer,
1436 tok::kw___is_nothrow_assignable,
1437 tok::kw___is_nothrow_constructible,
1438 tok::kw___is_nothrow_destructible,
1439 tok::kw___is_object,
1441 tok::kw___is_pointer,
1442 tok::kw___is_polymorphic,
1443 tok::kw___is_reference,
1444 tok::kw___is_rvalue_expr,
1445 tok::kw___is_rvalue_reference,
1447 tok::kw___is_scalar,
1448 tok::kw___is_sealed,
1449 tok::kw___is_signed,
1450 tok::kw___is_standard_layout,
1451 tok::kw___is_trivial,
1452 tok::kw___is_trivially_assignable,
1453 tok::kw___is_trivially_constructible,
1454 tok::kw___is_trivially_copyable,
1456 tok::kw___is_unsigned,
1458 tok::kw___is_volatile))
1459 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1460 // name of struct templates, but some are keywords in GCC >= 4.3
1461 // and Clang. Therefore, when we see the token sequence "struct
1462 // X", make X into a normal identifier rather than a keyword, to
1463 // allow libstdc++ 4.2 and libc++ to work properly.
1464 TryKeywordIdentFallback(true);
1466 struct PreserveAtomicIdentifierInfoRAII {
1467 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1468 : AtomicII(nullptr) {
1471 assert(Tok.is(tok::kw__Atomic));
1472 AtomicII = Tok.getIdentifierInfo();
1473 AtomicII->revertTokenIDToIdentifier();
1474 Tok.setKind(tok::identifier);
1476 ~PreserveAtomicIdentifierInfoRAII() {
1479 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1481 IdentifierInfo *AtomicII;
1484 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1485 // implementation for VS2013 uses _Atomic as an identifier for one of the
1486 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1487 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1488 // use '_Atomic' in its own header files.
1489 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1490 Tok.is(tok::kw__Atomic) &&
1491 TagType == DeclSpec::TST_struct;
1492 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1493 Tok, ShouldChangeAtomicToIdentifier);
1495 // Parse the (optional) nested-name-specifier.
1496 CXXScopeSpec &SS = DS.getTypeSpecScope();
1497 if (getLangOpts().CPlusPlus) {
1498 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1499 // is a base-specifier-list.
1500 ColonProtectionRAIIObject X(*this);
1503 bool HasValidSpec = true;
1504 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
1505 DS.SetTypeSpecError();
1506 HasValidSpec = false;
1509 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1510 Diag(Tok, diag::err_expected) << tok::identifier;
1511 HasValidSpec = false;
1517 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1519 // Parse the (optional) class name or simple-template-id.
1520 IdentifierInfo *Name = nullptr;
1521 SourceLocation NameLoc;
1522 TemplateIdAnnotation *TemplateId = nullptr;
1523 if (Tok.is(tok::identifier)) {
1524 Name = Tok.getIdentifierInfo();
1525 NameLoc = ConsumeToken();
1527 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1528 // The name was supposed to refer to a template, but didn't.
1529 // Eat the template argument list and try to continue parsing this as
1530 // a class (or template thereof).
1531 TemplateArgList TemplateArgs;
1532 SourceLocation LAngleLoc, RAngleLoc;
1533 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1535 // We couldn't parse the template argument list at all, so don't
1536 // try to give any location information for the list.
1537 LAngleLoc = RAngleLoc = SourceLocation();
1540 Diag(NameLoc, diag::err_explicit_spec_non_template)
1541 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1542 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1544 // Strip off the last template parameter list if it was empty, since
1545 // we've removed its template argument list.
1546 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1547 if (TemplateParams->size() > 1) {
1548 TemplateParams->pop_back();
1550 TemplateParams = nullptr;
1551 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1552 = ParsedTemplateInfo::NonTemplate;
1554 } else if (TemplateInfo.Kind
1555 == ParsedTemplateInfo::ExplicitInstantiation) {
1556 // Pretend this is just a forward declaration.
1557 TemplateParams = nullptr;
1558 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1559 = ParsedTemplateInfo::NonTemplate;
1560 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1562 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1566 } else if (Tok.is(tok::annot_template_id)) {
1567 TemplateId = takeTemplateIdAnnotation(Tok);
1568 NameLoc = ConsumeAnnotationToken();
1570 if (TemplateId->Kind != TNK_Type_template &&
1571 TemplateId->Kind != TNK_Dependent_template_name) {
1572 // The template-name in the simple-template-id refers to
1573 // something other than a class template. Give an appropriate
1574 // error message and skip to the ';'.
1575 SourceRange Range(NameLoc);
1576 if (SS.isNotEmpty())
1577 Range.setBegin(SS.getBeginLoc());
1579 // FIXME: Name may be null here.
1580 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1581 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1583 DS.SetTypeSpecError();
1584 SkipUntil(tok::semi, StopBeforeMatch);
1589 // There are four options here.
1590 // - If we are in a trailing return type, this is always just a reference,
1591 // and we must not try to parse a definition. For instance,
1592 // [] () -> struct S { };
1593 // does not define a type.
1594 // - If we have 'struct foo {...', 'struct foo :...',
1595 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1596 // - If we have 'struct foo;', then this is either a forward declaration
1597 // or a friend declaration, which have to be treated differently.
1598 // - Otherwise we have something like 'struct foo xyz', a reference.
1600 // We also detect these erroneous cases to provide better diagnostic for
1601 // C++11 attributes parsing.
1602 // - attributes follow class name:
1603 // struct foo [[]] {};
1604 // - attributes appear before or after 'final':
1605 // struct foo [[]] final [[]] {};
1607 // However, in type-specifier-seq's, things look like declarations but are
1608 // just references, e.g.
1611 // &T::operator struct s;
1612 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
1614 // If there are attributes after class name, parse them.
1615 MaybeParseCXX11Attributes(Attributes);
1617 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1618 Sema::TagUseKind TUK;
1619 if (DSC == DSC_trailing)
1620 TUK = Sema::TUK_Reference;
1621 else if (Tok.is(tok::l_brace) ||
1622 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1623 (isCXX11FinalKeyword() &&
1624 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1625 if (DS.isFriendSpecified()) {
1626 // C++ [class.friend]p2:
1627 // A class shall not be defined in a friend declaration.
1628 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1629 << SourceRange(DS.getFriendSpecLoc());
1631 // Skip everything up to the semicolon, so that this looks like a proper
1632 // friend class (or template thereof) declaration.
1633 SkipUntil(tok::semi, StopBeforeMatch);
1634 TUK = Sema::TUK_Friend;
1636 // Okay, this is a class definition.
1637 TUK = Sema::TUK_Definition;
1639 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1640 NextToken().is(tok::kw_alignas))) {
1641 // We can't tell if this is a definition or reference
1642 // until we skipped the 'final' and C++11 attribute specifiers.
1643 TentativeParsingAction PA(*this);
1645 // Skip the 'final' keyword.
1648 // Skip C++11 attribute specifiers.
1650 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1652 if (!SkipUntil(tok::r_square, StopAtSemi))
1654 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1657 if (!SkipUntil(tok::r_paren, StopAtSemi))
1664 if (Tok.isOneOf(tok::l_brace, tok::colon))
1665 TUK = Sema::TUK_Definition;
1667 TUK = Sema::TUK_Reference;
1670 } else if (!isTypeSpecifier(DSC) &&
1671 (Tok.is(tok::semi) ||
1672 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1673 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1674 if (Tok.isNot(tok::semi)) {
1675 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1676 // A semicolon was missing after this declaration. Diagnose and recover.
1677 ExpectAndConsume(tok::semi, diag::err_expected_after,
1678 DeclSpec::getSpecifierName(TagType, PPol));
1680 Tok.setKind(tok::semi);
1683 TUK = Sema::TUK_Reference;
1685 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1686 // to caller to handle.
1687 if (TUK != Sema::TUK_Reference) {
1688 // If this is not a reference, then the only possible
1689 // valid place for C++11 attributes to appear here
1690 // is between class-key and class-name. If there are
1691 // any attributes after class-name, we try a fixit to move
1692 // them to the right place.
1693 SourceRange AttrRange = Attributes.Range;
1694 if (AttrRange.isValid()) {
1695 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1697 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1698 CharSourceRange(AttrRange, true))
1699 << FixItHint::CreateRemoval(AttrRange);
1701 // Recover by adding misplaced attributes to the attribute list
1702 // of the class so they can be applied on the class later.
1703 attrs.takeAllFrom(Attributes);
1707 // If this is an elaborated type specifier, and we delayed
1708 // diagnostics before, just merge them into the current pool.
1709 if (shouldDelayDiagsInTag) {
1710 diagsFromTag.done();
1711 if (TUK == Sema::TUK_Reference)
1712 diagsFromTag.redelay();
1715 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1716 TUK != Sema::TUK_Definition)) {
1717 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1718 // We have a declaration or reference to an anonymous class.
1719 Diag(StartLoc, diag::err_anon_type_definition)
1720 << DeclSpec::getSpecifierName(TagType, Policy);
1723 // If we are parsing a definition and stop at a base-clause, continue on
1724 // until the semicolon. Continuing from the comma will just trick us into
1725 // thinking we are seeing a variable declaration.
1726 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1727 SkipUntil(tok::semi, StopBeforeMatch);
1729 SkipUntil(tok::comma, StopAtSemi);
1733 // Create the tag portion of the class or class template.
1734 DeclResult TagOrTempResult = true; // invalid
1735 TypeResult TypeResult = true; // invalid
1738 Sema::SkipBodyInfo SkipBody;
1740 // Explicit specialization, class template partial specialization,
1741 // or explicit instantiation.
1742 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1743 TemplateId->NumArgs);
1744 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1745 TUK == Sema::TUK_Declaration) {
1746 // This is an explicit instantiation of a class template.
1747 ProhibitAttributes(attrs);
1750 = Actions.ActOnExplicitInstantiation(getCurScope(),
1751 TemplateInfo.ExternLoc,
1752 TemplateInfo.TemplateLoc,
1756 TemplateId->Template,
1757 TemplateId->TemplateNameLoc,
1758 TemplateId->LAngleLoc,
1760 TemplateId->RAngleLoc,
1763 // Friend template-ids are treated as references unless
1764 // they have template headers, in which case they're ill-formed
1765 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1766 // We diagnose this error in ActOnClassTemplateSpecialization.
1767 } else if (TUK == Sema::TUK_Reference ||
1768 (TUK == Sema::TUK_Friend &&
1769 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1770 ProhibitAttributes(attrs);
1771 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1773 TemplateId->TemplateKWLoc,
1774 TemplateId->Template,
1775 TemplateId->TemplateNameLoc,
1776 TemplateId->LAngleLoc,
1778 TemplateId->RAngleLoc);
1780 // This is an explicit specialization or a class template
1781 // partial specialization.
1782 TemplateParameterLists FakedParamLists;
1783 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1784 // This looks like an explicit instantiation, because we have
1787 // template class Foo<X>
1789 // but it actually has a definition. Most likely, this was
1790 // meant to be an explicit specialization, but the user forgot
1791 // the '<>' after 'template'.
1792 // It this is friend declaration however, since it cannot have a
1793 // template header, it is most likely that the user meant to
1794 // remove the 'template' keyword.
1795 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1796 "Expected a definition here");
1798 if (TUK == Sema::TUK_Friend) {
1799 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1800 TemplateParams = nullptr;
1802 SourceLocation LAngleLoc =
1803 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1804 Diag(TemplateId->TemplateNameLoc,
1805 diag::err_explicit_instantiation_with_definition)
1806 << SourceRange(TemplateInfo.TemplateLoc)
1807 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1809 // Create a fake template parameter list that contains only
1810 // "template<>", so that we treat this construct as a class
1811 // template specialization.
1812 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1813 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1814 LAngleLoc, nullptr));
1815 TemplateParams = &FakedParamLists;
1819 // Build the class template specialization.
1820 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1821 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1822 *TemplateId, attrs.getList(),
1823 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1825 TemplateParams ? TemplateParams->size() : 0),
1828 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1829 TUK == Sema::TUK_Declaration) {
1830 // Explicit instantiation of a member of a class template
1831 // specialization, e.g.,
1833 // template struct Outer<int>::Inner;
1835 ProhibitAttributes(attrs);
1838 = Actions.ActOnExplicitInstantiation(getCurScope(),
1839 TemplateInfo.ExternLoc,
1840 TemplateInfo.TemplateLoc,
1841 TagType, StartLoc, SS, Name,
1842 NameLoc, attrs.getList());
1843 } else if (TUK == Sema::TUK_Friend &&
1844 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1845 ProhibitAttributes(attrs);
1848 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1849 TagType, StartLoc, SS,
1850 Name, NameLoc, attrs.getList(),
1851 MultiTemplateParamsArg(
1852 TemplateParams? &(*TemplateParams)[0]
1854 TemplateParams? TemplateParams->size() : 0));
1856 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1857 ProhibitAttributes(attrs);
1859 if (TUK == Sema::TUK_Definition &&
1860 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1861 // If the declarator-id is not a template-id, issue a diagnostic and
1862 // recover by ignoring the 'template' keyword.
1863 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1864 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1865 TemplateParams = nullptr;
1868 bool IsDependent = false;
1870 // Don't pass down template parameter lists if this is just a tag
1871 // reference. For example, we don't need the template parameters here:
1872 // template <class T> class A *makeA(T t);
1873 MultiTemplateParamsArg TParams;
1874 if (TUK != Sema::TUK_Reference && TemplateParams)
1876 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1878 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
1880 // Declaration or definition of a class type
1881 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1882 SS, Name, NameLoc, attrs.getList(), AS,
1883 DS.getModulePrivateSpecLoc(),
1884 TParams, Owned, IsDependent,
1885 SourceLocation(), false,
1886 clang::TypeResult(),
1887 DSC == DSC_type_specifier,
1890 // If ActOnTag said the type was dependent, try again with the
1891 // less common call.
1893 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1894 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1895 SS, Name, StartLoc, NameLoc);
1899 // If there is a body, parse it and inform the actions module.
1900 if (TUK == Sema::TUK_Definition) {
1901 assert(Tok.is(tok::l_brace) ||
1902 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1903 isCXX11FinalKeyword());
1904 if (SkipBody.ShouldSkip)
1905 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1906 TagOrTempResult.get());
1907 else if (getLangOpts().CPlusPlus)
1908 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1909 TagOrTempResult.get());
1911 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1914 if (!TagOrTempResult.isInvalid())
1915 // Delayed proccessing of attributes.
1916 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1918 const char *PrevSpec = nullptr;
1921 if (!TypeResult.isInvalid()) {
1922 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1923 NameLoc.isValid() ? NameLoc : StartLoc,
1924 PrevSpec, DiagID, TypeResult.get(), Policy);
1925 } else if (!TagOrTempResult.isInvalid()) {
1926 Result = DS.SetTypeSpecType(TagType, StartLoc,
1927 NameLoc.isValid() ? NameLoc : StartLoc,
1928 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1931 DS.SetTypeSpecError();
1936 Diag(StartLoc, DiagID) << PrevSpec;
1938 // At this point, we've successfully parsed a class-specifier in 'definition'
1939 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1940 // going to look at what comes after it to improve error recovery. If an
1941 // impossible token occurs next, we assume that the programmer forgot a ; at
1942 // the end of the declaration and recover that way.
1944 // Also enforce C++ [temp]p3:
1945 // In a template-declaration which defines a class, no declarator
1948 // After a type-specifier, we don't expect a semicolon. This only happens in
1949 // C, since definitions are not permitted in this context in C++.
1950 if (TUK == Sema::TUK_Definition &&
1951 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1952 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1953 if (Tok.isNot(tok::semi)) {
1954 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1955 ExpectAndConsume(tok::semi, diag::err_expected_after,
1956 DeclSpec::getSpecifierName(TagType, PPol));
1957 // Push this token back into the preprocessor and change our current token
1958 // to ';' so that the rest of the code recovers as though there were an
1959 // ';' after the definition.
1961 Tok.setKind(tok::semi);
1966 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1968 /// base-clause : [C++ class.derived]
1969 /// ':' base-specifier-list
1970 /// base-specifier-list:
1971 /// base-specifier '...'[opt]
1972 /// base-specifier-list ',' base-specifier '...'[opt]
1973 void Parser::ParseBaseClause(Decl *ClassDecl) {
1974 assert(Tok.is(tok::colon) && "Not a base clause");
1977 // Build up an array of parsed base specifiers.
1978 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1981 // Parse a base-specifier.
1982 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1983 if (Result.isInvalid()) {
1984 // Skip the rest of this base specifier, up until the comma or
1986 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
1988 // Add this to our array of base specifiers.
1989 BaseInfo.push_back(Result.get());
1992 // If the next token is a comma, consume it and keep reading
1994 if (!TryConsumeToken(tok::comma))
1998 // Attach the base specifiers
1999 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2002 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2003 /// one entry in the base class list of a class specifier, for example:
2004 /// class foo : public bar, virtual private baz {
2005 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2007 /// base-specifier: [C++ class.derived]
2008 /// attribute-specifier-seq[opt] base-type-specifier
2009 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2010 /// base-type-specifier
2011 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2012 /// base-type-specifier
2013 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2014 bool IsVirtual = false;
2015 SourceLocation StartLoc = Tok.getLocation();
2017 ParsedAttributesWithRange Attributes(AttrFactory);
2018 MaybeParseCXX11Attributes(Attributes);
2020 // Parse the 'virtual' keyword.
2021 if (TryConsumeToken(tok::kw_virtual))
2024 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2026 // Parse an (optional) access specifier.
2027 AccessSpecifier Access = getAccessSpecifierIfPresent();
2028 if (Access != AS_none)
2031 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2033 // Parse the 'virtual' keyword (again!), in case it came after the
2034 // access specifier.
2035 if (Tok.is(tok::kw_virtual)) {
2036 SourceLocation VirtualLoc = ConsumeToken();
2038 // Complain about duplicate 'virtual'
2039 Diag(VirtualLoc, diag::err_dup_virtual)
2040 << FixItHint::CreateRemoval(VirtualLoc);
2046 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2048 // Parse the class-name.
2050 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2051 // implementation for VS2013 uses _Atomic as an identifier for one of the
2052 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2053 // parsing the class-name for a base specifier.
2054 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2055 NextToken().is(tok::less))
2056 Tok.setKind(tok::identifier);
2058 SourceLocation EndLocation;
2059 SourceLocation BaseLoc;
2060 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2061 if (BaseType.isInvalid())
2064 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2065 // actually part of the base-specifier-list grammar productions, but we
2066 // parse it here for convenience.
2067 SourceLocation EllipsisLoc;
2068 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2070 // Find the complete source range for the base-specifier.
2071 SourceRange Range(StartLoc, EndLocation);
2073 // Notify semantic analysis that we have parsed a complete
2075 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2076 Access, BaseType.get(), BaseLoc,
2080 /// getAccessSpecifierIfPresent - Determine whether the next token is
2081 /// a C++ access-specifier.
2083 /// access-specifier: [C++ class.derived]
2087 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2088 switch (Tok.getKind()) {
2089 default: return AS_none;
2090 case tok::kw_private: return AS_private;
2091 case tok::kw_protected: return AS_protected;
2092 case tok::kw_public: return AS_public;
2096 /// \brief If the given declarator has any parts for which parsing has to be
2097 /// delayed, e.g., default arguments or an exception-specification, create a
2098 /// late-parsed method declaration record to handle the parsing at the end of
2099 /// the class definition.
2100 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2102 DeclaratorChunk::FunctionTypeInfo &FTI
2103 = DeclaratorInfo.getFunctionTypeInfo();
2104 // If there was a late-parsed exception-specification, we'll need a
2106 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2108 if (!NeedLateParse) {
2109 // Look ahead to see if there are any default args
2110 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2111 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2112 if (Param->hasUnparsedDefaultArg()) {
2113 NeedLateParse = true;
2119 if (NeedLateParse) {
2120 // Push this method onto the stack of late-parsed method
2122 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2123 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2124 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2126 // Stash the exception-specification tokens in the late-pased method.
2127 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2128 FTI.ExceptionSpecTokens = nullptr;
2130 // Push tokens for each parameter. Those that do not have
2131 // defaults will be NULL.
2132 LateMethod->DefaultArgs.reserve(FTI.NumParams);
2133 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2134 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2135 FTI.Params[ParamIdx].Param,
2136 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2140 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2147 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2148 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2149 return VirtSpecifiers::VS_None;
2151 IdentifierInfo *II = Tok.getIdentifierInfo();
2153 // Initialize the contextual keywords.
2155 Ident_final = &PP.getIdentifierTable().get("final");
2156 if (getLangOpts().GNUKeywords)
2157 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2158 if (getLangOpts().MicrosoftExt)
2159 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2160 Ident_override = &PP.getIdentifierTable().get("override");
2163 if (II == Ident_override)
2164 return VirtSpecifiers::VS_Override;
2166 if (II == Ident_sealed)
2167 return VirtSpecifiers::VS_Sealed;
2169 if (II == Ident_final)
2170 return VirtSpecifiers::VS_Final;
2172 if (II == Ident_GNU_final)
2173 return VirtSpecifiers::VS_GNU_Final;
2175 return VirtSpecifiers::VS_None;
2178 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2180 /// virt-specifier-seq:
2182 /// virt-specifier-seq virt-specifier
2183 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2185 SourceLocation FriendLoc) {
2187 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2188 if (Specifier == VirtSpecifiers::VS_None)
2191 if (FriendLoc.isValid()) {
2192 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2193 << VirtSpecifiers::getSpecifierName(Specifier)
2194 << FixItHint::CreateRemoval(Tok.getLocation())
2195 << SourceRange(FriendLoc, FriendLoc);
2200 // C++ [class.mem]p8:
2201 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2202 const char *PrevSpec = nullptr;
2203 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2204 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2206 << FixItHint::CreateRemoval(Tok.getLocation());
2208 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2209 Specifier == VirtSpecifiers::VS_Sealed)) {
2210 Diag(Tok.getLocation(), diag::err_override_control_interface)
2211 << VirtSpecifiers::getSpecifierName(Specifier);
2212 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2213 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2214 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2215 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2217 Diag(Tok.getLocation(),
2218 getLangOpts().CPlusPlus11
2219 ? diag::warn_cxx98_compat_override_control_keyword
2220 : diag::ext_override_control_keyword)
2221 << VirtSpecifiers::getSpecifierName(Specifier);
2227 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2228 /// 'final' or Microsoft 'sealed' contextual keyword.
2229 bool Parser::isCXX11FinalKeyword() const {
2230 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2231 return Specifier == VirtSpecifiers::VS_Final ||
2232 Specifier == VirtSpecifiers::VS_GNU_Final ||
2233 Specifier == VirtSpecifiers::VS_Sealed;
2236 /// \brief Parse a C++ member-declarator up to, but not including, the optional
2237 /// brace-or-equal-initializer or pure-specifier.
2238 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2239 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2240 LateParsedAttrList &LateParsedAttrs) {
2241 // member-declarator:
2242 // declarator pure-specifier[opt]
2243 // declarator brace-or-equal-initializer[opt]
2244 // identifier[opt] ':' constant-expression
2245 if (Tok.isNot(tok::colon))
2246 ParseDeclarator(DeclaratorInfo);
2248 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2250 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2251 assert(DeclaratorInfo.isPastIdentifier() &&
2252 "don't know where identifier would go yet?");
2253 BitfieldSize = ParseConstantExpression();
2254 if (BitfieldSize.isInvalid())
2255 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2257 ParseOptionalCXX11VirtSpecifierSeq(
2258 VS, getCurrentClass().IsInterface,
2259 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2261 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2264 // If a simple-asm-expr is present, parse it.
2265 if (Tok.is(tok::kw_asm)) {
2267 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2268 if (AsmLabel.isInvalid())
2269 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2271 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2272 DeclaratorInfo.SetRangeEnd(Loc);
2275 // If attributes exist after the declarator, but before an '{', parse them.
2276 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2278 // For compatibility with code written to older Clang, also accept a
2279 // virt-specifier *after* the GNU attributes.
2280 if (BitfieldSize.isUnset() && VS.isUnset()) {
2281 ParseOptionalCXX11VirtSpecifierSeq(
2282 VS, getCurrentClass().IsInterface,
2283 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2284 if (!VS.isUnset()) {
2285 // If we saw any GNU-style attributes that are known to GCC followed by a
2286 // virt-specifier, issue a GCC-compat warning.
2287 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2289 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2290 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2291 Attr = Attr->getNext();
2293 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2297 // If this has neither a name nor a bit width, something has gone seriously
2298 // wrong. Skip until the semi-colon or }.
2299 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2300 // If so, skip until the semi-colon or a }.
2301 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2307 /// \brief Look for declaration specifiers possibly occurring after C++11
2308 /// virt-specifier-seq and diagnose them.
2309 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2311 VirtSpecifiers &VS) {
2312 DeclSpec DS(AttrFactory);
2314 // GNU-style and C++11 attributes are not allowed here, but they will be
2315 // handled by the caller. Diagnose everything else.
2316 ParseTypeQualifierListOpt(
2317 DS, AR_NoAttributesParsed, false,
2318 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2319 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2321 D.ExtendWithDeclSpec(DS);
2323 if (D.isFunctionDeclarator()) {
2324 auto &Function = D.getFunctionTypeInfo();
2325 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2326 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2327 const char *FixItName,
2328 SourceLocation SpecLoc,
2329 unsigned* QualifierLoc) {
2330 FixItHint Insertion;
2331 if (DS.getTypeQualifiers() & TypeQual) {
2332 if (!(Function.TypeQuals & TypeQual)) {
2333 std::string Name(FixItName);
2335 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2336 Function.TypeQuals |= TypeQual;
2337 *QualifierLoc = SpecLoc.getRawEncoding();
2339 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2341 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2342 << FixItHint::CreateRemoval(SpecLoc)
2346 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2347 &Function.ConstQualifierLoc);
2348 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2349 &Function.VolatileQualifierLoc);
2350 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2351 &Function.RestrictQualifierLoc);
2354 // Parse ref-qualifiers.
2355 bool RefQualifierIsLValueRef = true;
2356 SourceLocation RefQualifierLoc;
2357 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2358 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2359 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2360 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2361 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2363 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2364 << (RefQualifierIsLValueRef ? "&" : "&&")
2365 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2366 << FixItHint::CreateRemoval(RefQualifierLoc)
2368 D.SetRangeEnd(RefQualifierLoc);
2373 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2375 /// member-declaration:
2376 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2377 /// function-definition ';'[opt]
2378 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2379 /// using-declaration [TODO]
2380 /// [C++0x] static_assert-declaration
2381 /// template-declaration
2382 /// [GNU] '__extension__' member-declaration
2384 /// member-declarator-list:
2385 /// member-declarator
2386 /// member-declarator-list ',' member-declarator
2388 /// member-declarator:
2389 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2390 /// declarator constant-initializer[opt]
2391 /// [C++11] declarator brace-or-equal-initializer[opt]
2392 /// identifier[opt] ':' constant-expression
2394 /// virt-specifier-seq:
2396 /// virt-specifier-seq virt-specifier
2406 /// constant-initializer:
2407 /// '=' constant-expression
2409 Parser::DeclGroupPtrTy
2410 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2411 AttributeList *AccessAttrs,
2412 const ParsedTemplateInfo &TemplateInfo,
2413 ParsingDeclRAIIObject *TemplateDiags) {
2414 if (Tok.is(tok::at)) {
2415 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2416 Diag(Tok, diag::err_at_defs_cxx);
2418 Diag(Tok, diag::err_at_in_class);
2421 SkipUntil(tok::r_brace, StopAtSemi);
2425 // Turn on colon protection early, while parsing declspec, although there is
2426 // nothing to protect there. It prevents from false errors if error recovery
2427 // incorrectly determines where the declspec ends, as in the example:
2428 // struct A { enum class B { C }; };
2430 // struct D { A::B : C; };
2431 ColonProtectionRAIIObject X(*this);
2433 // Access declarations.
2434 bool MalformedTypeSpec = false;
2435 if (!TemplateInfo.Kind &&
2436 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2437 if (TryAnnotateCXXScopeToken())
2438 MalformedTypeSpec = true;
2441 if (Tok.isNot(tok::annot_cxxscope))
2442 isAccessDecl = false;
2443 else if (NextToken().is(tok::identifier))
2444 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2446 isAccessDecl = NextToken().is(tok::kw_operator);
2449 // Collect the scope specifier token we annotated earlier.
2451 ParseOptionalCXXScopeSpecifier(SS, nullptr,
2452 /*EnteringContext=*/false);
2454 if (SS.isInvalid()) {
2455 SkipUntil(tok::semi);
2459 // Try to parse an unqualified-id.
2460 SourceLocation TemplateKWLoc;
2462 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2463 TemplateKWLoc, Name)) {
2464 SkipUntil(tok::semi);
2468 // TODO: recover from mistakenly-qualified operator declarations.
2469 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2470 "access declaration")) {
2471 SkipUntil(tok::semi);
2475 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2476 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2477 /*TypenameLoc*/ SourceLocation(), SS, Name,
2478 /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
2482 // static_assert-declaration. A templated static_assert declaration is
2483 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2484 if (!TemplateInfo.Kind &&
2485 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2486 SourceLocation DeclEnd;
2487 return DeclGroupPtrTy::make(
2488 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2491 if (Tok.is(tok::kw_template)) {
2492 assert(!TemplateInfo.TemplateParams &&
2493 "Nested template improperly parsed?");
2494 ObjCDeclContextSwitch ObjCDC(*this);
2495 SourceLocation DeclEnd;
2496 return DeclGroupPtrTy::make(
2497 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2498 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
2501 // Handle: member-declaration ::= '__extension__' member-declaration
2502 if (Tok.is(tok::kw___extension__)) {
2503 // __extension__ silences extension warnings in the subexpression.
2504 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2506 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2507 TemplateInfo, TemplateDiags);
2510 ParsedAttributesWithRange attrs(AttrFactory);
2511 ParsedAttributesWithRange FnAttrs(AttrFactory);
2512 // Optional C++11 attribute-specifier
2513 MaybeParseCXX11Attributes(attrs);
2514 // We need to keep these attributes for future diagnostic
2515 // before they are taken over by declaration specifier.
2516 FnAttrs.addAll(attrs.getList());
2517 FnAttrs.Range = attrs.Range;
2519 MaybeParseMicrosoftAttributes(attrs);
2521 if (Tok.is(tok::kw_using)) {
2522 ProhibitAttributes(attrs);
2525 SourceLocation UsingLoc = ConsumeToken();
2527 if (Tok.is(tok::kw_namespace)) {
2528 Diag(UsingLoc, diag::err_using_namespace_in_class);
2529 SkipUntil(tok::semi, StopBeforeMatch);
2532 SourceLocation DeclEnd;
2533 // Otherwise, it must be a using-declaration or an alias-declaration.
2534 return ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2535 UsingLoc, DeclEnd, AS);
2538 // Hold late-parsed attributes so we can attach a Decl to them later.
2539 LateParsedAttrList CommonLateParsedAttrs;
2541 // decl-specifier-seq:
2542 // Parse the common declaration-specifiers piece.
2543 ParsingDeclSpec DS(*this, TemplateDiags);
2544 DS.takeAttributesFrom(attrs);
2545 if (MalformedTypeSpec)
2546 DS.SetTypeSpecError();
2548 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2549 &CommonLateParsedAttrs);
2551 // Turn off colon protection that was set for declspec.
2554 // If we had a free-standing type definition with a missing semicolon, we
2555 // may get this far before the problem becomes obvious.
2556 if (DS.hasTagDefinition() &&
2557 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2558 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2559 &CommonLateParsedAttrs))
2562 MultiTemplateParamsArg TemplateParams(
2563 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2565 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2567 if (TryConsumeToken(tok::semi)) {
2568 if (DS.isFriendSpecified())
2569 ProhibitAttributes(FnAttrs);
2571 RecordDecl *AnonRecord = nullptr;
2572 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2573 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2574 DS.complete(TheDecl);
2576 Decl* decls[] = {AnonRecord, TheDecl};
2577 return Actions.BuildDeclaratorGroup(decls);
2579 return Actions.ConvertDeclToDeclGroup(TheDecl);
2582 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2585 // Hold late-parsed attributes so we can attach a Decl to them later.
2586 LateParsedAttrList LateParsedAttrs;
2588 SourceLocation EqualLoc;
2589 SourceLocation PureSpecLoc;
2591 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2592 if (Tok.isNot(tok::equal))
2595 auto &Zero = NextToken();
2596 SmallString<8> Buffer;
2597 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2598 PP.getSpelling(Zero, Buffer) != "0")
2601 auto &After = GetLookAheadToken(2);
2602 if (!After.isOneOf(tok::semi, tok::comma) &&
2603 !(AllowDefinition &&
2604 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2607 EqualLoc = ConsumeToken();
2608 PureSpecLoc = ConsumeToken();
2612 SmallVector<Decl *, 8> DeclsInGroup;
2613 ExprResult BitfieldSize;
2614 bool ExpectSemi = true;
2616 // Parse the first declarator.
2617 if (ParseCXXMemberDeclaratorBeforeInitializer(
2618 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2619 TryConsumeToken(tok::semi);
2623 // Check for a member function definition.
2624 if (BitfieldSize.isUnset()) {
2625 // MSVC permits pure specifier on inline functions defined at class scope.
2626 // Hence check for =0 before checking for function definition.
2627 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2628 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2630 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2631 // function-definition:
2633 // In C++11, a non-function declarator followed by an open brace is a
2634 // braced-init-list for an in-class member initialization, not an
2635 // erroneous function definition.
2636 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2637 DefinitionKind = FDK_Definition;
2638 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2639 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2640 DefinitionKind = FDK_Definition;
2641 } else if (Tok.is(tok::equal)) {
2642 const Token &KW = NextToken();
2643 if (KW.is(tok::kw_default))
2644 DefinitionKind = FDK_Defaulted;
2645 else if (KW.is(tok::kw_delete))
2646 DefinitionKind = FDK_Deleted;
2649 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2651 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2652 // to a friend declaration, that declaration shall be a definition.
2653 if (DeclaratorInfo.isFunctionDeclarator() &&
2654 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2655 // Diagnose attributes that appear before decl specifier:
2656 // [[]] friend int foo();
2657 ProhibitAttributes(FnAttrs);
2660 if (DefinitionKind != FDK_Declaration) {
2661 if (!DeclaratorInfo.isFunctionDeclarator()) {
2662 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2664 SkipUntil(tok::r_brace);
2666 // Consume the optional ';'
2667 TryConsumeToken(tok::semi);
2672 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2673 Diag(DeclaratorInfo.getIdentifierLoc(),
2674 diag::err_function_declared_typedef);
2676 // Recover by treating the 'typedef' as spurious.
2677 DS.ClearStorageClassSpecs();
2681 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2685 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2686 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2688 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2689 LateParsedAttrs[i]->addDecl(FunDecl);
2692 LateParsedAttrs.clear();
2694 // Consume the ';' - it's optional unless we have a delete or default
2695 if (Tok.is(tok::semi))
2696 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2698 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2702 // member-declarator-list:
2703 // member-declarator
2704 // member-declarator-list ',' member-declarator
2707 InClassInitStyle HasInClassInit = ICIS_NoInit;
2708 bool HasStaticInitializer = false;
2709 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2710 if (BitfieldSize.get()) {
2711 Diag(Tok, diag::err_bitfield_member_init);
2712 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2713 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2714 // It's a pure-specifier.
2715 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2716 // Parse it as an expression so that Sema can diagnose it.
2717 HasStaticInitializer = true;
2718 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2719 DeclSpec::SCS_static &&
2720 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2721 DeclSpec::SCS_typedef &&
2722 !DS.isFriendSpecified()) {
2723 // It's a default member initializer.
2724 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2726 HasStaticInitializer = true;
2730 // NOTE: If Sema is the Action module and declarator is an instance field,
2731 // this call will *not* return the created decl; It will return null.
2732 // See Sema::ActOnCXXMemberDeclarator for details.
2734 NamedDecl *ThisDecl = nullptr;
2735 if (DS.isFriendSpecified()) {
2736 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2737 // to a friend declaration, that declaration shall be a definition.
2739 // Diagnose attributes that appear in a friend member function declarator:
2740 // friend int foo [[]] ();
2741 SmallVector<SourceRange, 4> Ranges;
2742 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2743 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2744 E = Ranges.end(); I != E; ++I)
2745 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2747 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2750 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2754 VS, HasInClassInit);
2756 if (VarTemplateDecl *VT =
2757 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2758 // Re-direct this decl to refer to the templated decl so that we can
2760 ThisDecl = VT->getTemplatedDecl();
2762 if (ThisDecl && AccessAttrs)
2763 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2766 // Error recovery might have converted a non-static member into a static
2768 if (HasInClassInit != ICIS_NoInit &&
2769 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2770 DeclSpec::SCS_static) {
2771 HasInClassInit = ICIS_NoInit;
2772 HasStaticInitializer = true;
2775 if (ThisDecl && PureSpecLoc.isValid())
2776 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2778 // Handle the initializer.
2779 if (HasInClassInit != ICIS_NoInit) {
2780 // The initializer was deferred; parse it and cache the tokens.
2781 Diag(Tok, getLangOpts().CPlusPlus11
2782 ? diag::warn_cxx98_compat_nonstatic_member_init
2783 : diag::ext_nonstatic_member_init);
2785 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2786 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2787 // declarator is followed by an initializer.
2789 // A brace-or-equal-initializer for a member-declarator is not an
2790 // initializer in the grammar, so this is ill-formed.
2791 Diag(Tok, diag::err_incomplete_array_member_init);
2792 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2794 // Avoid later warnings about a class member of incomplete type.
2796 ThisDecl->setInvalidDecl();
2798 ParseCXXNonStaticMemberInitializer(ThisDecl);
2799 } else if (HasStaticInitializer) {
2800 // Normal initializer.
2801 ExprResult Init = ParseCXXMemberInitializer(
2802 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2804 if (Init.isInvalid())
2805 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2807 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
2808 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2810 Actions.ActOnUninitializedDecl(ThisDecl);
2813 if (!ThisDecl->isInvalidDecl()) {
2814 // Set the Decl for any late parsed attributes
2815 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2816 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2818 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2819 LateParsedAttrs[i]->addDecl(ThisDecl);
2821 Actions.FinalizeDeclaration(ThisDecl);
2822 DeclsInGroup.push_back(ThisDecl);
2824 if (DeclaratorInfo.isFunctionDeclarator() &&
2825 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2826 DeclSpec::SCS_typedef)
2827 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2829 LateParsedAttrs.clear();
2831 DeclaratorInfo.complete(ThisDecl);
2833 // If we don't have a comma, it is either the end of the list (a ';')
2834 // or an error, bail out.
2835 SourceLocation CommaLoc;
2836 if (!TryConsumeToken(tok::comma, CommaLoc))
2839 if (Tok.isAtStartOfLine() &&
2840 !MightBeDeclarator(Declarator::MemberContext)) {
2841 // This comma was followed by a line-break and something which can't be
2842 // the start of a declarator. The comma was probably a typo for a
2844 Diag(CommaLoc, diag::err_expected_semi_declaration)
2845 << FixItHint::CreateReplacement(CommaLoc, ";");
2850 // Parse the next declarator.
2851 DeclaratorInfo.clear();
2853 BitfieldSize = ExprResult(/*Invalid=*/false);
2854 EqualLoc = PureSpecLoc = SourceLocation();
2855 DeclaratorInfo.setCommaLoc(CommaLoc);
2857 // GNU attributes are allowed before the second and subsequent declarator.
2858 MaybeParseGNUAttributes(DeclaratorInfo);
2860 if (ParseCXXMemberDeclaratorBeforeInitializer(
2861 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2866 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2867 // Skip to end of block or statement.
2868 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2869 // If we stopped at a ';', eat it.
2870 TryConsumeToken(tok::semi);
2874 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2877 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2878 /// Also detect and reject any attempted defaulted/deleted function definition.
2879 /// The location of the '=', if any, will be placed in EqualLoc.
2881 /// This does not check for a pure-specifier; that's handled elsewhere.
2883 /// brace-or-equal-initializer:
2884 /// '=' initializer-expression
2885 /// braced-init-list
2887 /// initializer-clause:
2888 /// assignment-expression
2889 /// braced-init-list
2891 /// defaulted/deleted function-definition:
2895 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2896 /// be a constant-expression.
2897 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2898 SourceLocation &EqualLoc) {
2899 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2900 && "Data member initializer not starting with '=' or '{'");
2902 EnterExpressionEvaluationContext Context(
2903 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
2904 if (TryConsumeToken(tok::equal, EqualLoc)) {
2905 if (Tok.is(tok::kw_delete)) {
2906 // In principle, an initializer of '= delete p;' is legal, but it will
2907 // never type-check. It's better to diagnose it as an ill-formed expression
2908 // than as an ill-formed deleted non-function member.
2909 // An initializer of '= delete p, foo' will never be parsed, because
2910 // a top-level comma always ends the initializer expression.
2911 const Token &Next = NextToken();
2912 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2914 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2917 Diag(ConsumeToken(), diag::err_deleted_non_function);
2920 } else if (Tok.is(tok::kw_default)) {
2922 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2925 Diag(ConsumeToken(), diag::err_default_special_members);
2929 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2930 Diag(Tok, diag::err_ms_property_initializer) << PD;
2933 return ParseInitializer();
2936 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2937 SourceLocation AttrFixitLoc,
2938 unsigned TagType, Decl *TagDecl) {
2939 // Skip the optional 'final' keyword.
2940 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2941 assert(isCXX11FinalKeyword() && "not a class definition");
2944 // Diagnose any C++11 attributes after 'final' keyword.
2945 // We deliberately discard these attributes.
2946 ParsedAttributesWithRange Attrs(AttrFactory);
2947 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2949 // This can only happen if we had malformed misplaced attributes;
2950 // we only get called if there is a colon or left-brace after the
2952 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2956 // Skip the base clauses. This requires actually parsing them, because
2957 // otherwise we can't be sure where they end (a left brace may appear
2958 // within a template argument).
2959 if (Tok.is(tok::colon)) {
2960 // Enter the scope of the class so that we can correctly parse its bases.
2961 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2962 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2963 TagType == DeclSpec::TST_interface);
2965 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2967 // Parse the bases but don't attach them to the class.
2968 ParseBaseClause(nullptr);
2970 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2972 if (!Tok.is(tok::l_brace)) {
2973 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2974 diag::err_expected_lbrace_after_base_specifiers);
2980 assert(Tok.is(tok::l_brace));
2981 BalancedDelimiterTracker T(*this, tok::l_brace);
2985 // Parse and discard any trailing attributes.
2986 ParsedAttributes Attrs(AttrFactory);
2987 if (Tok.is(tok::kw___attribute))
2988 MaybeParseGNUAttributes(Attrs);
2991 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
2992 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2993 DeclSpec::TST TagType, Decl *TagDecl) {
2994 switch (Tok.getKind()) {
2995 case tok::kw___if_exists:
2996 case tok::kw___if_not_exists:
2997 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
3001 // Check for extraneous top-level semicolon.
3002 ConsumeExtraSemi(InsideStruct, TagType);
3005 // Handle pragmas that can appear as member declarations.
3006 case tok::annot_pragma_vis:
3007 HandlePragmaVisibility();
3009 case tok::annot_pragma_pack:
3012 case tok::annot_pragma_align:
3013 HandlePragmaAlign();
3015 case tok::annot_pragma_ms_pointers_to_members:
3016 HandlePragmaMSPointersToMembers();
3018 case tok::annot_pragma_ms_pragma:
3019 HandlePragmaMSPragma();
3021 case tok::annot_pragma_ms_vtordisp:
3022 HandlePragmaMSVtorDisp();
3024 case tok::annot_pragma_dump:
3028 case tok::kw_namespace:
3029 // If we see a namespace here, a close brace was missing somewhere.
3030 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3033 case tok::kw_public:
3034 case tok::kw_protected:
3035 case tok::kw_private: {
3036 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3037 assert(NewAS != AS_none);
3038 // Current token is a C++ access specifier.
3040 SourceLocation ASLoc = Tok.getLocation();
3041 unsigned TokLength = Tok.getLength();
3043 AccessAttrs.clear();
3044 MaybeParseGNUAttributes(AccessAttrs);
3046 SourceLocation EndLoc;
3047 if (TryConsumeToken(tok::colon, EndLoc)) {
3048 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3049 Diag(EndLoc, diag::err_expected)
3050 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3052 EndLoc = ASLoc.getLocWithOffset(TokLength);
3053 Diag(EndLoc, diag::err_expected)
3054 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3057 // The Microsoft extension __interface does not permit non-public
3058 // access specifiers.
3059 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3060 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3063 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3064 AccessAttrs.getList())) {
3065 // found another attribute than only annotations
3066 AccessAttrs.clear();
3072 case tok::annot_pragma_openmp:
3073 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3077 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3081 /// ParseCXXMemberSpecification - Parse the class definition.
3083 /// member-specification:
3084 /// member-declaration member-specification[opt]
3085 /// access-specifier ':' member-specification[opt]
3087 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3088 SourceLocation AttrFixitLoc,
3089 ParsedAttributesWithRange &Attrs,
3090 unsigned TagType, Decl *TagDecl) {
3091 assert((TagType == DeclSpec::TST_struct ||
3092 TagType == DeclSpec::TST_interface ||
3093 TagType == DeclSpec::TST_union ||
3094 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3096 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3097 "parsing struct/union/class body");
3099 // Determine whether this is a non-nested class. Note that local
3100 // classes are *not* considered to be nested classes.
3101 bool NonNestedClass = true;
3102 if (!ClassStack.empty()) {
3103 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
3104 if (S->isClassScope()) {
3105 // We're inside a class scope, so this is a nested class.
3106 NonNestedClass = false;
3108 // The Microsoft extension __interface does not permit nested classes.
3109 if (getCurrentClass().IsInterface) {
3110 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3112 << (isa<NamedDecl>(TagDecl)
3113 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3119 if ((S->getFlags() & Scope::FnScope))
3120 // If we're in a function or function template then this is a local
3121 // class rather than a nested class.
3126 // Enter a scope for the class.
3127 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3129 // Note that we are parsing a new (potentially-nested) class definition.
3130 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3131 TagType == DeclSpec::TST_interface);
3134 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3136 SourceLocation FinalLoc;
3137 bool IsFinalSpelledSealed = false;
3139 // Parse the optional 'final' keyword.
3140 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3141 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3142 assert((Specifier == VirtSpecifiers::VS_Final ||
3143 Specifier == VirtSpecifiers::VS_GNU_Final ||
3144 Specifier == VirtSpecifiers::VS_Sealed) &&
3145 "not a class definition");
3146 FinalLoc = ConsumeToken();
3147 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
3149 if (TagType == DeclSpec::TST_interface)
3150 Diag(FinalLoc, diag::err_override_control_interface)
3151 << VirtSpecifiers::getSpecifierName(Specifier);
3152 else if (Specifier == VirtSpecifiers::VS_Final)
3153 Diag(FinalLoc, getLangOpts().CPlusPlus11
3154 ? diag::warn_cxx98_compat_override_control_keyword
3155 : diag::ext_override_control_keyword)
3156 << VirtSpecifiers::getSpecifierName(Specifier);
3157 else if (Specifier == VirtSpecifiers::VS_Sealed)
3158 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3159 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3160 Diag(FinalLoc, diag::ext_warn_gnu_final);
3162 // Parse any C++11 attributes after 'final' keyword.
3163 // These attributes are not allowed to appear here,
3164 // and the only possible place for them to appertain
3165 // to the class would be between class-key and class-name.
3166 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3168 // ParseClassSpecifier() does only a superficial check for attributes before
3169 // deciding to call this method. For example, for
3170 // `class C final alignas ([l) {` it will decide that this looks like a
3171 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3172 // attribute parsing code will try to parse the '[' as a constexpr lambda
3173 // and consume enough tokens that the alignas parsing code will eat the
3174 // opening '{'. So bail out if the next token isn't one we expect.
3175 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3177 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3182 if (Tok.is(tok::colon)) {
3183 ParseBaseClause(TagDecl);
3184 if (!Tok.is(tok::l_brace)) {
3185 bool SuggestFixIt = false;
3186 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3187 if (Tok.isAtStartOfLine()) {
3188 switch (Tok.getKind()) {
3189 case tok::kw_private:
3190 case tok::kw_protected:
3191 case tok::kw_public:
3192 SuggestFixIt = NextToken().getKind() == tok::colon;
3194 case tok::kw_static_assert:
3197 // base-clause can have simple-template-id; 'template' can't be there
3198 case tok::kw_template:
3199 SuggestFixIt = true;
3201 case tok::identifier:
3202 SuggestFixIt = isConstructorDeclarator(true);
3205 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3209 DiagnosticBuilder LBraceDiag =
3210 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3212 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3213 // Try recovering from missing { after base-clause.
3215 Tok.setKind(tok::l_brace);
3218 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3224 assert(Tok.is(tok::l_brace));
3225 BalancedDelimiterTracker T(*this, tok::l_brace);
3229 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3230 IsFinalSpelledSealed,
3231 T.getOpenLocation());
3233 // C++ 11p3: Members of a class defined with the keyword class are private
3234 // by default. Members of a class defined with the keywords struct or union
3235 // are public by default.
3236 AccessSpecifier CurAS;
3237 if (TagType == DeclSpec::TST_class)
3241 ParsedAttributesWithRange AccessAttrs(AttrFactory);
3244 // While we still have something to read, read the member-declarations.
3245 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3246 Tok.isNot(tok::eof)) {
3247 // Each iteration of this loop reads one member-declaration.
3248 ParseCXXClassMemberDeclarationWithPragmas(
3249 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3253 SkipUntil(tok::r_brace);
3256 // If attributes exist after class contents, parse them.
3257 ParsedAttributes attrs(AttrFactory);
3258 MaybeParseGNUAttributes(attrs);
3261 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3262 T.getOpenLocation(),
3263 T.getCloseLocation(),
3266 // C++11 [class.mem]p2:
3267 // Within the class member-specification, the class is regarded as complete
3268 // within function bodies, default arguments, exception-specifications, and
3269 // brace-or-equal-initializers for non-static data members (including such
3270 // things in nested classes).
3271 if (TagDecl && NonNestedClass) {
3272 // We are not inside a nested class. This class and its nested classes
3273 // are complete and we can parse the delayed portions of method
3274 // declarations and the lexed inline method definitions, along with any
3275 // delayed attributes.
3276 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3277 ParseLexedAttributes(getCurrentClass());
3278 ParseLexedMethodDeclarations(getCurrentClass());
3280 // We've finished with all pending member declarations.
3281 Actions.ActOnFinishCXXMemberDecls();
3283 ParseLexedMemberInitializers(getCurrentClass());
3284 ParseLexedMethodDefs(getCurrentClass());
3285 PrevTokLocation = SavedPrevTokLocation;
3287 // We've finished parsing everything, including default argument
3289 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3293 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3295 // Leave the class scope.
3300 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3301 assert(Tok.is(tok::kw_namespace));
3303 // FIXME: Suggest where the close brace should have gone by looking
3304 // at indentation changes within the definition body.
3305 Diag(D->getLocation(),
3306 diag::err_missing_end_of_definition) << D;
3307 Diag(Tok.getLocation(),
3308 diag::note_missing_end_of_definition_before) << D;
3310 // Push '};' onto the token stream to recover.
3314 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3315 Tok.setKind(tok::semi);
3318 Tok.setKind(tok::r_brace);
3321 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3322 /// which explicitly initializes the members or base classes of a
3323 /// class (C++ [class.base.init]). For example, the three initializers
3324 /// after the ':' in the Derived constructor below:
3328 /// class Derived : Base {
3332 /// Derived(float f) : Base(), x(17), f(f) { }
3336 /// [C++] ctor-initializer:
3337 /// ':' mem-initializer-list
3339 /// [C++] mem-initializer-list:
3340 /// mem-initializer ...[opt]
3341 /// mem-initializer ...[opt] , mem-initializer-list
3342 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3343 assert(Tok.is(tok::colon) &&
3344 "Constructor initializer always starts with ':'");
3346 // Poison the SEH identifiers so they are flagged as illegal in constructor
3348 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3349 SourceLocation ColonLoc = ConsumeToken();
3351 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3352 bool AnyErrors = false;
3355 if (Tok.is(tok::code_completion)) {
3356 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3358 return cutOffParsing();
3361 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3362 if (!MemInit.isInvalid())
3363 MemInitializers.push_back(MemInit.get());
3367 if (Tok.is(tok::comma))
3369 else if (Tok.is(tok::l_brace))
3371 // If the previous initializer was valid and the next token looks like a
3372 // base or member initializer, assume that we're just missing a comma.
3373 else if (!MemInit.isInvalid() &&
3374 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3375 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3376 Diag(Loc, diag::err_ctor_init_missing_comma)
3377 << FixItHint::CreateInsertion(Loc, ", ");
3379 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3380 if (!MemInit.isInvalid())
3381 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3383 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3388 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3392 /// ParseMemInitializer - Parse a C++ member initializer, which is
3393 /// part of a constructor initializer that explicitly initializes one
3394 /// member or base class (C++ [class.base.init]). See
3395 /// ParseConstructorInitializer for an example.
3397 /// [C++] mem-initializer:
3398 /// mem-initializer-id '(' expression-list[opt] ')'
3399 /// [C++0x] mem-initializer-id braced-init-list
3401 /// [C++] mem-initializer-id:
3402 /// '::'[opt] nested-name-specifier[opt] class-name
3404 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3405 // parse '::'[opt] nested-name-specifier[opt]
3407 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
3410 IdentifierInfo *II = nullptr;
3411 SourceLocation IdLoc = Tok.getLocation();
3413 DeclSpec DS(AttrFactory);
3414 // : template_name<...>
3415 ParsedType TemplateTypeTy;
3417 if (Tok.is(tok::identifier)) {
3418 // Get the identifier. This may be a member name or a class name,
3419 // but we'll let the semantic analysis determine which it is.
3420 II = Tok.getIdentifierInfo();
3422 } else if (Tok.is(tok::annot_decltype)) {
3423 // Get the decltype expression, if there is one.
3424 // Uses of decltype will already have been converted to annot_decltype by
3425 // ParseOptionalCXXScopeSpecifier at this point.
3426 // FIXME: Can we get here with a scope specifier?
3427 ParseDecltypeSpecifier(DS);
3429 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3430 ? takeTemplateIdAnnotation(Tok)
3432 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3433 TemplateId->Kind == TNK_Dependent_template_name)) {
3434 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
3435 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3436 TemplateTypeTy = getTypeAnnotation(Tok);
3437 ConsumeAnnotationToken();
3439 Diag(Tok, diag::err_expected_member_or_base_name);
3445 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3446 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3448 ExprResult InitList = ParseBraceInitializer();
3449 if (InitList.isInvalid())
3452 SourceLocation EllipsisLoc;
3453 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3455 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3456 TemplateTypeTy, DS, IdLoc,
3457 InitList.get(), EllipsisLoc);
3458 } else if(Tok.is(tok::l_paren)) {
3459 BalancedDelimiterTracker T(*this, tok::l_paren);
3462 // Parse the optional expression-list.
3463 ExprVector ArgExprs;
3464 CommaLocsTy CommaLocs;
3465 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
3466 SkipUntil(tok::r_paren, StopAtSemi);
3472 SourceLocation EllipsisLoc;
3473 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3475 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3476 TemplateTypeTy, DS, IdLoc,
3477 T.getOpenLocation(), ArgExprs,
3478 T.getCloseLocation(), EllipsisLoc);
3481 if (getLangOpts().CPlusPlus11)
3482 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3484 return Diag(Tok, diag::err_expected) << tok::l_paren;
3487 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
3489 /// exception-specification:
3490 /// dynamic-exception-specification
3491 /// noexcept-specification
3493 /// noexcept-specification:
3495 /// 'noexcept' '(' constant-expression ')'
3496 ExceptionSpecificationType
3497 Parser::tryParseExceptionSpecification(bool Delayed,
3498 SourceRange &SpecificationRange,
3499 SmallVectorImpl<ParsedType> &DynamicExceptions,
3500 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3501 ExprResult &NoexceptExpr,
3502 CachedTokens *&ExceptionSpecTokens) {
3503 ExceptionSpecificationType Result = EST_None;
3504 ExceptionSpecTokens = nullptr;
3506 // Handle delayed parsing of exception-specifications.
3508 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3511 // Consume and cache the starting token.
3512 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3513 Token StartTok = Tok;
3514 SpecificationRange = SourceRange(ConsumeToken());
3517 if (!Tok.is(tok::l_paren)) {
3518 // If this is a bare 'noexcept', we're done.
3520 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3521 NoexceptExpr = nullptr;
3522 return EST_BasicNoexcept;
3525 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3526 return EST_DynamicNone;
3529 // Cache the tokens for the exception-specification.
3530 ExceptionSpecTokens = new CachedTokens;
3531 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3532 ExceptionSpecTokens->push_back(Tok); // '('
3533 SpecificationRange.setEnd(ConsumeParen()); // '('
3535 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3536 /*StopAtSemi=*/true,
3537 /*ConsumeFinalToken=*/true);
3538 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3540 return EST_Unparsed;
3543 // See if there's a dynamic specification.
3544 if (Tok.is(tok::kw_throw)) {
3545 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3547 DynamicExceptionRanges);
3548 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3549 "Produced different number of exception types and ranges.");
3552 // If there's no noexcept specification, we're done.
3553 if (Tok.isNot(tok::kw_noexcept))
3556 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3558 // If we already had a dynamic specification, parse the noexcept for,
3559 // recovery, but emit a diagnostic and don't store the results.
3560 SourceRange NoexceptRange;
3561 ExceptionSpecificationType NoexceptType = EST_None;
3563 SourceLocation KeywordLoc = ConsumeToken();
3564 if (Tok.is(tok::l_paren)) {
3565 // There is an argument.
3566 BalancedDelimiterTracker T(*this, tok::l_paren);
3568 NoexceptType = EST_ComputedNoexcept;
3569 NoexceptExpr = ParseConstantExpression();
3571 // The argument must be contextually convertible to bool. We use
3572 // CheckBooleanCondition for this purpose.
3573 // FIXME: Add a proper Sema entry point for this.
3574 if (!NoexceptExpr.isInvalid()) {
3576 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
3577 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3579 NoexceptType = EST_BasicNoexcept;
3582 // There is no argument.
3583 NoexceptType = EST_BasicNoexcept;
3584 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3587 if (Result == EST_None) {
3588 SpecificationRange = NoexceptRange;
3589 Result = NoexceptType;
3591 // If there's a dynamic specification after a noexcept specification,
3592 // parse that and ignore the results.
3593 if (Tok.is(tok::kw_throw)) {
3594 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3595 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3596 DynamicExceptionRanges);
3599 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3605 static void diagnoseDynamicExceptionSpecification(
3606 Parser &P, SourceRange Range, bool IsNoexcept) {
3607 if (P.getLangOpts().CPlusPlus11) {
3608 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3609 P.Diag(Range.getBegin(),
3610 P.getLangOpts().CPlusPlus1z && !IsNoexcept
3611 ? diag::ext_dynamic_exception_spec
3612 : diag::warn_exception_spec_deprecated)
3614 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3615 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3619 /// ParseDynamicExceptionSpecification - Parse a C++
3620 /// dynamic-exception-specification (C++ [except.spec]).
3622 /// dynamic-exception-specification:
3623 /// 'throw' '(' type-id-list [opt] ')'
3624 /// [MS] 'throw' '(' '...' ')'
3627 /// type-id ... [opt]
3628 /// type-id-list ',' type-id ... [opt]
3630 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3631 SourceRange &SpecificationRange,
3632 SmallVectorImpl<ParsedType> &Exceptions,
3633 SmallVectorImpl<SourceRange> &Ranges) {
3634 assert(Tok.is(tok::kw_throw) && "expected throw");
3636 SpecificationRange.setBegin(ConsumeToken());
3637 BalancedDelimiterTracker T(*this, tok::l_paren);
3638 if (T.consumeOpen()) {
3639 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3640 SpecificationRange.setEnd(SpecificationRange.getBegin());
3641 return EST_DynamicNone;
3644 // Parse throw(...), a Microsoft extension that means "this function
3645 // can throw anything".
3646 if (Tok.is(tok::ellipsis)) {
3647 SourceLocation EllipsisLoc = ConsumeToken();
3648 if (!getLangOpts().MicrosoftExt)
3649 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3651 SpecificationRange.setEnd(T.getCloseLocation());
3652 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3656 // Parse the sequence of type-ids.
3658 while (Tok.isNot(tok::r_paren)) {
3659 TypeResult Res(ParseTypeName(&Range));
3661 if (Tok.is(tok::ellipsis)) {
3662 // C++0x [temp.variadic]p5:
3663 // - In a dynamic-exception-specification (15.4); the pattern is a
3665 SourceLocation Ellipsis = ConsumeToken();
3666 Range.setEnd(Ellipsis);
3667 if (!Res.isInvalid())
3668 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3671 if (!Res.isInvalid()) {
3672 Exceptions.push_back(Res.get());
3673 Ranges.push_back(Range);
3676 if (!TryConsumeToken(tok::comma))
3681 SpecificationRange.setEnd(T.getCloseLocation());
3682 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3683 Exceptions.empty());
3684 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3687 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3688 /// function declaration.
3689 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3690 assert(Tok.is(tok::arrow) && "expected arrow");
3694 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3697 /// \brief We have just started parsing the definition of a new class,
3698 /// so push that class onto our stack of classes that is currently
3700 Sema::ParsingClassState
3701 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3703 assert((NonNestedClass || !ClassStack.empty()) &&
3704 "Nested class without outer class");
3705 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3706 return Actions.PushParsingClass();
3709 /// \brief Deallocate the given parsed class and all of its nested
3711 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3712 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3713 delete Class->LateParsedDeclarations[I];
3717 /// \brief Pop the top class of the stack of classes that are
3718 /// currently being parsed.
3720 /// This routine should be called when we have finished parsing the
3721 /// definition of a class, but have not yet popped the Scope
3722 /// associated with the class's definition.
3723 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3724 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3726 Actions.PopParsingClass(state);
3728 ParsingClass *Victim = ClassStack.top();
3730 if (Victim->TopLevelClass) {
3731 // Deallocate all of the nested classes of this class,
3732 // recursively: we don't need to keep any of this information.
3733 DeallocateParsedClasses(Victim);
3736 assert(!ClassStack.empty() && "Missing top-level class?");
3738 if (Victim->LateParsedDeclarations.empty()) {
3739 // The victim is a nested class, but we will not need to perform
3740 // any processing after the definition of this class since it has
3741 // no members whose handling was delayed. Therefore, we can just
3742 // remove this nested class.
3743 DeallocateParsedClasses(Victim);
3747 // This nested class has some members that will need to be processed
3748 // after the top-level class is completely defined. Therefore, add
3749 // it to the list of nested classes within its parent.
3750 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3751 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3752 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3755 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3757 /// \return the parsed identifier on success, and 0 if the next token is not an
3758 /// attribute-token.
3760 /// C++11 [dcl.attr.grammar]p3:
3761 /// If a keyword or an alternative token that satisfies the syntactic
3762 /// requirements of an identifier is contained in an attribute-token,
3763 /// it is considered an identifier.
3764 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3765 switch (Tok.getKind()) {
3767 // Identifiers and keywords have identifier info attached.
3768 if (!Tok.isAnnotation()) {
3769 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3770 Loc = ConsumeToken();
3776 case tok::ampamp: // 'and'
3777 case tok::pipe: // 'bitor'
3778 case tok::pipepipe: // 'or'
3779 case tok::caret: // 'xor'
3780 case tok::tilde: // 'compl'
3781 case tok::amp: // 'bitand'
3782 case tok::ampequal: // 'and_eq'
3783 case tok::pipeequal: // 'or_eq'
3784 case tok::caretequal: // 'xor_eq'
3785 case tok::exclaim: // 'not'
3786 case tok::exclaimequal: // 'not_eq'
3787 // Alternative tokens do not have identifier info, but their spelling
3788 // starts with an alphabetical character.
3789 SmallString<8> SpellingBuf;
3790 SourceLocation SpellingLoc =
3791 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3792 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3793 if (isLetter(Spelling[0])) {
3794 Loc = ConsumeToken();
3795 return &PP.getIdentifierTable().get(Spelling);
3801 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3802 IdentifierInfo *ScopeName) {
3803 switch (AttributeList::getKind(AttrName, ScopeName,
3804 AttributeList::AS_CXX11)) {
3805 case AttributeList::AT_CarriesDependency:
3806 case AttributeList::AT_Deprecated:
3807 case AttributeList::AT_FallThrough:
3808 case AttributeList::AT_CXX11NoReturn:
3810 case AttributeList::AT_WarnUnusedResult:
3811 return !ScopeName && AttrName->getName().equals("nodiscard");
3812 case AttributeList::AT_Unused:
3813 return !ScopeName && AttrName->getName().equals("maybe_unused");
3819 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3821 /// [C++11] attribute-argument-clause:
3822 /// '(' balanced-token-seq ')'
3824 /// [C++11] balanced-token-seq:
3826 /// balanced-token-seq balanced-token
3828 /// [C++11] balanced-token:
3829 /// '(' balanced-token-seq ')'
3830 /// '[' balanced-token-seq ']'
3831 /// '{' balanced-token-seq '}'
3832 /// any token but '(', ')', '[', ']', '{', or '}'
3833 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3834 SourceLocation AttrNameLoc,
3835 ParsedAttributes &Attrs,
3836 SourceLocation *EndLoc,
3837 IdentifierInfo *ScopeName,
3838 SourceLocation ScopeLoc) {
3839 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3840 SourceLocation LParenLoc = Tok.getLocation();
3842 // If the attribute isn't known, we will not attempt to parse any
3844 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
3845 getTargetInfo(), getLangOpts())) {
3846 // Eat the left paren, then skip to the ending right paren.
3848 SkipUntil(tok::r_paren);
3852 if (ScopeName && ScopeName->getName() == "gnu") {
3853 // GNU-scoped attributes have some special cases to handle GNU-specific
3855 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3856 ScopeLoc, AttributeList::AS_CXX11, nullptr);
3861 // Some Clang-scoped attributes have some special parsing behavior.
3862 if (ScopeName && ScopeName->getName() == "clang")
3864 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3865 ScopeLoc, AttributeList::AS_CXX11);
3868 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3869 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3871 const AttributeList *Attr = Attrs.getList();
3872 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3873 // If the attribute is a standard or built-in attribute and we are
3874 // parsing an argument list, we need to determine whether this attribute
3875 // was allowed to have an argument list (such as [[deprecated]]), and how
3876 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3877 if (Attr->getMaxArgs() && !NumArgs) {
3878 // The attribute was allowed to have arguments, but none were provided
3879 // even though the attribute parsed successfully. This is an error.
3880 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3881 Attr->setInvalid(true);
3882 } else if (!Attr->getMaxArgs()) {
3883 // The attribute parsed successfully, but was not allowed to have any
3884 // arguments. It doesn't matter whether any were provided -- the
3885 // presence of the argument list (even if empty) is diagnosed.
3886 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3888 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3889 Attr->setInvalid(true);
3895 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
3897 /// [C++11] attribute-specifier:
3898 /// '[' '[' attribute-list ']' ']'
3899 /// alignment-specifier
3901 /// [C++11] attribute-list:
3903 /// attribute-list ',' attribute[opt]
3905 /// attribute-list ',' attribute '...'
3907 /// [C++11] attribute:
3908 /// attribute-token attribute-argument-clause[opt]
3910 /// [C++11] attribute-token:
3912 /// attribute-scoped-token
3914 /// [C++11] attribute-scoped-token:
3915 /// attribute-namespace '::' identifier
3917 /// [C++11] attribute-namespace:
3919 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3920 SourceLocation *endLoc) {
3921 if (Tok.is(tok::kw_alignas)) {
3922 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3923 ParseAlignmentSpecifier(attrs, endLoc);
3927 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3928 && "Not a C++11 attribute list");
3930 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3935 SourceLocation CommonScopeLoc;
3936 IdentifierInfo *CommonScopeName = nullptr;
3937 if (Tok.is(tok::kw_using)) {
3938 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
3939 ? diag::warn_cxx14_compat_using_attribute_ns
3940 : diag::ext_using_attribute_ns);
3943 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3944 if (!CommonScopeName) {
3945 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3946 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3948 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3949 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3952 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3954 while (Tok.isNot(tok::r_square)) {
3955 // attribute not present
3956 if (TryConsumeToken(tok::comma))
3959 SourceLocation ScopeLoc, AttrLoc;
3960 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3962 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3964 // Break out to the "expected ']'" diagnostic.
3968 if (TryConsumeToken(tok::coloncolon)) {
3969 ScopeName = AttrName;
3972 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3974 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3975 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3980 if (CommonScopeName) {
3982 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
3983 << SourceRange(CommonScopeLoc);
3985 ScopeName = CommonScopeName;
3986 ScopeLoc = CommonScopeLoc;
3990 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
3991 bool AttrParsed = false;
3994 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3995 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
3996 << AttrName << SourceRange(SeenAttrs[AttrName]);
3998 // Parse attribute arguments
3999 if (Tok.is(tok::l_paren))
4000 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4001 ScopeName, ScopeLoc);
4004 attrs.addNew(AttrName,
4005 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
4007 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
4009 if (TryConsumeToken(tok::ellipsis))
4010 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4011 << AttrName->getName();
4014 if (ExpectAndConsume(tok::r_square))
4015 SkipUntil(tok::r_square);
4017 *endLoc = Tok.getLocation();
4018 if (ExpectAndConsume(tok::r_square))
4019 SkipUntil(tok::r_square);
4022 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
4024 /// attribute-specifier-seq:
4025 /// attribute-specifier-seq[opt] attribute-specifier
4026 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
4027 SourceLocation *endLoc) {
4028 assert(getLangOpts().CPlusPlus11);
4030 SourceLocation StartLoc = Tok.getLocation(), Loc;
4035 ParseCXX11AttributeSpecifier(attrs, endLoc);
4036 } while (isCXX11AttributeSpecifier());
4038 attrs.Range = SourceRange(StartLoc, *endLoc);
4041 void Parser::DiagnoseAndSkipCXX11Attributes() {
4042 // Start and end location of an attribute or an attribute list.
4043 SourceLocation StartLoc = Tok.getLocation();
4044 SourceLocation EndLoc = SkipCXX11Attributes();
4046 if (EndLoc.isValid()) {
4047 SourceRange Range(StartLoc, EndLoc);
4048 Diag(StartLoc, diag::err_attributes_not_allowed)
4053 SourceLocation Parser::SkipCXX11Attributes() {
4054 SourceLocation EndLoc;
4056 if (!isCXX11AttributeSpecifier())
4060 if (Tok.is(tok::l_square)) {
4061 BalancedDelimiterTracker T(*this, tok::l_square);
4064 EndLoc = T.getCloseLocation();
4066 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4068 BalancedDelimiterTracker T(*this, tok::l_paren);
4069 if (!T.consumeOpen())
4071 EndLoc = T.getCloseLocation();
4073 } while (isCXX11AttributeSpecifier());
4078 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4079 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4080 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4081 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4082 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4084 SourceLocation UuidLoc = Tok.getLocation();
4087 // Ignore the left paren location for now.
4088 BalancedDelimiterTracker T(*this, tok::l_paren);
4089 if (T.consumeOpen()) {
4090 Diag(Tok, diag::err_expected) << tok::l_paren;
4094 ArgsVector ArgExprs;
4095 if (Tok.is(tok::string_literal)) {
4096 // Easy case: uuid("...") -- quoted string.
4097 ExprResult StringResult = ParseStringLiteralExpression();
4098 if (StringResult.isInvalid())
4100 ArgExprs.push_back(StringResult.get());
4102 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4103 // quotes in the parens. Just append the spelling of all tokens encountered
4104 // until the closing paren.
4106 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4109 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4110 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4111 // tok::numeric_constant (0000) should be enough. But the spelling of the
4112 // uuid argument is checked later anyways, so there's no harm in accepting
4113 // almost anything here.
4114 // cl is very strict about whitespace in this form and errors out if any
4115 // is present, so check the space flags on the tokens.
4116 SourceLocation StartLoc = Tok.getLocation();
4117 while (Tok.isNot(tok::r_paren)) {
4118 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4119 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4120 SkipUntil(tok::r_paren, StopAtSemi);
4123 SmallString<16> SpellingBuffer;
4124 SpellingBuffer.resize(Tok.getLength() + 1);
4125 bool Invalid = false;
4126 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4128 SkipUntil(tok::r_paren, StopAtSemi);
4131 StrBuffer += TokSpelling;
4136 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4137 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4142 // Pretend the user wrote the appropriate string literal here.
4143 // ActOnStringLiteral() copies the string data into the literal, so it's
4144 // ok that the Token points to StrBuffer.
4146 Toks[0].startToken();
4147 Toks[0].setKind(tok::string_literal);
4148 Toks[0].setLocation(StartLoc);
4149 Toks[0].setLiteralData(StrBuffer.data());
4150 Toks[0].setLength(StrBuffer.size());
4151 StringLiteral *UuidString =
4152 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4153 ArgExprs.push_back(UuidString);
4156 if (!T.consumeClose()) {
4157 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4158 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4159 AttributeList::AS_Microsoft);
4163 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4165 /// [MS] ms-attribute:
4166 /// '[' token-seq ']'
4168 /// [MS] ms-attribute-seq:
4169 /// ms-attribute[opt]
4170 /// ms-attribute ms-attribute-seq
4171 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4172 SourceLocation *endLoc) {
4173 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4176 // FIXME: If this is actually a C++11 attribute, parse it as one.
4177 BalancedDelimiterTracker T(*this, tok::l_square);
4180 // Skip most ms attributes except for a whitelist.
4182 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4183 if (Tok.isNot(tok::identifier)) // ']', but also eof
4185 if (Tok.getIdentifierInfo()->getName() == "uuid")
4186 ParseMicrosoftUuidAttributeArgs(attrs);
4193 *endLoc = T.getCloseLocation();
4194 } while (Tok.is(tok::l_square));
4197 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4198 AccessSpecifier& CurAS) {
4199 IfExistsCondition Result;
4200 if (ParseMicrosoftIfExistsCondition(Result))
4203 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4204 if (Braces.consumeOpen()) {
4205 Diag(Tok, diag::err_expected) << tok::l_brace;
4209 switch (Result.Behavior) {
4211 // Parse the declarations below.
4215 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4216 << Result.IsIfExists;
4217 // Fall through to skip.
4224 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4225 // __if_exists, __if_not_exists can nest.
4226 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4227 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4231 // Check for extraneous top-level semicolon.
4232 if (Tok.is(tok::semi)) {
4233 ConsumeExtraSemi(InsideStruct, TagType);
4237 AccessSpecifier AS = getAccessSpecifierIfPresent();
4238 if (AS != AS_none) {
4239 // Current token is a C++ access specifier.
4241 SourceLocation ASLoc = Tok.getLocation();
4243 if (Tok.is(tok::colon))
4244 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4246 Diag(Tok, diag::err_expected) << tok::colon;
4251 // Parse all the comma separated declarators.
4252 ParseCXXClassMemberDeclaration(CurAS, nullptr);
4255 Braces.consumeClose();