1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -----------------------===//
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 "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Basic/Attributes.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/OperatorKinds.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/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"
29 using namespace clang;
31 /// ParseNamespace - We know that the current token is a namespace keyword. This
32 /// may either be a top level namespace or a block-level namespace alias. If
33 /// there was an inline keyword, it has already been parsed.
35 /// namespace-definition: [C++ 7.3: basic.namespace]
36 /// named-namespace-definition
37 /// unnamed-namespace-definition
39 /// unnamed-namespace-definition:
40 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
42 /// named-namespace-definition:
43 /// original-namespace-definition
44 /// extension-namespace-definition
46 /// original-namespace-definition:
47 /// 'inline'[opt] 'namespace' identifier attributes[opt]
48 /// '{' namespace-body '}'
50 /// extension-namespace-definition:
51 /// 'inline'[opt] 'namespace' original-namespace-name
52 /// '{' namespace-body '}'
54 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
55 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
57 Decl *Parser::ParseNamespace(unsigned Context,
58 SourceLocation &DeclEnd,
59 SourceLocation InlineLoc) {
60 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
61 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
62 ObjCDeclContextSwitch ObjCDC(*this);
64 if (Tok.is(tok::code_completion)) {
65 Actions.CodeCompleteNamespaceDecl(getCurScope());
70 SourceLocation IdentLoc;
71 IdentifierInfo *Ident = nullptr;
72 std::vector<SourceLocation> ExtraIdentLoc;
73 std::vector<IdentifierInfo*> ExtraIdent;
74 std::vector<SourceLocation> ExtraNamespaceLoc;
76 ParsedAttributesWithRange attrs(AttrFactory);
77 SourceLocation attrLoc;
78 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
79 if (!getLangOpts().CPlusPlus1z)
80 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
82 attrLoc = Tok.getLocation();
83 ParseCXX11Attributes(attrs);
86 if (Tok.is(tok::identifier)) {
87 Ident = Tok.getIdentifierInfo();
88 IdentLoc = ConsumeToken(); // eat the identifier.
89 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
90 ExtraNamespaceLoc.push_back(ConsumeToken());
91 ExtraIdent.push_back(Tok.getIdentifierInfo());
92 ExtraIdentLoc.push_back(ConsumeToken());
96 // A nested namespace definition cannot have attributes.
97 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
98 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
100 // Read label attributes, if present.
101 if (Tok.is(tok::kw___attribute)) {
102 attrLoc = Tok.getLocation();
103 ParseGNUAttributes(attrs);
106 if (Tok.is(tok::equal)) {
108 Diag(Tok, diag::err_expected) << tok::identifier;
109 // Skip to end of the definition and eat the ';'.
110 SkipUntil(tok::semi);
113 if (attrLoc.isValid())
114 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
115 if (InlineLoc.isValid())
116 Diag(InlineLoc, diag::err_inline_namespace_alias)
117 << FixItHint::CreateRemoval(InlineLoc);
118 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
122 BalancedDelimiterTracker T(*this, tok::l_brace);
123 if (T.consumeOpen()) {
125 Diag(Tok, diag::err_expected) << tok::l_brace;
127 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
131 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
132 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
133 getCurScope()->getFnParent()) {
134 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
135 SkipUntil(tok::r_brace);
139 if (ExtraIdent.empty()) {
140 // Normal namespace definition, not a nested-namespace-definition.
141 } else if (InlineLoc.isValid()) {
142 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
143 } else if (getLangOpts().CPlusPlus1z) {
144 Diag(ExtraNamespaceLoc[0],
145 diag::warn_cxx14_compat_nested_namespace_definition);
147 TentativeParsingAction TPA(*this);
148 SkipUntil(tok::r_brace, StopBeforeMatch);
149 Token rBraceToken = Tok;
152 if (!rBraceToken.is(tok::r_brace)) {
153 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
154 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
156 std::string NamespaceFix;
157 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
158 E = ExtraIdent.end(); I != E; ++I) {
159 NamespaceFix += " { namespace ";
160 NamespaceFix += (*I)->getName();
164 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
167 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
168 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
169 ExtraIdentLoc.back()),
171 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
175 // If we're still good, complain about inline namespaces in non-C++0x now.
176 if (InlineLoc.isValid())
177 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
178 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
180 // Enter a scope for the namespace.
181 ParseScope NamespaceScope(this, Scope::DeclScope);
184 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
185 IdentLoc, Ident, T.getOpenLocation(),
188 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
189 "parsing namespace");
191 // Parse the contents of the namespace. This includes parsing recovery on
192 // any improperly nested namespaces.
193 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
194 InlineLoc, attrs, T);
196 // Leave the namespace scope.
197 NamespaceScope.Exit();
199 DeclEnd = T.getCloseLocation();
200 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
205 /// ParseInnerNamespace - Parse the contents of a namespace.
206 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
207 std::vector<IdentifierInfo *> &Ident,
208 std::vector<SourceLocation> &NamespaceLoc,
209 unsigned int index, SourceLocation &InlineLoc,
210 ParsedAttributes &attrs,
211 BalancedDelimiterTracker &Tracker) {
212 if (index == Ident.size()) {
213 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
214 ParsedAttributesWithRange attrs(AttrFactory);
215 MaybeParseCXX11Attributes(attrs);
216 MaybeParseMicrosoftAttributes(attrs);
217 ParseExternalDeclaration(attrs);
220 // The caller is what called check -- we are simply calling
222 Tracker.consumeClose();
227 // Handle a nested namespace definition.
228 // FIXME: Preserve the source information through to the AST rather than
229 // desugaring it here.
230 ParseScope NamespaceScope(this, Scope::DeclScope);
232 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
233 NamespaceLoc[index], IdentLoc[index],
234 Ident[index], Tracker.getOpenLocation(),
237 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
240 NamespaceScope.Exit();
242 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
245 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
246 /// alias definition.
248 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
249 SourceLocation AliasLoc,
250 IdentifierInfo *Alias,
251 SourceLocation &DeclEnd) {
252 assert(Tok.is(tok::equal) && "Not equal token");
254 ConsumeToken(); // eat the '='.
256 if (Tok.is(tok::code_completion)) {
257 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
263 // Parse (optional) nested-name-specifier.
264 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
266 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
267 Diag(Tok, diag::err_expected_namespace_name);
268 // Skip to end of the definition and eat the ';'.
269 SkipUntil(tok::semi);
274 IdentifierInfo *Ident = Tok.getIdentifierInfo();
275 SourceLocation IdentLoc = ConsumeToken();
278 DeclEnd = Tok.getLocation();
279 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
280 SkipUntil(tok::semi);
282 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
283 SS, IdentLoc, Ident);
286 /// ParseLinkage - We know that the current token is a string_literal
287 /// and just before that, that extern was seen.
289 /// linkage-specification: [C++ 7.5p2: dcl.link]
290 /// 'extern' string-literal '{' declaration-seq[opt] '}'
291 /// 'extern' string-literal declaration
293 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
294 assert(isTokenStringLiteral() && "Not a string literal!");
295 ExprResult Lang = ParseStringLiteralExpression(false);
297 ParseScope LinkageScope(this, Scope::DeclScope);
301 : Actions.ActOnStartLinkageSpecification(
302 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
303 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
305 ParsedAttributesWithRange attrs(AttrFactory);
306 MaybeParseCXX11Attributes(attrs);
307 MaybeParseMicrosoftAttributes(attrs);
309 if (Tok.isNot(tok::l_brace)) {
310 // Reset the source range in DS, as the leading "extern"
311 // does not really belong to the inner declaration ...
312 DS.SetRangeStart(SourceLocation());
313 DS.SetRangeEnd(SourceLocation());
314 // ... but anyway remember that such an "extern" was seen.
315 DS.setExternInLinkageSpec(true);
316 ParseExternalDeclaration(attrs, &DS);
317 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
318 getCurScope(), LinkageSpec, SourceLocation())
324 ProhibitAttributes(attrs);
326 BalancedDelimiterTracker T(*this, tok::l_brace);
329 unsigned NestedModules = 0;
331 switch (Tok.getKind()) {
332 case tok::annot_module_begin:
337 case tok::annot_module_end:
344 case tok::annot_module_include:
356 ParsedAttributesWithRange attrs(AttrFactory);
357 MaybeParseCXX11Attributes(attrs);
358 MaybeParseMicrosoftAttributes(attrs);
359 ParseExternalDeclaration(attrs);
367 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
368 getCurScope(), LinkageSpec, T.getCloseLocation())
372 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
373 /// using-directive. Assumes that current token is 'using'.
374 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
375 const ParsedTemplateInfo &TemplateInfo,
376 SourceLocation &DeclEnd,
377 ParsedAttributesWithRange &attrs,
379 assert(Tok.is(tok::kw_using) && "Not using token");
380 ObjCDeclContextSwitch ObjCDC(*this);
383 SourceLocation UsingLoc = ConsumeToken();
385 if (Tok.is(tok::code_completion)) {
386 Actions.CodeCompleteUsing(getCurScope());
391 // 'using namespace' means this is a using-directive.
392 if (Tok.is(tok::kw_namespace)) {
393 // Template parameters are always an error here.
394 if (TemplateInfo.Kind) {
395 SourceRange R = TemplateInfo.getSourceRange();
396 Diag(UsingLoc, diag::err_templated_using_directive)
397 << R << FixItHint::CreateRemoval(R);
400 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
403 // Otherwise, it must be a using-declaration or an alias-declaration.
405 // Using declarations can't have attributes.
406 ProhibitAttributes(attrs);
408 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
412 /// ParseUsingDirective - Parse C++ using-directive, assumes
413 /// that current token is 'namespace' and 'using' was already parsed.
415 /// using-directive: [C++ 7.3.p4: namespace.udir]
416 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
418 /// [GNU] using-directive:
419 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
420 /// namespace-name attributes[opt] ;
422 Decl *Parser::ParseUsingDirective(unsigned Context,
423 SourceLocation UsingLoc,
424 SourceLocation &DeclEnd,
425 ParsedAttributes &attrs) {
426 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
429 SourceLocation NamespcLoc = ConsumeToken();
431 if (Tok.is(tok::code_completion)) {
432 Actions.CodeCompleteUsingDirective(getCurScope());
438 // Parse (optional) nested-name-specifier.
439 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
441 IdentifierInfo *NamespcName = nullptr;
442 SourceLocation IdentLoc = SourceLocation();
444 // Parse namespace-name.
445 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
446 Diag(Tok, diag::err_expected_namespace_name);
447 // If there was invalid namespace name, skip to end of decl, and eat ';'.
448 SkipUntil(tok::semi);
449 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
454 NamespcName = Tok.getIdentifierInfo();
455 IdentLoc = ConsumeToken();
457 // Parse (optional) attributes (most likely GNU strong-using extension).
458 bool GNUAttr = false;
459 if (Tok.is(tok::kw___attribute)) {
461 ParseGNUAttributes(attrs);
465 DeclEnd = Tok.getLocation();
466 if (ExpectAndConsume(tok::semi,
467 GNUAttr ? diag::err_expected_semi_after_attribute_list
468 : diag::err_expected_semi_after_namespace_name))
469 SkipUntil(tok::semi);
471 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
472 IdentLoc, NamespcName, attrs.getList());
475 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
476 /// Assumes that 'using' was already seen.
478 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
479 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
481 /// 'using' :: unqualified-id
483 /// alias-declaration: C++11 [dcl.dcl]p1
484 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
486 Decl *Parser::ParseUsingDeclaration(unsigned Context,
487 const ParsedTemplateInfo &TemplateInfo,
488 SourceLocation UsingLoc,
489 SourceLocation &DeclEnd,
493 SourceLocation TypenameLoc;
494 bool HasTypenameKeyword = false;
496 // Check for misplaced attributes before the identifier in an
497 // alias-declaration.
498 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
499 MaybeParseCXX11Attributes(MisplacedAttrs);
501 // Ignore optional 'typename'.
502 // FIXME: This is wrong; we should parse this as a typename-specifier.
503 if (TryConsumeToken(tok::kw_typename, TypenameLoc))
504 HasTypenameKeyword = true;
506 if (Tok.is(tok::kw___super)) {
507 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
508 SkipUntil(tok::semi);
512 // Parse nested-name-specifier.
513 IdentifierInfo *LastII = nullptr;
514 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false,
515 /*MayBePseudoDtor=*/nullptr,
516 /*IsTypename=*/false,
519 // Check nested-name specifier.
520 if (SS.isInvalid()) {
521 SkipUntil(tok::semi);
525 SourceLocation TemplateKWLoc;
528 // Parse the unqualified-id. We allow parsing of both constructor and
529 // destructor names and allow the action module to diagnose any semantic
532 // C++11 [class.qual]p2:
533 // [...] in a using-declaration that is a member-declaration, if the name
534 // specified after the nested-name-specifier is the same as the identifier
535 // or the simple-template-id's template-name in the last component of the
536 // nested-name-specifier, the name is [...] considered to name the
538 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
539 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
540 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
541 !SS.getScopeRep()->getAsNamespace() &&
542 !SS.getScopeRep()->getAsNamespaceAlias()) {
543 SourceLocation IdLoc = ConsumeToken();
544 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
545 Name.setConstructorName(Type, IdLoc, IdLoc);
546 } else if (ParseUnqualifiedId(
547 SS, /*EnteringContext=*/false,
548 /*AllowDestructorName=*/true,
549 /*AllowConstructorName=*/NextToken().isNot(tok::equal),
550 ParsedType(), TemplateKWLoc, Name)) {
551 SkipUntil(tok::semi);
555 ParsedAttributesWithRange Attrs(AttrFactory);
556 MaybeParseGNUAttributes(Attrs);
557 MaybeParseCXX11Attributes(Attrs);
559 // Maybe this is an alias-declaration.
560 TypeResult TypeAlias;
561 bool IsAliasDecl = Tok.is(tok::equal);
562 Decl *DeclFromDeclSpec = nullptr;
564 // If we had any misplaced attributes from earlier, this is where they
565 // should have been written.
566 if (MisplacedAttrs.Range.isValid()) {
567 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
568 << FixItHint::CreateInsertionFromRange(
570 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
571 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
572 Attrs.takeAllFrom(MisplacedAttrs);
577 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
578 diag::warn_cxx98_compat_alias_declaration :
579 diag::ext_alias_declaration);
581 // Type alias templates cannot be specialized.
583 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
584 Name.getKind() == UnqualifiedId::IK_TemplateId)
586 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
588 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
590 if (SpecKind != -1) {
593 Range = SourceRange(Name.TemplateId->LAngleLoc,
594 Name.TemplateId->RAngleLoc);
596 Range = TemplateInfo.getSourceRange();
597 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
598 << SpecKind << Range;
599 SkipUntil(tok::semi);
603 // Name must be an identifier.
604 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
605 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
606 // No removal fixit: can't recover from this.
607 SkipUntil(tok::semi);
609 } else if (HasTypenameKeyword)
610 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
611 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
612 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
613 else if (SS.isNotEmpty())
614 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
615 << FixItHint::CreateRemoval(SS.getRange());
617 TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind
618 ? Declarator::AliasTemplateContext
619 : Declarator::AliasDeclContext,
620 AS, &DeclFromDeclSpec, &Attrs);
622 *OwnedType = DeclFromDeclSpec;
624 // C++11 attributes are not allowed on a using-declaration, but GNU ones
626 ProhibitAttributes(MisplacedAttrs);
627 ProhibitAttributes(Attrs);
629 // Parse (optional) attributes (most likely GNU strong-using extension).
630 MaybeParseGNUAttributes(Attrs);
634 DeclEnd = Tok.getLocation();
635 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
636 !Attrs.empty() ? "attributes list"
637 : IsAliasDecl ? "alias declaration"
638 : "using declaration"))
639 SkipUntil(tok::semi);
641 // Diagnose an attempt to declare a templated using-declaration.
642 // In C++11, alias-declarations can be templates:
643 // template <...> using id = type;
644 if (TemplateInfo.Kind && !IsAliasDecl) {
645 SourceRange R = TemplateInfo.getSourceRange();
646 Diag(UsingLoc, diag::err_templated_using_declaration)
647 << R << FixItHint::CreateRemoval(R);
649 // Unfortunately, we have to bail out instead of recovering by
650 // ignoring the parameters, just in case the nested name specifier
651 // depends on the parameters.
655 // "typename" keyword is allowed for identifiers only,
656 // because it may be a type definition.
657 if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
658 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
659 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
660 // Proceed parsing, but reset the HasTypenameKeyword flag.
661 HasTypenameKeyword = false;
665 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
666 MultiTemplateParamsArg TemplateParamsArg(
667 TemplateParams ? TemplateParams->data() : nullptr,
668 TemplateParams ? TemplateParams->size() : 0);
669 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
670 UsingLoc, Name, Attrs.getList(),
671 TypeAlias, DeclFromDeclSpec);
674 return Actions.ActOnUsingDeclaration(getCurScope(), AS,
675 /* HasUsingKeyword */ true, UsingLoc,
676 SS, Name, Attrs.getList(),
677 HasTypenameKeyword, TypenameLoc);
680 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
682 /// [C++0x] static_assert-declaration:
683 /// static_assert ( constant-expression , string-literal ) ;
685 /// [C11] static_assert-declaration:
686 /// _Static_assert ( constant-expression , string-literal ) ;
688 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
689 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
690 "Not a static_assert declaration");
692 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
693 Diag(Tok, diag::ext_c11_static_assert);
694 if (Tok.is(tok::kw_static_assert))
695 Diag(Tok, diag::warn_cxx98_compat_static_assert);
697 SourceLocation StaticAssertLoc = ConsumeToken();
699 BalancedDelimiterTracker T(*this, tok::l_paren);
700 if (T.consumeOpen()) {
701 Diag(Tok, diag::err_expected) << tok::l_paren;
706 ExprResult AssertExpr(ParseConstantExpression());
707 if (AssertExpr.isInvalid()) {
712 ExprResult AssertMessage;
713 if (Tok.is(tok::r_paren)) {
714 Diag(Tok, getLangOpts().CPlusPlus1z
715 ? diag::warn_cxx14_compat_static_assert_no_message
716 : diag::ext_static_assert_no_message)
717 << (getLangOpts().CPlusPlus1z
719 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
721 if (ExpectAndConsume(tok::comma)) {
722 SkipUntil(tok::semi);
726 if (!isTokenStringLiteral()) {
727 Diag(Tok, diag::err_expected_string_literal)
728 << /*Source='static_assert'*/1;
733 AssertMessage = ParseStringLiteralExpression();
734 if (AssertMessage.isInvalid()) {
742 DeclEnd = Tok.getLocation();
743 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
745 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
748 T.getCloseLocation());
751 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
753 /// 'decltype' ( expression )
754 /// 'decltype' ( 'auto' ) [C++1y]
756 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
757 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
758 && "Not a decltype specifier");
761 SourceLocation StartLoc = Tok.getLocation();
762 SourceLocation EndLoc;
764 if (Tok.is(tok::annot_decltype)) {
765 Result = getExprAnnotation(Tok);
766 EndLoc = Tok.getAnnotationEndLoc();
768 if (Result.isInvalid()) {
769 DS.SetTypeSpecError();
773 if (Tok.getIdentifierInfo()->isStr("decltype"))
774 Diag(Tok, diag::warn_cxx98_compat_decltype);
778 BalancedDelimiterTracker T(*this, tok::l_paren);
779 if (T.expectAndConsume(diag::err_expected_lparen_after,
780 "decltype", tok::r_paren)) {
781 DS.SetTypeSpecError();
782 return T.getOpenLocation() == Tok.getLocation() ?
783 StartLoc : T.getOpenLocation();
786 // Check for C++1y 'decltype(auto)'.
787 if (Tok.is(tok::kw_auto)) {
788 // No need to disambiguate here: an expression can't start with 'auto',
789 // because the typename-specifier in a function-style cast operation can't
791 Diag(Tok.getLocation(),
792 getLangOpts().CPlusPlus14
793 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
794 : diag::ext_decltype_auto_type_specifier);
797 // Parse the expression
799 // C++11 [dcl.type.simple]p4:
800 // The operand of the decltype specifier is an unevaluated operand.
801 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
802 nullptr,/*IsDecltype=*/true);
804 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
805 return E->hasPlaceholderType() ? ExprError() : E;
807 if (Result.isInvalid()) {
808 DS.SetTypeSpecError();
809 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
810 EndLoc = ConsumeParen();
812 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
813 // Backtrack to get the location of the last token before the semi.
814 PP.RevertCachedTokens(2);
815 ConsumeToken(); // the semi.
816 EndLoc = ConsumeAnyToken();
817 assert(Tok.is(tok::semi));
819 EndLoc = Tok.getLocation();
825 Result = Actions.ActOnDecltypeExpression(Result.get());
830 if (T.getCloseLocation().isInvalid()) {
831 DS.SetTypeSpecError();
832 // FIXME: this should return the location of the last token
833 // that was consumed (by "consumeClose()")
834 return T.getCloseLocation();
837 if (Result.isInvalid()) {
838 DS.SetTypeSpecError();
839 return T.getCloseLocation();
842 EndLoc = T.getCloseLocation();
844 assert(!Result.isInvalid());
846 const char *PrevSpec = nullptr;
848 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
849 // Check for duplicate type specifiers (e.g. "int decltype(a)").
851 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
852 DiagID, Result.get(), Policy)
853 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
855 Diag(StartLoc, DiagID) << PrevSpec;
856 DS.SetTypeSpecError();
861 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
862 SourceLocation StartLoc,
863 SourceLocation EndLoc) {
864 // make sure we have a token we can turn into an annotation token
865 if (PP.isBacktrackEnabled())
866 PP.RevertCachedTokens(1);
870 Tok.setKind(tok::annot_decltype);
871 setExprAnnotation(Tok,
872 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
873 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
875 Tok.setAnnotationEndLoc(EndLoc);
876 Tok.setLocation(StartLoc);
877 PP.AnnotateCachedTokens(Tok);
880 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
881 assert(Tok.is(tok::kw___underlying_type) &&
882 "Not an underlying type specifier");
884 SourceLocation StartLoc = ConsumeToken();
885 BalancedDelimiterTracker T(*this, tok::l_paren);
886 if (T.expectAndConsume(diag::err_expected_lparen_after,
887 "__underlying_type", tok::r_paren)) {
891 TypeResult Result = ParseTypeName();
892 if (Result.isInvalid()) {
893 SkipUntil(tok::r_paren, StopAtSemi);
899 if (T.getCloseLocation().isInvalid())
902 const char *PrevSpec = nullptr;
904 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
905 DiagID, Result.get(),
906 Actions.getASTContext().getPrintingPolicy()))
907 Diag(StartLoc, DiagID) << PrevSpec;
908 DS.setTypeofParensRange(T.getRange());
911 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
912 /// class name or decltype-specifier. Note that we only check that the result
913 /// names a type; semantic analysis will need to verify that the type names a
914 /// class. The result is either a type or null, depending on whether a type
917 /// base-type-specifier: [C++11 class.derived]
918 /// class-or-decltype
919 /// class-or-decltype: [C++11 class.derived]
920 /// nested-name-specifier[opt] class-name
921 /// decltype-specifier
922 /// class-name: [C++ class.name]
924 /// simple-template-id
926 /// In C++98, instead of base-type-specifier, we have:
928 /// ::[opt] nested-name-specifier[opt] class-name
929 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
930 SourceLocation &EndLocation) {
931 // Ignore attempts to use typename
932 if (Tok.is(tok::kw_typename)) {
933 Diag(Tok, diag::err_expected_class_name_not_template)
934 << FixItHint::CreateRemoval(Tok.getLocation());
938 // Parse optional nested-name-specifier
940 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
942 BaseLoc = Tok.getLocation();
944 // Parse decltype-specifier
945 // tok == kw_decltype is just error recovery, it can only happen when SS
947 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
949 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
950 << FixItHint::CreateRemoval(SS.getRange());
951 // Fake up a Declarator to use with ActOnTypeName.
952 DeclSpec DS(AttrFactory);
954 EndLocation = ParseDecltypeSpecifier(DS);
956 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
957 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
960 // Check whether we have a template-id that names a type.
961 if (Tok.is(tok::annot_template_id)) {
962 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
963 if (TemplateId->Kind == TNK_Type_template ||
964 TemplateId->Kind == TNK_Dependent_template_name) {
965 AnnotateTemplateIdTokenAsType();
967 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
968 ParsedType Type = getTypeAnnotation(Tok);
969 EndLocation = Tok.getAnnotationEndLoc();
977 // Fall through to produce an error below.
980 if (Tok.isNot(tok::identifier)) {
981 Diag(Tok, diag::err_expected_class_name);
985 IdentifierInfo *Id = Tok.getIdentifierInfo();
986 SourceLocation IdLoc = ConsumeToken();
988 if (Tok.is(tok::less)) {
989 // It looks the user intended to write a template-id here, but the
990 // template-name was wrong. Try to fix that.
991 TemplateNameKind TNK = TNK_Type_template;
993 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
994 &SS, Template, TNK)) {
995 Diag(IdLoc, diag::err_unknown_template_name)
1000 TemplateArgList TemplateArgs;
1001 SourceLocation LAngleLoc, RAngleLoc;
1002 ParseTemplateIdAfterTemplateName(TemplateTy(), IdLoc, SS,
1003 true, LAngleLoc, TemplateArgs, RAngleLoc);
1007 // Form the template name
1008 UnqualifiedId TemplateName;
1009 TemplateName.setIdentifier(Id, IdLoc);
1011 // Parse the full template-id, then turn it into a type.
1012 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1013 TemplateName, true))
1015 if (TNK == TNK_Dependent_template_name)
1016 AnnotateTemplateIdTokenAsType();
1018 // If we didn't end up with a typename token, there's nothing more we
1020 if (Tok.isNot(tok::annot_typename))
1023 // Retrieve the type from the annotation token, consume that token, and
1025 EndLocation = Tok.getAnnotationEndLoc();
1026 ParsedType Type = getTypeAnnotation(Tok);
1031 // We have an identifier; check whether it is actually a type.
1032 IdentifierInfo *CorrectedII = nullptr;
1033 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
1034 false, ParsedType(),
1035 /*IsCtorOrDtorName=*/false,
1036 /*NonTrivialTypeSourceInfo=*/true,
1039 Diag(IdLoc, diag::err_expected_class_name);
1043 // Consume the identifier.
1044 EndLocation = IdLoc;
1046 // Fake up a Declarator to use with ActOnTypeName.
1047 DeclSpec DS(AttrFactory);
1048 DS.SetRangeStart(IdLoc);
1049 DS.SetRangeEnd(EndLocation);
1050 DS.getTypeSpecScope() = SS;
1052 const char *PrevSpec = nullptr;
1054 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1055 Actions.getASTContext().getPrintingPolicy());
1057 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1058 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1061 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1062 while (Tok.isOneOf(tok::kw___single_inheritance,
1063 tok::kw___multiple_inheritance,
1064 tok::kw___virtual_inheritance)) {
1065 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1066 SourceLocation AttrNameLoc = ConsumeToken();
1067 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1068 AttributeList::AS_Keyword);
1072 /// Determine whether the following tokens are valid after a type-specifier
1073 /// which could be a standalone declaration. This will conservatively return
1074 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1075 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1076 // This switch enumerates the valid "follow" set for type-specifiers.
1077 switch (Tok.getKind()) {
1079 case tok::semi: // struct foo {...} ;
1080 case tok::star: // struct foo {...} * P;
1081 case tok::amp: // struct foo {...} & R = ...
1082 case tok::ampamp: // struct foo {...} && R = ...
1083 case tok::identifier: // struct foo {...} V ;
1084 case tok::r_paren: //(struct foo {...} ) {4}
1085 case tok::annot_cxxscope: // struct foo {...} a:: b;
1086 case tok::annot_typename: // struct foo {...} a ::b;
1087 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1088 case tok::l_paren: // struct foo {...} ( x);
1089 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1090 case tok::kw_operator: // struct foo operator ++() {...}
1091 case tok::kw___declspec: // struct foo {...} __declspec(...)
1092 case tok::l_square: // void f(struct f [ 3])
1093 case tok::ellipsis: // void f(struct f ... [Ns])
1094 // FIXME: we should emit semantic diagnostic when declaration
1095 // attribute is in type attribute position.
1096 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1099 return CouldBeBitfield; // enum E { ... } : 2;
1101 case tok::kw_const: // struct foo {...} const x;
1102 case tok::kw_volatile: // struct foo {...} volatile x;
1103 case tok::kw_restrict: // struct foo {...} restrict x;
1104 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1105 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1106 // Function specifiers
1107 // Note, no 'explicit'. An explicit function must be either a conversion
1108 // operator or a constructor. Either way, it can't have a return type.
1109 case tok::kw_inline: // struct foo inline f();
1110 case tok::kw_virtual: // struct foo virtual f();
1111 case tok::kw_friend: // struct foo friend f();
1112 // Storage-class specifiers
1113 case tok::kw_static: // struct foo {...} static x;
1114 case tok::kw_extern: // struct foo {...} extern x;
1115 case tok::kw_typedef: // struct foo {...} typedef x;
1116 case tok::kw_register: // struct foo {...} register x;
1117 case tok::kw_auto: // struct foo {...} auto x;
1118 case tok::kw_mutable: // struct foo {...} mutable x;
1119 case tok::kw_thread_local: // struct foo {...} thread_local x;
1120 case tok::kw_constexpr: // struct foo {...} constexpr x;
1121 // As shown above, type qualifiers and storage class specifiers absolutely
1122 // can occur after class specifiers according to the grammar. However,
1123 // almost no one actually writes code like this. If we see one of these,
1124 // it is much more likely that someone missed a semi colon and the
1125 // type/storage class specifier we're seeing is part of the *next*
1126 // intended declaration, as in:
1128 // struct foo { ... }
1131 // We'd really like to emit a missing semicolon error instead of emitting
1132 // an error on the 'int' saying that you can't have two type specifiers in
1133 // the same declaration of X. Because of this, we look ahead past this
1134 // token to see if it's a type specifier. If so, we know the code is
1135 // otherwise invalid, so we can produce the expected semi error.
1136 if (!isKnownToBeTypeSpecifier(NextToken()))
1139 case tok::r_brace: // struct bar { struct foo {...} }
1140 // Missing ';' at end of struct is accepted as an extension in C mode.
1141 if (!getLangOpts().CPlusPlus)
1145 // template<class T = class X>
1146 return getLangOpts().CPlusPlus;
1151 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1152 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1153 /// until we reach the start of a definition or see a token that
1154 /// cannot start a definition.
1156 /// class-specifier: [C++ class]
1157 /// class-head '{' member-specification[opt] '}'
1158 /// class-head '{' member-specification[opt] '}' attributes[opt]
1160 /// class-key identifier[opt] base-clause[opt]
1161 /// class-key nested-name-specifier identifier base-clause[opt]
1162 /// class-key nested-name-specifier[opt] simple-template-id
1163 /// base-clause[opt]
1164 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1165 /// [GNU] class-key attributes[opt] nested-name-specifier
1166 /// identifier base-clause[opt]
1167 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1168 /// simple-template-id base-clause[opt]
1174 /// elaborated-type-specifier: [C++ dcl.type.elab]
1175 /// class-key ::[opt] nested-name-specifier[opt] identifier
1176 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1177 /// simple-template-id
1179 /// Note that the C++ class-specifier and elaborated-type-specifier,
1180 /// together, subsume the C99 struct-or-union-specifier:
1182 /// struct-or-union-specifier: [C99 6.7.2.1]
1183 /// struct-or-union identifier[opt] '{' struct-contents '}'
1184 /// struct-or-union identifier
1185 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1186 /// '}' attributes[opt]
1187 /// [GNU] struct-or-union attributes[opt] identifier
1188 /// struct-or-union:
1191 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1192 SourceLocation StartLoc, DeclSpec &DS,
1193 const ParsedTemplateInfo &TemplateInfo,
1195 bool EnteringContext, DeclSpecContext DSC,
1196 ParsedAttributesWithRange &Attributes) {
1197 DeclSpec::TST TagType;
1198 if (TagTokKind == tok::kw_struct)
1199 TagType = DeclSpec::TST_struct;
1200 else if (TagTokKind == tok::kw___interface)
1201 TagType = DeclSpec::TST_interface;
1202 else if (TagTokKind == tok::kw_class)
1203 TagType = DeclSpec::TST_class;
1205 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1206 TagType = DeclSpec::TST_union;
1209 if (Tok.is(tok::code_completion)) {
1210 // Code completion for a struct, class, or union name.
1211 Actions.CodeCompleteTag(getCurScope(), TagType);
1212 return cutOffParsing();
1215 // C++03 [temp.explicit] 14.7.2/8:
1216 // The usual access checking rules do not apply to names used to specify
1217 // explicit instantiations.
1219 // As an extension we do not perform access checking on the names used to
1220 // specify explicit specializations either. This is important to allow
1221 // specializing traits classes for private types.
1223 // Note that we don't suppress if this turns out to be an elaborated
1225 bool shouldDelayDiagsInTag =
1226 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1227 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1228 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1230 ParsedAttributesWithRange attrs(AttrFactory);
1231 // If attributes exist after tag, parse them.
1232 MaybeParseGNUAttributes(attrs);
1233 MaybeParseMicrosoftDeclSpecs(attrs);
1235 // Parse inheritance specifiers.
1236 if (Tok.isOneOf(tok::kw___single_inheritance,
1237 tok::kw___multiple_inheritance,
1238 tok::kw___virtual_inheritance))
1239 ParseMicrosoftInheritanceClassAttributes(attrs);
1241 // If C++0x attributes exist here, parse them.
1242 // FIXME: Are we consistent with the ordering of parsing of different
1243 // styles of attributes?
1244 MaybeParseCXX11Attributes(attrs);
1246 // Source location used by FIXIT to insert misplaced
1248 SourceLocation AttrFixitLoc = Tok.getLocation();
1250 if (TagType == DeclSpec::TST_struct &&
1251 Tok.isNot(tok::identifier) &&
1252 !Tok.isAnnotation() &&
1253 Tok.getIdentifierInfo() &&
1254 Tok.isOneOf(tok::kw___is_abstract,
1255 tok::kw___is_arithmetic,
1257 tok::kw___is_base_of,
1259 tok::kw___is_complete_type,
1260 tok::kw___is_compound,
1262 tok::kw___is_constructible,
1263 tok::kw___is_convertible,
1264 tok::kw___is_convertible_to,
1265 tok::kw___is_destructible,
1268 tok::kw___is_floating_point,
1270 tok::kw___is_function,
1271 tok::kw___is_fundamental,
1272 tok::kw___is_integral,
1273 tok::kw___is_interface_class,
1274 tok::kw___is_literal,
1275 tok::kw___is_lvalue_expr,
1276 tok::kw___is_lvalue_reference,
1277 tok::kw___is_member_function_pointer,
1278 tok::kw___is_member_object_pointer,
1279 tok::kw___is_member_pointer,
1280 tok::kw___is_nothrow_assignable,
1281 tok::kw___is_nothrow_constructible,
1282 tok::kw___is_nothrow_destructible,
1283 tok::kw___is_object,
1285 tok::kw___is_pointer,
1286 tok::kw___is_polymorphic,
1287 tok::kw___is_reference,
1288 tok::kw___is_rvalue_expr,
1289 tok::kw___is_rvalue_reference,
1291 tok::kw___is_scalar,
1292 tok::kw___is_sealed,
1293 tok::kw___is_signed,
1294 tok::kw___is_standard_layout,
1295 tok::kw___is_trivial,
1296 tok::kw___is_trivially_assignable,
1297 tok::kw___is_trivially_constructible,
1298 tok::kw___is_trivially_copyable,
1300 tok::kw___is_unsigned,
1302 tok::kw___is_volatile))
1303 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1304 // name of struct templates, but some are keywords in GCC >= 4.3
1305 // and Clang. Therefore, when we see the token sequence "struct
1306 // X", make X into a normal identifier rather than a keyword, to
1307 // allow libstdc++ 4.2 and libc++ to work properly.
1308 TryKeywordIdentFallback(true);
1310 // Parse the (optional) nested-name-specifier.
1311 CXXScopeSpec &SS = DS.getTypeSpecScope();
1312 if (getLangOpts().CPlusPlus) {
1313 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1314 // is a base-specifier-list.
1315 ColonProtectionRAIIObject X(*this);
1318 bool HasValidSpec = true;
1319 if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(), EnteringContext)) {
1320 DS.SetTypeSpecError();
1321 HasValidSpec = false;
1324 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1325 Diag(Tok, diag::err_expected) << tok::identifier;
1326 HasValidSpec = false;
1332 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1334 // Parse the (optional) class name or simple-template-id.
1335 IdentifierInfo *Name = nullptr;
1336 SourceLocation NameLoc;
1337 TemplateIdAnnotation *TemplateId = nullptr;
1338 if (Tok.is(tok::identifier)) {
1339 Name = Tok.getIdentifierInfo();
1340 NameLoc = ConsumeToken();
1342 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1343 // The name was supposed to refer to a template, but didn't.
1344 // Eat the template argument list and try to continue parsing this as
1345 // a class (or template thereof).
1346 TemplateArgList TemplateArgs;
1347 SourceLocation LAngleLoc, RAngleLoc;
1348 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1350 TemplateArgs, RAngleLoc)) {
1351 // We couldn't parse the template argument list at all, so don't
1352 // try to give any location information for the list.
1353 LAngleLoc = RAngleLoc = SourceLocation();
1356 Diag(NameLoc, diag::err_explicit_spec_non_template)
1357 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1358 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1360 // Strip off the last template parameter list if it was empty, since
1361 // we've removed its template argument list.
1362 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1363 if (TemplateParams && TemplateParams->size() > 1) {
1364 TemplateParams->pop_back();
1366 TemplateParams = nullptr;
1367 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1368 = ParsedTemplateInfo::NonTemplate;
1370 } else if (TemplateInfo.Kind
1371 == ParsedTemplateInfo::ExplicitInstantiation) {
1372 // Pretend this is just a forward declaration.
1373 TemplateParams = nullptr;
1374 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1375 = ParsedTemplateInfo::NonTemplate;
1376 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1378 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1382 } else if (Tok.is(tok::annot_template_id)) {
1383 TemplateId = takeTemplateIdAnnotation(Tok);
1384 NameLoc = ConsumeToken();
1386 if (TemplateId->Kind != TNK_Type_template &&
1387 TemplateId->Kind != TNK_Dependent_template_name) {
1388 // The template-name in the simple-template-id refers to
1389 // something other than a class template. Give an appropriate
1390 // error message and skip to the ';'.
1391 SourceRange Range(NameLoc);
1392 if (SS.isNotEmpty())
1393 Range.setBegin(SS.getBeginLoc());
1395 // FIXME: Name may be null here.
1396 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1397 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1399 DS.SetTypeSpecError();
1400 SkipUntil(tok::semi, StopBeforeMatch);
1405 // There are four options here.
1406 // - If we are in a trailing return type, this is always just a reference,
1407 // and we must not try to parse a definition. For instance,
1408 // [] () -> struct S { };
1409 // does not define a type.
1410 // - If we have 'struct foo {...', 'struct foo :...',
1411 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1412 // - If we have 'struct foo;', then this is either a forward declaration
1413 // or a friend declaration, which have to be treated differently.
1414 // - Otherwise we have something like 'struct foo xyz', a reference.
1416 // We also detect these erroneous cases to provide better diagnostic for
1417 // C++11 attributes parsing.
1418 // - attributes follow class name:
1419 // struct foo [[]] {};
1420 // - attributes appear before or after 'final':
1421 // struct foo [[]] final [[]] {};
1423 // However, in type-specifier-seq's, things look like declarations but are
1424 // just references, e.g.
1427 // &T::operator struct s;
1428 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
1430 // If there are attributes after class name, parse them.
1431 MaybeParseCXX11Attributes(Attributes);
1433 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1434 Sema::TagUseKind TUK;
1435 if (DSC == DSC_trailing)
1436 TUK = Sema::TUK_Reference;
1437 else if (Tok.is(tok::l_brace) ||
1438 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1439 (isCXX11FinalKeyword() &&
1440 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1441 if (DS.isFriendSpecified()) {
1442 // C++ [class.friend]p2:
1443 // A class shall not be defined in a friend declaration.
1444 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1445 << SourceRange(DS.getFriendSpecLoc());
1447 // Skip everything up to the semicolon, so that this looks like a proper
1448 // friend class (or template thereof) declaration.
1449 SkipUntil(tok::semi, StopBeforeMatch);
1450 TUK = Sema::TUK_Friend;
1452 // Okay, this is a class definition.
1453 TUK = Sema::TUK_Definition;
1455 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1456 NextToken().is(tok::kw_alignas))) {
1457 // We can't tell if this is a definition or reference
1458 // until we skipped the 'final' and C++11 attribute specifiers.
1459 TentativeParsingAction PA(*this);
1461 // Skip the 'final' keyword.
1464 // Skip C++11 attribute specifiers.
1466 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1468 if (!SkipUntil(tok::r_square, StopAtSemi))
1470 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1473 if (!SkipUntil(tok::r_paren, StopAtSemi))
1480 if (Tok.isOneOf(tok::l_brace, tok::colon))
1481 TUK = Sema::TUK_Definition;
1483 TUK = Sema::TUK_Reference;
1486 } else if (!isTypeSpecifier(DSC) &&
1487 (Tok.is(tok::semi) ||
1488 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1489 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1490 if (Tok.isNot(tok::semi)) {
1491 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1492 // A semicolon was missing after this declaration. Diagnose and recover.
1493 ExpectAndConsume(tok::semi, diag::err_expected_after,
1494 DeclSpec::getSpecifierName(TagType, PPol));
1496 Tok.setKind(tok::semi);
1499 TUK = Sema::TUK_Reference;
1501 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1502 // to caller to handle.
1503 if (TUK != Sema::TUK_Reference) {
1504 // If this is not a reference, then the only possible
1505 // valid place for C++11 attributes to appear here
1506 // is between class-key and class-name. If there are
1507 // any attributes after class-name, we try a fixit to move
1508 // them to the right place.
1509 SourceRange AttrRange = Attributes.Range;
1510 if (AttrRange.isValid()) {
1511 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1513 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1514 CharSourceRange(AttrRange, true))
1515 << FixItHint::CreateRemoval(AttrRange);
1517 // Recover by adding misplaced attributes to the attribute list
1518 // of the class so they can be applied on the class later.
1519 attrs.takeAllFrom(Attributes);
1523 // If this is an elaborated type specifier, and we delayed
1524 // diagnostics before, just merge them into the current pool.
1525 if (shouldDelayDiagsInTag) {
1526 diagsFromTag.done();
1527 if (TUK == Sema::TUK_Reference)
1528 diagsFromTag.redelay();
1531 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1532 TUK != Sema::TUK_Definition)) {
1533 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1534 // We have a declaration or reference to an anonymous class.
1535 Diag(StartLoc, diag::err_anon_type_definition)
1536 << DeclSpec::getSpecifierName(TagType, Policy);
1539 // If we are parsing a definition and stop at a base-clause, continue on
1540 // until the semicolon. Continuing from the comma will just trick us into
1541 // thinking we are seeing a variable declaration.
1542 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1543 SkipUntil(tok::semi, StopBeforeMatch);
1545 SkipUntil(tok::comma, StopAtSemi);
1549 // Create the tag portion of the class or class template.
1550 DeclResult TagOrTempResult = true; // invalid
1551 TypeResult TypeResult = true; // invalid
1554 Sema::SkipBodyInfo SkipBody;
1556 // Explicit specialization, class template partial specialization,
1557 // or explicit instantiation.
1558 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1559 TemplateId->NumArgs);
1560 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1561 TUK == Sema::TUK_Declaration) {
1562 // This is an explicit instantiation of a class template.
1563 ProhibitAttributes(attrs);
1566 = Actions.ActOnExplicitInstantiation(getCurScope(),
1567 TemplateInfo.ExternLoc,
1568 TemplateInfo.TemplateLoc,
1572 TemplateId->Template,
1573 TemplateId->TemplateNameLoc,
1574 TemplateId->LAngleLoc,
1576 TemplateId->RAngleLoc,
1579 // Friend template-ids are treated as references unless
1580 // they have template headers, in which case they're ill-formed
1581 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1582 // We diagnose this error in ActOnClassTemplateSpecialization.
1583 } else if (TUK == Sema::TUK_Reference ||
1584 (TUK == Sema::TUK_Friend &&
1585 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1586 ProhibitAttributes(attrs);
1587 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1589 TemplateId->TemplateKWLoc,
1590 TemplateId->Template,
1591 TemplateId->TemplateNameLoc,
1592 TemplateId->LAngleLoc,
1594 TemplateId->RAngleLoc);
1596 // This is an explicit specialization or a class template
1597 // partial specialization.
1598 TemplateParameterLists FakedParamLists;
1599 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1600 // This looks like an explicit instantiation, because we have
1603 // template class Foo<X>
1605 // but it actually has a definition. Most likely, this was
1606 // meant to be an explicit specialization, but the user forgot
1607 // the '<>' after 'template'.
1608 // It this is friend declaration however, since it cannot have a
1609 // template header, it is most likely that the user meant to
1610 // remove the 'template' keyword.
1611 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1612 "Expected a definition here");
1614 if (TUK == Sema::TUK_Friend) {
1615 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1616 TemplateParams = nullptr;
1618 SourceLocation LAngleLoc =
1619 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1620 Diag(TemplateId->TemplateNameLoc,
1621 diag::err_explicit_instantiation_with_definition)
1622 << SourceRange(TemplateInfo.TemplateLoc)
1623 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1625 // Create a fake template parameter list that contains only
1626 // "template<>", so that we treat this construct as a class
1627 // template specialization.
1628 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1629 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
1631 TemplateParams = &FakedParamLists;
1635 // Build the class template specialization.
1636 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1637 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1638 *TemplateId, attrs.getList(),
1639 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1641 TemplateParams ? TemplateParams->size() : 0),
1644 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1645 TUK == Sema::TUK_Declaration) {
1646 // Explicit instantiation of a member of a class template
1647 // specialization, e.g.,
1649 // template struct Outer<int>::Inner;
1651 ProhibitAttributes(attrs);
1654 = Actions.ActOnExplicitInstantiation(getCurScope(),
1655 TemplateInfo.ExternLoc,
1656 TemplateInfo.TemplateLoc,
1657 TagType, StartLoc, SS, Name,
1658 NameLoc, attrs.getList());
1659 } else if (TUK == Sema::TUK_Friend &&
1660 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1661 ProhibitAttributes(attrs);
1664 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1665 TagType, StartLoc, SS,
1666 Name, NameLoc, attrs.getList(),
1667 MultiTemplateParamsArg(
1668 TemplateParams? &(*TemplateParams)[0]
1670 TemplateParams? TemplateParams->size() : 0));
1672 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1673 ProhibitAttributes(attrs);
1675 if (TUK == Sema::TUK_Definition &&
1676 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1677 // If the declarator-id is not a template-id, issue a diagnostic and
1678 // recover by ignoring the 'template' keyword.
1679 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1680 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1681 TemplateParams = nullptr;
1684 bool IsDependent = false;
1686 // Don't pass down template parameter lists if this is just a tag
1687 // reference. For example, we don't need the template parameters here:
1688 // template <class T> class A *makeA(T t);
1689 MultiTemplateParamsArg TParams;
1690 if (TUK != Sema::TUK_Reference && TemplateParams)
1692 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1694 handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
1696 // Declaration or definition of a class type
1697 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1698 SS, Name, NameLoc, attrs.getList(), AS,
1699 DS.getModulePrivateSpecLoc(),
1700 TParams, Owned, IsDependent,
1701 SourceLocation(), false,
1702 clang::TypeResult(),
1703 DSC == DSC_type_specifier,
1706 // If ActOnTag said the type was dependent, try again with the
1707 // less common call.
1709 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1710 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1711 SS, Name, StartLoc, NameLoc);
1715 // If there is a body, parse it and inform the actions module.
1716 if (TUK == Sema::TUK_Definition) {
1717 assert(Tok.is(tok::l_brace) ||
1718 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1719 isCXX11FinalKeyword());
1720 if (SkipBody.ShouldSkip)
1721 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1722 TagOrTempResult.get());
1723 else if (getLangOpts().CPlusPlus)
1724 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1725 TagOrTempResult.get());
1727 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1730 const char *PrevSpec = nullptr;
1733 if (!TypeResult.isInvalid()) {
1734 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1735 NameLoc.isValid() ? NameLoc : StartLoc,
1736 PrevSpec, DiagID, TypeResult.get(), Policy);
1737 } else if (!TagOrTempResult.isInvalid()) {
1738 Result = DS.SetTypeSpecType(TagType, StartLoc,
1739 NameLoc.isValid() ? NameLoc : StartLoc,
1740 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1743 DS.SetTypeSpecError();
1748 Diag(StartLoc, DiagID) << PrevSpec;
1750 // At this point, we've successfully parsed a class-specifier in 'definition'
1751 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1752 // going to look at what comes after it to improve error recovery. If an
1753 // impossible token occurs next, we assume that the programmer forgot a ; at
1754 // the end of the declaration and recover that way.
1756 // Also enforce C++ [temp]p3:
1757 // In a template-declaration which defines a class, no declarator
1760 // After a type-specifier, we don't expect a semicolon. This only happens in
1761 // C, since definitions are not permitted in this context in C++.
1762 if (TUK == Sema::TUK_Definition &&
1763 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1764 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1765 if (Tok.isNot(tok::semi)) {
1766 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1767 ExpectAndConsume(tok::semi, diag::err_expected_after,
1768 DeclSpec::getSpecifierName(TagType, PPol));
1769 // Push this token back into the preprocessor and change our current token
1770 // to ';' so that the rest of the code recovers as though there were an
1771 // ';' after the definition.
1773 Tok.setKind(tok::semi);
1778 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1780 /// base-clause : [C++ class.derived]
1781 /// ':' base-specifier-list
1782 /// base-specifier-list:
1783 /// base-specifier '...'[opt]
1784 /// base-specifier-list ',' base-specifier '...'[opt]
1785 void Parser::ParseBaseClause(Decl *ClassDecl) {
1786 assert(Tok.is(tok::colon) && "Not a base clause");
1789 // Build up an array of parsed base specifiers.
1790 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1793 // Parse a base-specifier.
1794 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1795 if (Result.isInvalid()) {
1796 // Skip the rest of this base specifier, up until the comma or
1798 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
1800 // Add this to our array of base specifiers.
1801 BaseInfo.push_back(Result.get());
1804 // If the next token is a comma, consume it and keep reading
1806 if (!TryConsumeToken(tok::comma))
1810 // Attach the base specifiers
1811 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1814 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1815 /// one entry in the base class list of a class specifier, for example:
1816 /// class foo : public bar, virtual private baz {
1817 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1819 /// base-specifier: [C++ class.derived]
1820 /// attribute-specifier-seq[opt] base-type-specifier
1821 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
1822 /// base-type-specifier
1823 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
1824 /// base-type-specifier
1825 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1826 bool IsVirtual = false;
1827 SourceLocation StartLoc = Tok.getLocation();
1829 ParsedAttributesWithRange Attributes(AttrFactory);
1830 MaybeParseCXX11Attributes(Attributes);
1832 // Parse the 'virtual' keyword.
1833 if (TryConsumeToken(tok::kw_virtual))
1836 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1838 // Parse an (optional) access specifier.
1839 AccessSpecifier Access = getAccessSpecifierIfPresent();
1840 if (Access != AS_none)
1843 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1845 // Parse the 'virtual' keyword (again!), in case it came after the
1846 // access specifier.
1847 if (Tok.is(tok::kw_virtual)) {
1848 SourceLocation VirtualLoc = ConsumeToken();
1850 // Complain about duplicate 'virtual'
1851 Diag(VirtualLoc, diag::err_dup_virtual)
1852 << FixItHint::CreateRemoval(VirtualLoc);
1858 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1860 // Parse the class-name.
1861 SourceLocation EndLocation;
1862 SourceLocation BaseLoc;
1863 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1864 if (BaseType.isInvalid())
1867 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1868 // actually part of the base-specifier-list grammar productions, but we
1869 // parse it here for convenience.
1870 SourceLocation EllipsisLoc;
1871 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1873 // Find the complete source range for the base-specifier.
1874 SourceRange Range(StartLoc, EndLocation);
1876 // Notify semantic analysis that we have parsed a complete
1878 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
1879 Access, BaseType.get(), BaseLoc,
1883 /// getAccessSpecifierIfPresent - Determine whether the next token is
1884 /// a C++ access-specifier.
1886 /// access-specifier: [C++ class.derived]
1890 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1891 switch (Tok.getKind()) {
1892 default: return AS_none;
1893 case tok::kw_private: return AS_private;
1894 case tok::kw_protected: return AS_protected;
1895 case tok::kw_public: return AS_public;
1899 /// \brief If the given declarator has any parts for which parsing has to be
1900 /// delayed, e.g., default arguments or an exception-specification, create a
1901 /// late-parsed method declaration record to handle the parsing at the end of
1902 /// the class definition.
1903 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1905 DeclaratorChunk::FunctionTypeInfo &FTI
1906 = DeclaratorInfo.getFunctionTypeInfo();
1907 // If there was a late-parsed exception-specification, we'll need a
1909 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
1911 if (!NeedLateParse) {
1912 // Look ahead to see if there are any default args
1913 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
1914 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
1915 if (Param->hasUnparsedDefaultArg()) {
1916 NeedLateParse = true;
1922 if (NeedLateParse) {
1923 // Push this method onto the stack of late-parsed method
1925 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1926 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1927 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1929 // Stash the exception-specification tokens in the late-pased method.
1930 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
1931 FTI.ExceptionSpecTokens = 0;
1933 // Push tokens for each parameter. Those that do not have
1934 // defaults will be NULL.
1935 LateMethod->DefaultArgs.reserve(FTI.NumParams);
1936 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
1937 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
1938 FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
1942 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
1948 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
1949 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
1950 return VirtSpecifiers::VS_None;
1952 IdentifierInfo *II = Tok.getIdentifierInfo();
1954 // Initialize the contextual keywords.
1956 Ident_final = &PP.getIdentifierTable().get("final");
1957 if (getLangOpts().MicrosoftExt)
1958 Ident_sealed = &PP.getIdentifierTable().get("sealed");
1959 Ident_override = &PP.getIdentifierTable().get("override");
1962 if (II == Ident_override)
1963 return VirtSpecifiers::VS_Override;
1965 if (II == Ident_sealed)
1966 return VirtSpecifiers::VS_Sealed;
1968 if (II == Ident_final)
1969 return VirtSpecifiers::VS_Final;
1971 return VirtSpecifiers::VS_None;
1974 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
1976 /// virt-specifier-seq:
1978 /// virt-specifier-seq virt-specifier
1979 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
1981 SourceLocation FriendLoc) {
1983 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
1984 if (Specifier == VirtSpecifiers::VS_None)
1987 if (FriendLoc.isValid()) {
1988 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
1989 << VirtSpecifiers::getSpecifierName(Specifier)
1990 << FixItHint::CreateRemoval(Tok.getLocation())
1991 << SourceRange(FriendLoc, FriendLoc);
1996 // C++ [class.mem]p8:
1997 // A virt-specifier-seq shall contain at most one of each virt-specifier.
1998 const char *PrevSpec = nullptr;
1999 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2000 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2002 << FixItHint::CreateRemoval(Tok.getLocation());
2004 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2005 Specifier == VirtSpecifiers::VS_Sealed)) {
2006 Diag(Tok.getLocation(), diag::err_override_control_interface)
2007 << VirtSpecifiers::getSpecifierName(Specifier);
2008 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2009 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2011 Diag(Tok.getLocation(),
2012 getLangOpts().CPlusPlus11
2013 ? diag::warn_cxx98_compat_override_control_keyword
2014 : diag::ext_override_control_keyword)
2015 << VirtSpecifiers::getSpecifierName(Specifier);
2021 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2022 /// 'final' or Microsoft 'sealed' contextual keyword.
2023 bool Parser::isCXX11FinalKeyword() const {
2024 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2025 return Specifier == VirtSpecifiers::VS_Final ||
2026 Specifier == VirtSpecifiers::VS_Sealed;
2029 /// \brief Parse a C++ member-declarator up to, but not including, the optional
2030 /// brace-or-equal-initializer or pure-specifier.
2031 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2032 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2033 LateParsedAttrList &LateParsedAttrs) {
2034 // member-declarator:
2035 // declarator pure-specifier[opt]
2036 // declarator brace-or-equal-initializer[opt]
2037 // identifier[opt] ':' constant-expression
2038 if (Tok.isNot(tok::colon))
2039 ParseDeclarator(DeclaratorInfo);
2041 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2043 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2044 assert(DeclaratorInfo.isPastIdentifier() &&
2045 "don't know where identifier would go yet?");
2046 BitfieldSize = ParseConstantExpression();
2047 if (BitfieldSize.isInvalid())
2048 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2050 ParseOptionalCXX11VirtSpecifierSeq(
2051 VS, getCurrentClass().IsInterface,
2052 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2054 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2057 // If a simple-asm-expr is present, parse it.
2058 if (Tok.is(tok::kw_asm)) {
2060 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2061 if (AsmLabel.isInvalid())
2062 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2064 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2065 DeclaratorInfo.SetRangeEnd(Loc);
2068 // If attributes exist after the declarator, but before an '{', parse them.
2069 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2071 // For compatibility with code written to older Clang, also accept a
2072 // virt-specifier *after* the GNU attributes.
2073 if (BitfieldSize.isUnset() && VS.isUnset()) {
2074 ParseOptionalCXX11VirtSpecifierSeq(
2075 VS, getCurrentClass().IsInterface,
2076 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2077 if (!VS.isUnset()) {
2078 // If we saw any GNU-style attributes that are known to GCC followed by a
2079 // virt-specifier, issue a GCC-compat warning.
2080 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2082 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2083 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2084 Attr = Attr->getNext();
2086 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2090 // If this has neither a name nor a bit width, something has gone seriously
2091 // wrong. Skip until the semi-colon or }.
2092 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2093 // If so, skip until the semi-colon or a }.
2094 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2100 /// \brief Look for declaration specifiers possibly occurring after C++11
2101 /// virt-specifier-seq and diagnose them.
2102 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2104 VirtSpecifiers &VS) {
2105 DeclSpec DS(AttrFactory);
2107 // GNU-style and C++11 attributes are not allowed here, but they will be
2108 // handled by the caller. Diagnose everything else.
2109 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, false);
2110 D.ExtendWithDeclSpec(DS);
2112 if (D.isFunctionDeclarator()) {
2113 auto &Function = D.getFunctionTypeInfo();
2114 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2115 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2116 const char *FixItName,
2117 SourceLocation SpecLoc,
2118 unsigned* QualifierLoc) {
2119 FixItHint Insertion;
2120 if (DS.getTypeQualifiers() & TypeQual) {
2121 if (!(Function.TypeQuals & TypeQual)) {
2122 std::string Name(FixItName);
2124 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name.c_str());
2125 Function.TypeQuals |= TypeQual;
2126 *QualifierLoc = SpecLoc.getRawEncoding();
2128 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2130 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2131 << FixItHint::CreateRemoval(SpecLoc)
2135 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2136 &Function.ConstQualifierLoc);
2137 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2138 &Function.VolatileQualifierLoc);
2139 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2140 &Function.RestrictQualifierLoc);
2143 // Parse ref-qualifiers.
2144 bool RefQualifierIsLValueRef = true;
2145 SourceLocation RefQualifierLoc;
2146 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2147 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2148 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2149 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2150 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2152 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2153 << (RefQualifierIsLValueRef ? "&" : "&&")
2154 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2155 << FixItHint::CreateRemoval(RefQualifierLoc)
2157 D.SetRangeEnd(RefQualifierLoc);
2162 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2164 /// member-declaration:
2165 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2166 /// function-definition ';'[opt]
2167 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2168 /// using-declaration [TODO]
2169 /// [C++0x] static_assert-declaration
2170 /// template-declaration
2171 /// [GNU] '__extension__' member-declaration
2173 /// member-declarator-list:
2174 /// member-declarator
2175 /// member-declarator-list ',' member-declarator
2177 /// member-declarator:
2178 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2179 /// declarator constant-initializer[opt]
2180 /// [C++11] declarator brace-or-equal-initializer[opt]
2181 /// identifier[opt] ':' constant-expression
2183 /// virt-specifier-seq:
2185 /// virt-specifier-seq virt-specifier
2195 /// constant-initializer:
2196 /// '=' constant-expression
2198 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2199 AttributeList *AccessAttrs,
2200 const ParsedTemplateInfo &TemplateInfo,
2201 ParsingDeclRAIIObject *TemplateDiags) {
2202 if (Tok.is(tok::at)) {
2203 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2204 Diag(Tok, diag::err_at_defs_cxx);
2206 Diag(Tok, diag::err_at_in_class);
2209 SkipUntil(tok::r_brace, StopAtSemi);
2213 // Turn on colon protection early, while parsing declspec, although there is
2214 // nothing to protect there. It prevents from false errors if error recovery
2215 // incorrectly determines where the declspec ends, as in the example:
2216 // struct A { enum class B { C }; };
2218 // struct D { A::B : C; };
2219 ColonProtectionRAIIObject X(*this);
2221 // Access declarations.
2222 bool MalformedTypeSpec = false;
2223 if (!TemplateInfo.Kind &&
2224 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2225 if (TryAnnotateCXXScopeToken())
2226 MalformedTypeSpec = true;
2229 if (Tok.isNot(tok::annot_cxxscope))
2230 isAccessDecl = false;
2231 else if (NextToken().is(tok::identifier))
2232 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2234 isAccessDecl = NextToken().is(tok::kw_operator);
2237 // Collect the scope specifier token we annotated earlier.
2239 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
2240 /*EnteringContext=*/false);
2242 if (SS.isInvalid()) {
2243 SkipUntil(tok::semi);
2247 // Try to parse an unqualified-id.
2248 SourceLocation TemplateKWLoc;
2250 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
2251 TemplateKWLoc, Name)) {
2252 SkipUntil(tok::semi);
2256 // TODO: recover from mistakenly-qualified operator declarations.
2257 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2258 "access declaration")) {
2259 SkipUntil(tok::semi);
2263 Actions.ActOnUsingDeclaration(getCurScope(), AS,
2264 /* HasUsingKeyword */ false,
2267 /* AttrList */ nullptr,
2268 /* HasTypenameKeyword */ false,
2274 // static_assert-declaration. A templated static_assert declaration is
2275 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2276 if (!TemplateInfo.Kind &&
2277 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2278 SourceLocation DeclEnd;
2279 ParseStaticAssertDeclaration(DeclEnd);
2283 if (Tok.is(tok::kw_template)) {
2284 assert(!TemplateInfo.TemplateParams &&
2285 "Nested template improperly parsed?");
2286 SourceLocation DeclEnd;
2287 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
2292 // Handle: member-declaration ::= '__extension__' member-declaration
2293 if (Tok.is(tok::kw___extension__)) {
2294 // __extension__ silences extension warnings in the subexpression.
2295 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2297 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2298 TemplateInfo, TemplateDiags);
2301 ParsedAttributesWithRange attrs(AttrFactory);
2302 ParsedAttributesWithRange FnAttrs(AttrFactory);
2303 // Optional C++11 attribute-specifier
2304 MaybeParseCXX11Attributes(attrs);
2305 // We need to keep these attributes for future diagnostic
2306 // before they are taken over by declaration specifier.
2307 FnAttrs.addAll(attrs.getList());
2308 FnAttrs.Range = attrs.Range;
2310 MaybeParseMicrosoftAttributes(attrs);
2312 if (Tok.is(tok::kw_using)) {
2313 ProhibitAttributes(attrs);
2316 SourceLocation UsingLoc = ConsumeToken();
2318 if (Tok.is(tok::kw_namespace)) {
2319 Diag(UsingLoc, diag::err_using_namespace_in_class);
2320 SkipUntil(tok::semi, StopBeforeMatch);
2322 SourceLocation DeclEnd;
2323 // Otherwise, it must be a using-declaration or an alias-declaration.
2324 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2325 UsingLoc, DeclEnd, AS);
2330 // Hold late-parsed attributes so we can attach a Decl to them later.
2331 LateParsedAttrList CommonLateParsedAttrs;
2333 // decl-specifier-seq:
2334 // Parse the common declaration-specifiers piece.
2335 ParsingDeclSpec DS(*this, TemplateDiags);
2336 DS.takeAttributesFrom(attrs);
2337 if (MalformedTypeSpec)
2338 DS.SetTypeSpecError();
2340 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2341 &CommonLateParsedAttrs);
2343 // Turn off colon protection that was set for declspec.
2346 // If we had a free-standing type definition with a missing semicolon, we
2347 // may get this far before the problem becomes obvious.
2348 if (DS.hasTagDefinition() &&
2349 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2350 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2351 &CommonLateParsedAttrs))
2354 MultiTemplateParamsArg TemplateParams(
2355 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2357 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2359 if (TryConsumeToken(tok::semi)) {
2360 if (DS.isFriendSpecified())
2361 ProhibitAttributes(FnAttrs);
2364 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
2365 DS.complete(TheDecl);
2369 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2372 // Hold late-parsed attributes so we can attach a Decl to them later.
2373 LateParsedAttrList LateParsedAttrs;
2375 SourceLocation EqualLoc;
2376 SourceLocation PureSpecLoc;
2378 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2379 if (Tok.isNot(tok::equal))
2382 auto &Zero = NextToken();
2383 SmallString<8> Buffer;
2384 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2385 PP.getSpelling(Zero, Buffer) != "0")
2388 auto &After = GetLookAheadToken(2);
2389 if (!After.isOneOf(tok::semi, tok::comma) &&
2390 !(AllowDefinition &&
2391 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2394 EqualLoc = ConsumeToken();
2395 PureSpecLoc = ConsumeToken();
2399 SmallVector<Decl *, 8> DeclsInGroup;
2400 ExprResult BitfieldSize;
2401 bool ExpectSemi = true;
2403 // Parse the first declarator.
2404 if (ParseCXXMemberDeclaratorBeforeInitializer(
2405 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2406 TryConsumeToken(tok::semi);
2410 // Check for a member function definition.
2411 if (BitfieldSize.isUnset()) {
2412 // MSVC permits pure specifier on inline functions defined at class scope.
2413 // Hence check for =0 before checking for function definition.
2414 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2415 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2417 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2418 // function-definition:
2420 // In C++11, a non-function declarator followed by an open brace is a
2421 // braced-init-list for an in-class member initialization, not an
2422 // erroneous function definition.
2423 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2424 DefinitionKind = FDK_Definition;
2425 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2426 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2427 DefinitionKind = FDK_Definition;
2428 } else if (Tok.is(tok::equal)) {
2429 const Token &KW = NextToken();
2430 if (KW.is(tok::kw_default))
2431 DefinitionKind = FDK_Defaulted;
2432 else if (KW.is(tok::kw_delete))
2433 DefinitionKind = FDK_Deleted;
2436 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2438 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2439 // to a friend declaration, that declaration shall be a definition.
2440 if (DeclaratorInfo.isFunctionDeclarator() &&
2441 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2442 // Diagnose attributes that appear before decl specifier:
2443 // [[]] friend int foo();
2444 ProhibitAttributes(FnAttrs);
2447 if (DefinitionKind != FDK_Declaration) {
2448 if (!DeclaratorInfo.isFunctionDeclarator()) {
2449 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2451 SkipUntil(tok::r_brace);
2453 // Consume the optional ';'
2454 TryConsumeToken(tok::semi);
2459 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2460 Diag(DeclaratorInfo.getIdentifierLoc(),
2461 diag::err_function_declared_typedef);
2463 // Recover by treating the 'typedef' as spurious.
2464 DS.ClearStorageClassSpecs();
2468 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2472 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2473 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2475 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2476 LateParsedAttrs[i]->addDecl(FunDecl);
2479 LateParsedAttrs.clear();
2481 // Consume the ';' - it's optional unless we have a delete or default
2482 if (Tok.is(tok::semi))
2483 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2489 // member-declarator-list:
2490 // member-declarator
2491 // member-declarator-list ',' member-declarator
2494 InClassInitStyle HasInClassInit = ICIS_NoInit;
2495 bool HasStaticInitializer = false;
2496 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2497 if (BitfieldSize.get()) {
2498 Diag(Tok, diag::err_bitfield_member_init);
2499 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2500 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2501 // It's a pure-specifier.
2502 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2503 // Parse it as an expression so that Sema can diagnose it.
2504 HasStaticInitializer = true;
2505 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2506 DeclSpec::SCS_static &&
2507 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2508 DeclSpec::SCS_typedef &&
2509 !DS.isFriendSpecified()) {
2510 // It's a default member initializer.
2511 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2513 HasStaticInitializer = true;
2517 // NOTE: If Sema is the Action module and declarator is an instance field,
2518 // this call will *not* return the created decl; It will return null.
2519 // See Sema::ActOnCXXMemberDeclarator for details.
2521 NamedDecl *ThisDecl = nullptr;
2522 if (DS.isFriendSpecified()) {
2523 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2524 // to a friend declaration, that declaration shall be a definition.
2526 // Diagnose attributes that appear in a friend member function declarator:
2527 // friend int foo [[]] ();
2528 SmallVector<SourceRange, 4> Ranges;
2529 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2530 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2531 E = Ranges.end(); I != E; ++I)
2532 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2534 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2537 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2541 VS, HasInClassInit);
2543 if (VarTemplateDecl *VT =
2544 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2545 // Re-direct this decl to refer to the templated decl so that we can
2547 ThisDecl = VT->getTemplatedDecl();
2549 if (ThisDecl && AccessAttrs)
2550 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2553 // Error recovery might have converted a non-static member into a static
2555 if (HasInClassInit != ICIS_NoInit &&
2556 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2557 DeclSpec::SCS_static) {
2558 HasInClassInit = ICIS_NoInit;
2559 HasStaticInitializer = true;
2562 if (ThisDecl && PureSpecLoc.isValid())
2563 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2565 // Handle the initializer.
2566 if (HasInClassInit != ICIS_NoInit) {
2567 // The initializer was deferred; parse it and cache the tokens.
2568 Diag(Tok, getLangOpts().CPlusPlus11
2569 ? diag::warn_cxx98_compat_nonstatic_member_init
2570 : diag::ext_nonstatic_member_init);
2572 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2573 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2574 // declarator is followed by an initializer.
2576 // A brace-or-equal-initializer for a member-declarator is not an
2577 // initializer in the grammar, so this is ill-formed.
2578 Diag(Tok, diag::err_incomplete_array_member_init);
2579 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2581 // Avoid later warnings about a class member of incomplete type.
2583 ThisDecl->setInvalidDecl();
2585 ParseCXXNonStaticMemberInitializer(ThisDecl);
2586 } else if (HasStaticInitializer) {
2587 // Normal initializer.
2588 ExprResult Init = ParseCXXMemberInitializer(
2589 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2591 if (Init.isInvalid())
2592 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2594 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2595 DS.containsPlaceholderType());
2596 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2598 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
2601 if (!ThisDecl->isInvalidDecl()) {
2602 // Set the Decl for any late parsed attributes
2603 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2604 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2606 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2607 LateParsedAttrs[i]->addDecl(ThisDecl);
2609 Actions.FinalizeDeclaration(ThisDecl);
2610 DeclsInGroup.push_back(ThisDecl);
2612 if (DeclaratorInfo.isFunctionDeclarator() &&
2613 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2614 DeclSpec::SCS_typedef)
2615 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2617 LateParsedAttrs.clear();
2619 DeclaratorInfo.complete(ThisDecl);
2621 // If we don't have a comma, it is either the end of the list (a ';')
2622 // or an error, bail out.
2623 SourceLocation CommaLoc;
2624 if (!TryConsumeToken(tok::comma, CommaLoc))
2627 if (Tok.isAtStartOfLine() &&
2628 !MightBeDeclarator(Declarator::MemberContext)) {
2629 // This comma was followed by a line-break and something which can't be
2630 // the start of a declarator. The comma was probably a typo for a
2632 Diag(CommaLoc, diag::err_expected_semi_declaration)
2633 << FixItHint::CreateReplacement(CommaLoc, ";");
2638 // Parse the next declarator.
2639 DeclaratorInfo.clear();
2641 BitfieldSize = ExprResult(/*Invalid=*/false);
2642 EqualLoc = PureSpecLoc = SourceLocation();
2643 DeclaratorInfo.setCommaLoc(CommaLoc);
2645 // GNU attributes are allowed before the second and subsequent declarator.
2646 MaybeParseGNUAttributes(DeclaratorInfo);
2648 if (ParseCXXMemberDeclaratorBeforeInitializer(
2649 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2654 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2655 // Skip to end of block or statement.
2656 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2657 // If we stopped at a ';', eat it.
2658 TryConsumeToken(tok::semi);
2662 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2665 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2666 /// Also detect and reject any attempted defaulted/deleted function definition.
2667 /// The location of the '=', if any, will be placed in EqualLoc.
2669 /// This does not check for a pure-specifier; that's handled elsewhere.
2671 /// brace-or-equal-initializer:
2672 /// '=' initializer-expression
2673 /// braced-init-list
2675 /// initializer-clause:
2676 /// assignment-expression
2677 /// braced-init-list
2679 /// defaulted/deleted function-definition:
2683 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2684 /// be a constant-expression.
2685 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2686 SourceLocation &EqualLoc) {
2687 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2688 && "Data member initializer not starting with '=' or '{'");
2690 EnterExpressionEvaluationContext Context(Actions,
2691 Sema::PotentiallyEvaluated,
2693 if (TryConsumeToken(tok::equal, EqualLoc)) {
2694 if (Tok.is(tok::kw_delete)) {
2695 // In principle, an initializer of '= delete p;' is legal, but it will
2696 // never type-check. It's better to diagnose it as an ill-formed expression
2697 // than as an ill-formed deleted non-function member.
2698 // An initializer of '= delete p, foo' will never be parsed, because
2699 // a top-level comma always ends the initializer expression.
2700 const Token &Next = NextToken();
2701 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2703 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2706 Diag(ConsumeToken(), diag::err_deleted_non_function);
2709 } else if (Tok.is(tok::kw_default)) {
2711 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2714 Diag(ConsumeToken(), diag::err_default_special_members);
2718 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2719 Diag(Tok, diag::err_ms_property_initializer) << PD;
2722 return ParseInitializer();
2725 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2726 SourceLocation AttrFixitLoc,
2727 unsigned TagType, Decl *TagDecl) {
2728 // Skip the optional 'final' keyword.
2729 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2730 assert(isCXX11FinalKeyword() && "not a class definition");
2733 // Diagnose any C++11 attributes after 'final' keyword.
2734 // We deliberately discard these attributes.
2735 ParsedAttributesWithRange Attrs(AttrFactory);
2736 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2738 // This can only happen if we had malformed misplaced attributes;
2739 // we only get called if there is a colon or left-brace after the
2741 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2745 // Skip the base clauses. This requires actually parsing them, because
2746 // otherwise we can't be sure where they end (a left brace may appear
2747 // within a template argument).
2748 if (Tok.is(tok::colon)) {
2749 // Enter the scope of the class so that we can correctly parse its bases.
2750 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2751 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2752 TagType == DeclSpec::TST_interface);
2754 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2756 // Parse the bases but don't attach them to the class.
2757 ParseBaseClause(nullptr);
2759 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2761 if (!Tok.is(tok::l_brace)) {
2762 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2763 diag::err_expected_lbrace_after_base_specifiers);
2769 assert(Tok.is(tok::l_brace));
2770 BalancedDelimiterTracker T(*this, tok::l_brace);
2774 // Parse and discard any trailing attributes.
2775 ParsedAttributes Attrs(AttrFactory);
2776 if (Tok.is(tok::kw___attribute))
2777 MaybeParseGNUAttributes(Attrs);
2780 /// ParseCXXMemberSpecification - Parse the class definition.
2782 /// member-specification:
2783 /// member-declaration member-specification[opt]
2784 /// access-specifier ':' member-specification[opt]
2786 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2787 SourceLocation AttrFixitLoc,
2788 ParsedAttributesWithRange &Attrs,
2789 unsigned TagType, Decl *TagDecl) {
2790 assert((TagType == DeclSpec::TST_struct ||
2791 TagType == DeclSpec::TST_interface ||
2792 TagType == DeclSpec::TST_union ||
2793 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2795 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2796 "parsing struct/union/class body");
2798 // Determine whether this is a non-nested class. Note that local
2799 // classes are *not* considered to be nested classes.
2800 bool NonNestedClass = true;
2801 if (!ClassStack.empty()) {
2802 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2803 if (S->isClassScope()) {
2804 // We're inside a class scope, so this is a nested class.
2805 NonNestedClass = false;
2807 // The Microsoft extension __interface does not permit nested classes.
2808 if (getCurrentClass().IsInterface) {
2809 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2811 << (isa<NamedDecl>(TagDecl)
2812 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2818 if ((S->getFlags() & Scope::FnScope))
2819 // If we're in a function or function template then this is a local
2820 // class rather than a nested class.
2825 // Enter a scope for the class.
2826 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2828 // Note that we are parsing a new (potentially-nested) class definition.
2829 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2830 TagType == DeclSpec::TST_interface);
2833 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2835 SourceLocation FinalLoc;
2836 bool IsFinalSpelledSealed = false;
2838 // Parse the optional 'final' keyword.
2839 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2840 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2841 assert((Specifier == VirtSpecifiers::VS_Final ||
2842 Specifier == VirtSpecifiers::VS_Sealed) &&
2843 "not a class definition");
2844 FinalLoc = ConsumeToken();
2845 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
2847 if (TagType == DeclSpec::TST_interface)
2848 Diag(FinalLoc, diag::err_override_control_interface)
2849 << VirtSpecifiers::getSpecifierName(Specifier);
2850 else if (Specifier == VirtSpecifiers::VS_Final)
2851 Diag(FinalLoc, getLangOpts().CPlusPlus11
2852 ? diag::warn_cxx98_compat_override_control_keyword
2853 : diag::ext_override_control_keyword)
2854 << VirtSpecifiers::getSpecifierName(Specifier);
2855 else if (Specifier == VirtSpecifiers::VS_Sealed)
2856 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
2858 // Parse any C++11 attributes after 'final' keyword.
2859 // These attributes are not allowed to appear here,
2860 // and the only possible place for them to appertain
2861 // to the class would be between class-key and class-name.
2862 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2864 // ParseClassSpecifier() does only a superficial check for attributes before
2865 // deciding to call this method. For example, for
2866 // `class C final alignas ([l) {` it will decide that this looks like a
2867 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
2868 // attribute parsing code will try to parse the '[' as a constexpr lambda
2869 // and consume enough tokens that the alignas parsing code will eat the
2870 // opening '{'. So bail out if the next token isn't one we expect.
2871 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
2873 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2878 if (Tok.is(tok::colon)) {
2879 ParseBaseClause(TagDecl);
2880 if (!Tok.is(tok::l_brace)) {
2881 bool SuggestFixIt = false;
2882 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
2883 if (Tok.isAtStartOfLine()) {
2884 switch (Tok.getKind()) {
2885 case tok::kw_private:
2886 case tok::kw_protected:
2887 case tok::kw_public:
2888 SuggestFixIt = NextToken().getKind() == tok::colon;
2890 case tok::kw_static_assert:
2893 // base-clause can have simple-template-id; 'template' can't be there
2894 case tok::kw_template:
2895 SuggestFixIt = true;
2897 case tok::identifier:
2898 SuggestFixIt = isConstructorDeclarator(true);
2901 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
2905 DiagnosticBuilder LBraceDiag =
2906 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
2908 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
2909 // Try recovering from missing { after base-clause.
2911 Tok.setKind(tok::l_brace);
2914 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2920 assert(Tok.is(tok::l_brace));
2921 BalancedDelimiterTracker T(*this, tok::l_brace);
2925 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2926 IsFinalSpelledSealed,
2927 T.getOpenLocation());
2929 // C++ 11p3: Members of a class defined with the keyword class are private
2930 // by default. Members of a class defined with the keywords struct or union
2931 // are public by default.
2932 AccessSpecifier CurAS;
2933 if (TagType == DeclSpec::TST_class)
2937 ParsedAttributes AccessAttrs(AttrFactory);
2940 // While we still have something to read, read the member-declarations.
2941 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2942 // Each iteration of this loop reads one member-declaration.
2944 if (getLangOpts().MicrosoftExt && Tok.isOneOf(tok::kw___if_exists,
2945 tok::kw___if_not_exists)) {
2946 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2950 // Check for extraneous top-level semicolon.
2951 if (Tok.is(tok::semi)) {
2952 ConsumeExtraSemi(InsideStruct, TagType);
2956 if (Tok.is(tok::annot_pragma_vis)) {
2957 HandlePragmaVisibility();
2961 if (Tok.is(tok::annot_pragma_pack)) {
2966 if (Tok.is(tok::annot_pragma_align)) {
2967 HandlePragmaAlign();
2971 if (Tok.is(tok::annot_pragma_openmp)) {
2972 ParseOpenMPDeclarativeDirective();
2976 if (Tok.is(tok::annot_pragma_ms_pointers_to_members)) {
2977 HandlePragmaMSPointersToMembers();
2981 if (Tok.is(tok::annot_pragma_ms_pragma)) {
2982 HandlePragmaMSPragma();
2986 // If we see a namespace here, a close brace was missing somewhere.
2987 if (Tok.is(tok::kw_namespace)) {
2988 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
2992 AccessSpecifier AS = getAccessSpecifierIfPresent();
2993 if (AS != AS_none) {
2994 // Current token is a C++ access specifier.
2996 SourceLocation ASLoc = Tok.getLocation();
2997 unsigned TokLength = Tok.getLength();
2999 AccessAttrs.clear();
3000 MaybeParseGNUAttributes(AccessAttrs);
3002 SourceLocation EndLoc;
3003 if (TryConsumeToken(tok::colon, EndLoc)) {
3004 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3005 Diag(EndLoc, diag::err_expected)
3006 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3008 EndLoc = ASLoc.getLocWithOffset(TokLength);
3009 Diag(EndLoc, diag::err_expected)
3010 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3013 // The Microsoft extension __interface does not permit non-public
3014 // access specifiers.
3015 if (TagType == DeclSpec::TST_interface && CurAS != AS_public) {
3016 Diag(ASLoc, diag::err_access_specifier_interface)
3017 << (CurAS == AS_protected);
3020 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
3021 AccessAttrs.getList())) {
3022 // found another attribute than only annotations
3023 AccessAttrs.clear();
3029 // Parse all the comma separated declarators.
3030 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
3035 SkipUntil(tok::r_brace);
3038 // If attributes exist after class contents, parse them.
3039 ParsedAttributes attrs(AttrFactory);
3040 MaybeParseGNUAttributes(attrs);
3043 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3044 T.getOpenLocation(),
3045 T.getCloseLocation(),
3048 // C++11 [class.mem]p2:
3049 // Within the class member-specification, the class is regarded as complete
3050 // within function bodies, default arguments, exception-specifications, and
3051 // brace-or-equal-initializers for non-static data members (including such
3052 // things in nested classes).
3053 if (TagDecl && NonNestedClass) {
3054 // We are not inside a nested class. This class and its nested classes
3055 // are complete and we can parse the delayed portions of method
3056 // declarations and the lexed inline method definitions, along with any
3057 // delayed attributes.
3058 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3059 ParseLexedAttributes(getCurrentClass());
3060 ParseLexedMethodDeclarations(getCurrentClass());
3062 // We've finished with all pending member declarations.
3063 Actions.ActOnFinishCXXMemberDecls();
3065 ParseLexedMemberInitializers(getCurrentClass());
3066 ParseLexedMethodDefs(getCurrentClass());
3067 PrevTokLocation = SavedPrevTokLocation;
3069 // We've finished parsing everything, including default argument
3071 Actions.ActOnFinishCXXMemberDefaultArgs(TagDecl);
3075 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3076 T.getCloseLocation());
3078 // Leave the class scope.
3083 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3084 assert(Tok.is(tok::kw_namespace));
3086 // FIXME: Suggest where the close brace should have gone by looking
3087 // at indentation changes within the definition body.
3088 Diag(D->getLocation(),
3089 diag::err_missing_end_of_definition) << D;
3090 Diag(Tok.getLocation(),
3091 diag::note_missing_end_of_definition_before) << D;
3093 // Push '};' onto the token stream to recover.
3097 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3098 Tok.setKind(tok::semi);
3101 Tok.setKind(tok::r_brace);
3104 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3105 /// which explicitly initializes the members or base classes of a
3106 /// class (C++ [class.base.init]). For example, the three initializers
3107 /// after the ':' in the Derived constructor below:
3111 /// class Derived : Base {
3115 /// Derived(float f) : Base(), x(17), f(f) { }
3119 /// [C++] ctor-initializer:
3120 /// ':' mem-initializer-list
3122 /// [C++] mem-initializer-list:
3123 /// mem-initializer ...[opt]
3124 /// mem-initializer ...[opt] , mem-initializer-list
3125 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3126 assert(Tok.is(tok::colon) &&
3127 "Constructor initializer always starts with ':'");
3129 // Poison the SEH identifiers so they are flagged as illegal in constructor
3131 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3132 SourceLocation ColonLoc = ConsumeToken();
3134 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3135 bool AnyErrors = false;
3138 if (Tok.is(tok::code_completion)) {
3139 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3141 return cutOffParsing();
3143 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3144 if (!MemInit.isInvalid())
3145 MemInitializers.push_back(MemInit.get());
3150 if (Tok.is(tok::comma))
3152 else if (Tok.is(tok::l_brace))
3154 // If the next token looks like a base or member initializer, assume that
3155 // we're just missing a comma.
3156 else if (Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3157 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3158 Diag(Loc, diag::err_ctor_init_missing_comma)
3159 << FixItHint::CreateInsertion(Loc, ", ");
3161 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3162 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3164 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3169 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3173 /// ParseMemInitializer - Parse a C++ member initializer, which is
3174 /// part of a constructor initializer that explicitly initializes one
3175 /// member or base class (C++ [class.base.init]). See
3176 /// ParseConstructorInitializer for an example.
3178 /// [C++] mem-initializer:
3179 /// mem-initializer-id '(' expression-list[opt] ')'
3180 /// [C++0x] mem-initializer-id braced-init-list
3182 /// [C++] mem-initializer-id:
3183 /// '::'[opt] nested-name-specifier[opt] class-name
3185 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3186 // parse '::'[opt] nested-name-specifier[opt]
3188 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
3189 ParsedType TemplateTypeTy;
3190 if (Tok.is(tok::annot_template_id)) {
3191 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3192 if (TemplateId->Kind == TNK_Type_template ||
3193 TemplateId->Kind == TNK_Dependent_template_name) {
3194 AnnotateTemplateIdTokenAsType();
3195 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3196 TemplateTypeTy = getTypeAnnotation(Tok);
3199 // Uses of decltype will already have been converted to annot_decltype by
3200 // ParseOptionalCXXScopeSpecifier at this point.
3201 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
3202 && Tok.isNot(tok::annot_decltype)) {
3203 Diag(Tok, diag::err_expected_member_or_base_name);
3207 IdentifierInfo *II = nullptr;
3208 DeclSpec DS(AttrFactory);
3209 SourceLocation IdLoc = Tok.getLocation();
3210 if (Tok.is(tok::annot_decltype)) {
3211 // Get the decltype expression, if there is one.
3212 ParseDecltypeSpecifier(DS);
3214 if (Tok.is(tok::identifier))
3215 // Get the identifier. This may be a member name or a class name,
3216 // but we'll let the semantic analysis determine which it is.
3217 II = Tok.getIdentifierInfo();
3223 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3224 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3226 ExprResult InitList = ParseBraceInitializer();
3227 if (InitList.isInvalid())
3230 SourceLocation EllipsisLoc;
3231 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3233 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3234 TemplateTypeTy, DS, IdLoc,
3235 InitList.get(), EllipsisLoc);
3236 } else if(Tok.is(tok::l_paren)) {
3237 BalancedDelimiterTracker T(*this, tok::l_paren);
3240 // Parse the optional expression-list.
3241 ExprVector ArgExprs;
3242 CommaLocsTy CommaLocs;
3243 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
3244 SkipUntil(tok::r_paren, StopAtSemi);
3250 SourceLocation EllipsisLoc;
3251 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3253 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3254 TemplateTypeTy, DS, IdLoc,
3255 T.getOpenLocation(), ArgExprs,
3256 T.getCloseLocation(), EllipsisLoc);
3259 if (getLangOpts().CPlusPlus11)
3260 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3262 return Diag(Tok, diag::err_expected) << tok::l_paren;
3265 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
3267 /// exception-specification:
3268 /// dynamic-exception-specification
3269 /// noexcept-specification
3271 /// noexcept-specification:
3273 /// 'noexcept' '(' constant-expression ')'
3274 ExceptionSpecificationType
3275 Parser::tryParseExceptionSpecification(bool Delayed,
3276 SourceRange &SpecificationRange,
3277 SmallVectorImpl<ParsedType> &DynamicExceptions,
3278 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3279 ExprResult &NoexceptExpr,
3280 CachedTokens *&ExceptionSpecTokens) {
3281 ExceptionSpecificationType Result = EST_None;
3282 ExceptionSpecTokens = 0;
3284 // Handle delayed parsing of exception-specifications.
3286 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3289 // Consume and cache the starting token.
3290 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3291 Token StartTok = Tok;
3292 SpecificationRange = SourceRange(ConsumeToken());
3295 if (!Tok.is(tok::l_paren)) {
3296 // If this is a bare 'noexcept', we're done.
3298 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3300 return EST_BasicNoexcept;
3303 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3304 return EST_DynamicNone;
3307 // Cache the tokens for the exception-specification.
3308 ExceptionSpecTokens = new CachedTokens;
3309 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3310 ExceptionSpecTokens->push_back(Tok); // '('
3311 SpecificationRange.setEnd(ConsumeParen()); // '('
3313 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3314 /*StopAtSemi=*/true,
3315 /*ConsumeFinalToken=*/true);
3316 SpecificationRange.setEnd(Tok.getLocation());
3317 return EST_Unparsed;
3320 // See if there's a dynamic specification.
3321 if (Tok.is(tok::kw_throw)) {
3322 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3324 DynamicExceptionRanges);
3325 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3326 "Produced different number of exception types and ranges.");
3329 // If there's no noexcept specification, we're done.
3330 if (Tok.isNot(tok::kw_noexcept))
3333 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3335 // If we already had a dynamic specification, parse the noexcept for,
3336 // recovery, but emit a diagnostic and don't store the results.
3337 SourceRange NoexceptRange;
3338 ExceptionSpecificationType NoexceptType = EST_None;
3340 SourceLocation KeywordLoc = ConsumeToken();
3341 if (Tok.is(tok::l_paren)) {
3342 // There is an argument.
3343 BalancedDelimiterTracker T(*this, tok::l_paren);
3345 NoexceptType = EST_ComputedNoexcept;
3346 NoexceptExpr = ParseConstantExpression();
3348 // The argument must be contextually convertible to bool. We use
3349 // ActOnBooleanCondition for this purpose.
3350 if (!NoexceptExpr.isInvalid()) {
3351 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
3352 NoexceptExpr.get());
3353 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3355 NoexceptType = EST_None;
3358 // There is no argument.
3359 NoexceptType = EST_BasicNoexcept;
3360 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3363 if (Result == EST_None) {
3364 SpecificationRange = NoexceptRange;
3365 Result = NoexceptType;
3367 // If there's a dynamic specification after a noexcept specification,
3368 // parse that and ignore the results.
3369 if (Tok.is(tok::kw_throw)) {
3370 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3371 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3372 DynamicExceptionRanges);
3375 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3381 static void diagnoseDynamicExceptionSpecification(
3382 Parser &P, const SourceRange &Range, bool IsNoexcept) {
3383 if (P.getLangOpts().CPlusPlus11) {
3384 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3385 P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
3386 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3387 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3391 /// ParseDynamicExceptionSpecification - Parse a C++
3392 /// dynamic-exception-specification (C++ [except.spec]).
3394 /// dynamic-exception-specification:
3395 /// 'throw' '(' type-id-list [opt] ')'
3396 /// [MS] 'throw' '(' '...' ')'
3399 /// type-id ... [opt]
3400 /// type-id-list ',' type-id ... [opt]
3402 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3403 SourceRange &SpecificationRange,
3404 SmallVectorImpl<ParsedType> &Exceptions,
3405 SmallVectorImpl<SourceRange> &Ranges) {
3406 assert(Tok.is(tok::kw_throw) && "expected throw");
3408 SpecificationRange.setBegin(ConsumeToken());
3409 BalancedDelimiterTracker T(*this, tok::l_paren);
3410 if (T.consumeOpen()) {
3411 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3412 SpecificationRange.setEnd(SpecificationRange.getBegin());
3413 return EST_DynamicNone;
3416 // Parse throw(...), a Microsoft extension that means "this function
3417 // can throw anything".
3418 if (Tok.is(tok::ellipsis)) {
3419 SourceLocation EllipsisLoc = ConsumeToken();
3420 if (!getLangOpts().MicrosoftExt)
3421 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3423 SpecificationRange.setEnd(T.getCloseLocation());
3424 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3428 // Parse the sequence of type-ids.
3430 while (Tok.isNot(tok::r_paren)) {
3431 TypeResult Res(ParseTypeName(&Range));
3433 if (Tok.is(tok::ellipsis)) {
3434 // C++0x [temp.variadic]p5:
3435 // - In a dynamic-exception-specification (15.4); the pattern is a
3437 SourceLocation Ellipsis = ConsumeToken();
3438 Range.setEnd(Ellipsis);
3439 if (!Res.isInvalid())
3440 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3443 if (!Res.isInvalid()) {
3444 Exceptions.push_back(Res.get());
3445 Ranges.push_back(Range);
3448 if (!TryConsumeToken(tok::comma))
3453 SpecificationRange.setEnd(T.getCloseLocation());
3454 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3455 Exceptions.empty());
3456 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3459 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3460 /// function declaration.
3461 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3462 assert(Tok.is(tok::arrow) && "expected arrow");
3466 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3469 /// \brief We have just started parsing the definition of a new class,
3470 /// so push that class onto our stack of classes that is currently
3472 Sema::ParsingClassState
3473 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3475 assert((NonNestedClass || !ClassStack.empty()) &&
3476 "Nested class without outer class");
3477 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3478 return Actions.PushParsingClass();
3481 /// \brief Deallocate the given parsed class and all of its nested
3483 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3484 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3485 delete Class->LateParsedDeclarations[I];
3489 /// \brief Pop the top class of the stack of classes that are
3490 /// currently being parsed.
3492 /// This routine should be called when we have finished parsing the
3493 /// definition of a class, but have not yet popped the Scope
3494 /// associated with the class's definition.
3495 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3496 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3498 Actions.PopParsingClass(state);
3500 ParsingClass *Victim = ClassStack.top();
3502 if (Victim->TopLevelClass) {
3503 // Deallocate all of the nested classes of this class,
3504 // recursively: we don't need to keep any of this information.
3505 DeallocateParsedClasses(Victim);
3508 assert(!ClassStack.empty() && "Missing top-level class?");
3510 if (Victim->LateParsedDeclarations.empty()) {
3511 // The victim is a nested class, but we will not need to perform
3512 // any processing after the definition of this class since it has
3513 // no members whose handling was delayed. Therefore, we can just
3514 // remove this nested class.
3515 DeallocateParsedClasses(Victim);
3519 // This nested class has some members that will need to be processed
3520 // after the top-level class is completely defined. Therefore, add
3521 // it to the list of nested classes within its parent.
3522 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3523 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3524 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3527 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3529 /// \return the parsed identifier on success, and 0 if the next token is not an
3530 /// attribute-token.
3532 /// C++11 [dcl.attr.grammar]p3:
3533 /// If a keyword or an alternative token that satisfies the syntactic
3534 /// requirements of an identifier is contained in an attribute-token,
3535 /// it is considered an identifier.
3536 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3537 switch (Tok.getKind()) {
3539 // Identifiers and keywords have identifier info attached.
3540 if (!Tok.isAnnotation()) {
3541 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3542 Loc = ConsumeToken();
3548 case tok::ampamp: // 'and'
3549 case tok::pipe: // 'bitor'
3550 case tok::pipepipe: // 'or'
3551 case tok::caret: // 'xor'
3552 case tok::tilde: // 'compl'
3553 case tok::amp: // 'bitand'
3554 case tok::ampequal: // 'and_eq'
3555 case tok::pipeequal: // 'or_eq'
3556 case tok::caretequal: // 'xor_eq'
3557 case tok::exclaim: // 'not'
3558 case tok::exclaimequal: // 'not_eq'
3559 // Alternative tokens do not have identifier info, but their spelling
3560 // starts with an alphabetical character.
3561 SmallString<8> SpellingBuf;
3562 SourceLocation SpellingLoc =
3563 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3564 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3565 if (isLetter(Spelling[0])) {
3566 Loc = ConsumeToken();
3567 return &PP.getIdentifierTable().get(Spelling);
3573 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3574 IdentifierInfo *ScopeName) {
3575 switch (AttributeList::getKind(AttrName, ScopeName,
3576 AttributeList::AS_CXX11)) {
3577 case AttributeList::AT_CarriesDependency:
3578 case AttributeList::AT_Deprecated:
3579 case AttributeList::AT_FallThrough:
3580 case AttributeList::AT_CXX11NoReturn: {
3589 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3591 /// [C++11] attribute-argument-clause:
3592 /// '(' balanced-token-seq ')'
3594 /// [C++11] balanced-token-seq:
3596 /// balanced-token-seq balanced-token
3598 /// [C++11] balanced-token:
3599 /// '(' balanced-token-seq ')'
3600 /// '[' balanced-token-seq ']'
3601 /// '{' balanced-token-seq '}'
3602 /// any token but '(', ')', '[', ']', '{', or '}'
3603 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3604 SourceLocation AttrNameLoc,
3605 ParsedAttributes &Attrs,
3606 SourceLocation *EndLoc,
3607 IdentifierInfo *ScopeName,
3608 SourceLocation ScopeLoc) {
3609 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3610 SourceLocation LParenLoc = Tok.getLocation();
3612 // If the attribute isn't known, we will not attempt to parse any
3614 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
3615 getTargetInfo().getTriple(), getLangOpts())) {
3616 // Eat the left paren, then skip to the ending right paren.
3618 SkipUntil(tok::r_paren);
3622 if (ScopeName && ScopeName->getName() == "gnu")
3623 // GNU-scoped attributes have some special cases to handle GNU-specific
3625 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3626 ScopeLoc, AttributeList::AS_CXX11, nullptr);
3629 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3630 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3632 const AttributeList *Attr = Attrs.getList();
3633 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3634 // If the attribute is a standard or built-in attribute and we are
3635 // parsing an argument list, we need to determine whether this attribute
3636 // was allowed to have an argument list (such as [[deprecated]]), and how
3637 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3638 if (Attr->getMaxArgs() && !NumArgs) {
3639 // The attribute was allowed to have arguments, but none were provided
3640 // even though the attribute parsed successfully. This is an error.
3641 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3642 } else if (!Attr->getMaxArgs()) {
3643 // The attribute parsed successfully, but was not allowed to have any
3644 // arguments. It doesn't matter whether any were provided -- the
3645 // presence of the argument list (even if empty) is diagnosed.
3646 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3648 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3655 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
3657 /// [C++11] attribute-specifier:
3658 /// '[' '[' attribute-list ']' ']'
3659 /// alignment-specifier
3661 /// [C++11] attribute-list:
3663 /// attribute-list ',' attribute[opt]
3665 /// attribute-list ',' attribute '...'
3667 /// [C++11] attribute:
3668 /// attribute-token attribute-argument-clause[opt]
3670 /// [C++11] attribute-token:
3672 /// attribute-scoped-token
3674 /// [C++11] attribute-scoped-token:
3675 /// attribute-namespace '::' identifier
3677 /// [C++11] attribute-namespace:
3679 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3680 SourceLocation *endLoc) {
3681 if (Tok.is(tok::kw_alignas)) {
3682 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3683 ParseAlignmentSpecifier(attrs, endLoc);
3687 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3688 && "Not a C++11 attribute list");
3690 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3695 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3697 while (Tok.isNot(tok::r_square)) {
3698 // attribute not present
3699 if (TryConsumeToken(tok::comma))
3702 SourceLocation ScopeLoc, AttrLoc;
3703 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3705 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3707 // Break out to the "expected ']'" diagnostic.
3711 if (TryConsumeToken(tok::coloncolon)) {
3712 ScopeName = AttrName;
3715 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3717 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3718 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3723 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
3724 bool AttrParsed = false;
3727 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3728 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
3729 << AttrName << SourceRange(SeenAttrs[AttrName]);
3731 // Parse attribute arguments
3732 if (Tok.is(tok::l_paren))
3733 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3734 ScopeName, ScopeLoc);
3737 attrs.addNew(AttrName,
3738 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3740 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
3742 if (TryConsumeToken(tok::ellipsis))
3743 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3744 << AttrName->getName();
3747 if (ExpectAndConsume(tok::r_square))
3748 SkipUntil(tok::r_square);
3750 *endLoc = Tok.getLocation();
3751 if (ExpectAndConsume(tok::r_square))
3752 SkipUntil(tok::r_square);
3755 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3757 /// attribute-specifier-seq:
3758 /// attribute-specifier-seq[opt] attribute-specifier
3759 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3760 SourceLocation *endLoc) {
3761 assert(getLangOpts().CPlusPlus11);
3763 SourceLocation StartLoc = Tok.getLocation(), Loc;
3768 ParseCXX11AttributeSpecifier(attrs, endLoc);
3769 } while (isCXX11AttributeSpecifier());
3771 attrs.Range = SourceRange(StartLoc, *endLoc);
3774 void Parser::DiagnoseAndSkipCXX11Attributes() {
3775 // Start and end location of an attribute or an attribute list.
3776 SourceLocation StartLoc = Tok.getLocation();
3777 SourceLocation EndLoc = SkipCXX11Attributes();
3779 if (EndLoc.isValid()) {
3780 SourceRange Range(StartLoc, EndLoc);
3781 Diag(StartLoc, diag::err_attributes_not_allowed)
3786 SourceLocation Parser::SkipCXX11Attributes() {
3787 SourceLocation EndLoc;
3789 if (!isCXX11AttributeSpecifier())
3793 if (Tok.is(tok::l_square)) {
3794 BalancedDelimiterTracker T(*this, tok::l_square);
3797 EndLoc = T.getCloseLocation();
3799 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
3801 BalancedDelimiterTracker T(*this, tok::l_paren);
3802 if (!T.consumeOpen())
3804 EndLoc = T.getCloseLocation();
3806 } while (isCXX11AttributeSpecifier());
3811 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
3813 /// [MS] ms-attribute:
3814 /// '[' token-seq ']'
3816 /// [MS] ms-attribute-seq:
3817 /// ms-attribute[opt]
3818 /// ms-attribute ms-attribute-seq
3819 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3820 SourceLocation *endLoc) {
3821 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3824 // FIXME: If this is actually a C++11 attribute, parse it as one.
3825 BalancedDelimiterTracker T(*this, tok::l_square);
3827 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
3830 *endLoc = T.getCloseLocation();
3831 } while (Tok.is(tok::l_square));
3834 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3835 AccessSpecifier& CurAS) {
3836 IfExistsCondition Result;
3837 if (ParseMicrosoftIfExistsCondition(Result))
3840 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3841 if (Braces.consumeOpen()) {
3842 Diag(Tok, diag::err_expected) << tok::l_brace;
3846 switch (Result.Behavior) {
3848 // Parse the declarations below.
3852 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3853 << Result.IsIfExists;
3854 // Fall through to skip.
3861 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
3862 // __if_exists, __if_not_exists can nest.
3863 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
3864 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3868 // Check for extraneous top-level semicolon.
3869 if (Tok.is(tok::semi)) {
3870 ConsumeExtraSemi(InsideStruct, TagType);
3874 AccessSpecifier AS = getAccessSpecifierIfPresent();
3875 if (AS != AS_none) {
3876 // Current token is a C++ access specifier.
3878 SourceLocation ASLoc = Tok.getLocation();
3880 if (Tok.is(tok::colon))
3881 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3883 Diag(Tok, diag::err_expected) << tok::colon;
3888 // Parse all the comma separated declarators.
3889 ParseCXXClassMemberDeclaration(CurAS, nullptr);
3892 Braces.consumeClose();