1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++ Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "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"
30 using namespace clang;
32 /// ParseNamespace - We know that the current token is a namespace keyword. This
33 /// may either be a top level namespace or a block-level namespace alias. If
34 /// there was an inline keyword, it has already been parsed.
36 /// namespace-definition: [C++ 7.3: basic.namespace]
37 /// named-namespace-definition
38 /// unnamed-namespace-definition
40 /// unnamed-namespace-definition:
41 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
43 /// named-namespace-definition:
44 /// original-namespace-definition
45 /// extension-namespace-definition
47 /// original-namespace-definition:
48 /// 'inline'[opt] 'namespace' identifier attributes[opt]
49 /// '{' namespace-body '}'
51 /// extension-namespace-definition:
52 /// 'inline'[opt] 'namespace' original-namespace-name
53 /// '{' namespace-body '}'
55 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
56 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
58 Parser::DeclGroupPtrTy Parser::ParseNamespace(unsigned Context,
59 SourceLocation &DeclEnd,
60 SourceLocation InlineLoc) {
61 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
62 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
63 ObjCDeclContextSwitch ObjCDC(*this);
65 if (Tok.is(tok::code_completion)) {
66 Actions.CodeCompleteNamespaceDecl(getCurScope());
71 SourceLocation IdentLoc;
72 IdentifierInfo *Ident = nullptr;
73 std::vector<SourceLocation> ExtraIdentLoc;
74 std::vector<IdentifierInfo*> ExtraIdent;
75 std::vector<SourceLocation> ExtraNamespaceLoc;
77 ParsedAttributesWithRange attrs(AttrFactory);
78 SourceLocation attrLoc;
79 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
80 if (!getLangOpts().CPlusPlus1z)
81 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
83 attrLoc = Tok.getLocation();
84 ParseCXX11Attributes(attrs);
87 if (Tok.is(tok::identifier)) {
88 Ident = Tok.getIdentifierInfo();
89 IdentLoc = ConsumeToken(); // eat the identifier.
90 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
91 ExtraNamespaceLoc.push_back(ConsumeToken());
92 ExtraIdent.push_back(Tok.getIdentifierInfo());
93 ExtraIdentLoc.push_back(ConsumeToken());
97 // A nested namespace definition cannot have attributes.
98 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
99 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
101 // Read label attributes, if present.
102 if (Tok.is(tok::kw___attribute)) {
103 attrLoc = Tok.getLocation();
104 ParseGNUAttributes(attrs);
107 if (Tok.is(tok::equal)) {
109 Diag(Tok, diag::err_expected) << tok::identifier;
110 // Skip to end of the definition and eat the ';'.
111 SkipUntil(tok::semi);
114 if (attrLoc.isValid())
115 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
116 if (InlineLoc.isValid())
117 Diag(InlineLoc, diag::err_inline_namespace_alias)
118 << FixItHint::CreateRemoval(InlineLoc);
119 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
120 return Actions.ConvertDeclToDeclGroup(NSAlias);
123 BalancedDelimiterTracker T(*this, tok::l_brace);
124 if (T.consumeOpen()) {
126 Diag(Tok, diag::err_expected) << tok::l_brace;
128 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
132 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
133 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
134 getCurScope()->getFnParent()) {
135 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
136 SkipUntil(tok::r_brace);
140 if (ExtraIdent.empty()) {
141 // Normal namespace definition, not a nested-namespace-definition.
142 } else if (InlineLoc.isValid()) {
143 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
144 } else if (getLangOpts().CPlusPlus1z) {
145 Diag(ExtraNamespaceLoc[0],
146 diag::warn_cxx14_compat_nested_namespace_definition);
148 TentativeParsingAction TPA(*this);
149 SkipUntil(tok::r_brace, StopBeforeMatch);
150 Token rBraceToken = Tok;
153 if (!rBraceToken.is(tok::r_brace)) {
154 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
155 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
157 std::string NamespaceFix;
158 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
159 E = ExtraIdent.end(); I != E; ++I) {
160 NamespaceFix += " { namespace ";
161 NamespaceFix += (*I)->getName();
165 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
168 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
169 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
170 ExtraIdentLoc.back()),
172 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
176 // If we're still good, complain about inline namespaces in non-C++0x now.
177 if (InlineLoc.isValid())
178 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
179 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
181 // Enter a scope for the namespace.
182 ParseScope NamespaceScope(this, Scope::DeclScope);
184 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
186 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
187 IdentLoc, Ident, T.getOpenLocation(),
188 attrs.getList(), ImplicitUsingDirectiveDecl);
190 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
191 "parsing namespace");
193 // Parse the contents of the namespace. This includes parsing recovery on
194 // any improperly nested namespaces.
195 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
196 InlineLoc, attrs, T);
198 // Leave the namespace scope.
199 NamespaceScope.Exit();
201 DeclEnd = T.getCloseLocation();
202 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
204 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
205 ImplicitUsingDirectiveDecl);
208 /// ParseInnerNamespace - Parse the contents of a namespace.
209 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
210 std::vector<IdentifierInfo *> &Ident,
211 std::vector<SourceLocation> &NamespaceLoc,
212 unsigned int index, SourceLocation &InlineLoc,
213 ParsedAttributes &attrs,
214 BalancedDelimiterTracker &Tracker) {
215 if (index == Ident.size()) {
216 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
217 Tok.isNot(tok::eof)) {
218 ParsedAttributesWithRange attrs(AttrFactory);
219 MaybeParseCXX11Attributes(attrs);
220 MaybeParseMicrosoftAttributes(attrs);
221 ParseExternalDeclaration(attrs);
224 // The caller is what called check -- we are simply calling
226 Tracker.consumeClose();
231 // Handle a nested namespace definition.
232 // FIXME: Preserve the source information through to the AST rather than
233 // desugaring it here.
234 ParseScope NamespaceScope(this, Scope::DeclScope);
235 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
237 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
238 NamespaceLoc[index], IdentLoc[index],
239 Ident[index], Tracker.getOpenLocation(),
240 attrs.getList(), ImplicitUsingDirectiveDecl);
241 assert(!ImplicitUsingDirectiveDecl &&
242 "nested namespace definition cannot define anonymous namespace");
244 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
247 NamespaceScope.Exit();
248 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
251 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
252 /// alias definition.
254 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
255 SourceLocation AliasLoc,
256 IdentifierInfo *Alias,
257 SourceLocation &DeclEnd) {
258 assert(Tok.is(tok::equal) && "Not equal token");
260 ConsumeToken(); // eat the '='.
262 if (Tok.is(tok::code_completion)) {
263 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
269 // Parse (optional) nested-name-specifier.
270 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
272 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
273 Diag(Tok, diag::err_expected_namespace_name);
274 // Skip to end of the definition and eat the ';'.
275 SkipUntil(tok::semi);
280 IdentifierInfo *Ident = Tok.getIdentifierInfo();
281 SourceLocation IdentLoc = ConsumeToken();
284 DeclEnd = Tok.getLocation();
285 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
286 SkipUntil(tok::semi);
288 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
289 Alias, SS, IdentLoc, Ident);
292 /// ParseLinkage - We know that the current token is a string_literal
293 /// and just before that, that extern was seen.
295 /// linkage-specification: [C++ 7.5p2: dcl.link]
296 /// 'extern' string-literal '{' declaration-seq[opt] '}'
297 /// 'extern' string-literal declaration
299 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
300 assert(isTokenStringLiteral() && "Not a string literal!");
301 ExprResult Lang = ParseStringLiteralExpression(false);
303 ParseScope LinkageScope(this, Scope::DeclScope);
307 : Actions.ActOnStartLinkageSpecification(
308 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
309 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
311 ParsedAttributesWithRange attrs(AttrFactory);
312 MaybeParseCXX11Attributes(attrs);
313 MaybeParseMicrosoftAttributes(attrs);
315 if (Tok.isNot(tok::l_brace)) {
316 // Reset the source range in DS, as the leading "extern"
317 // does not really belong to the inner declaration ...
318 DS.SetRangeStart(SourceLocation());
319 DS.SetRangeEnd(SourceLocation());
320 // ... but anyway remember that such an "extern" was seen.
321 DS.setExternInLinkageSpec(true);
322 ParseExternalDeclaration(attrs, &DS);
323 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
324 getCurScope(), LinkageSpec, SourceLocation())
330 ProhibitAttributes(attrs);
332 BalancedDelimiterTracker T(*this, tok::l_brace);
335 unsigned NestedModules = 0;
337 switch (Tok.getKind()) {
338 case tok::annot_module_begin:
343 case tok::annot_module_end:
350 case tok::annot_module_include:
362 ParsedAttributesWithRange attrs(AttrFactory);
363 MaybeParseCXX11Attributes(attrs);
364 MaybeParseMicrosoftAttributes(attrs);
365 ParseExternalDeclaration(attrs);
373 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
374 getCurScope(), LinkageSpec, T.getCloseLocation())
378 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
379 /// using-directive. Assumes that current token is 'using'.
380 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
381 const ParsedTemplateInfo &TemplateInfo,
382 SourceLocation &DeclEnd,
383 ParsedAttributesWithRange &attrs,
385 assert(Tok.is(tok::kw_using) && "Not using token");
386 ObjCDeclContextSwitch ObjCDC(*this);
389 SourceLocation UsingLoc = ConsumeToken();
391 if (Tok.is(tok::code_completion)) {
392 Actions.CodeCompleteUsing(getCurScope());
397 // 'using namespace' means this is a using-directive.
398 if (Tok.is(tok::kw_namespace)) {
399 // Template parameters are always an error here.
400 if (TemplateInfo.Kind) {
401 SourceRange R = TemplateInfo.getSourceRange();
402 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
403 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
406 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
409 // Otherwise, it must be a using-declaration or an alias-declaration.
411 // Using declarations can't have attributes.
412 ProhibitAttributes(attrs);
414 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
418 /// ParseUsingDirective - Parse C++ using-directive, assumes
419 /// that current token is 'namespace' and 'using' was already parsed.
421 /// using-directive: [C++ 7.3.p4: namespace.udir]
422 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
424 /// [GNU] using-directive:
425 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
426 /// namespace-name attributes[opt] ;
428 Decl *Parser::ParseUsingDirective(unsigned Context,
429 SourceLocation UsingLoc,
430 SourceLocation &DeclEnd,
431 ParsedAttributes &attrs) {
432 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
435 SourceLocation NamespcLoc = ConsumeToken();
437 if (Tok.is(tok::code_completion)) {
438 Actions.CodeCompleteUsingDirective(getCurScope());
444 // Parse (optional) nested-name-specifier.
445 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
447 IdentifierInfo *NamespcName = nullptr;
448 SourceLocation IdentLoc = SourceLocation();
450 // Parse namespace-name.
451 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
452 Diag(Tok, diag::err_expected_namespace_name);
453 // If there was invalid namespace name, skip to end of decl, and eat ';'.
454 SkipUntil(tok::semi);
455 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
460 NamespcName = Tok.getIdentifierInfo();
461 IdentLoc = ConsumeToken();
463 // Parse (optional) attributes (most likely GNU strong-using extension).
464 bool GNUAttr = false;
465 if (Tok.is(tok::kw___attribute)) {
467 ParseGNUAttributes(attrs);
471 DeclEnd = Tok.getLocation();
472 if (ExpectAndConsume(tok::semi,
473 GNUAttr ? diag::err_expected_semi_after_attribute_list
474 : diag::err_expected_semi_after_namespace_name))
475 SkipUntil(tok::semi);
477 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
478 IdentLoc, NamespcName, attrs.getList());
481 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
482 /// Assumes that 'using' was already seen.
484 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
485 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
487 /// 'using' :: unqualified-id
489 /// alias-declaration: C++11 [dcl.dcl]p1
490 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
492 Decl *Parser::ParseUsingDeclaration(unsigned Context,
493 const ParsedTemplateInfo &TemplateInfo,
494 SourceLocation UsingLoc,
495 SourceLocation &DeclEnd,
499 SourceLocation TypenameLoc;
500 bool HasTypenameKeyword = false;
502 // Check for misplaced attributes before the identifier in an
503 // alias-declaration.
504 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
505 MaybeParseCXX11Attributes(MisplacedAttrs);
507 // Ignore optional 'typename'.
508 // FIXME: This is wrong; we should parse this as a typename-specifier.
509 if (TryConsumeToken(tok::kw_typename, TypenameLoc))
510 HasTypenameKeyword = true;
512 if (Tok.is(tok::kw___super)) {
513 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
514 SkipUntil(tok::semi);
518 // Parse nested-name-specifier.
519 IdentifierInfo *LastII = nullptr;
520 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
521 /*MayBePseudoDtor=*/nullptr,
522 /*IsTypename=*/false,
525 // Check nested-name specifier.
526 if (SS.isInvalid()) {
527 SkipUntil(tok::semi);
531 SourceLocation TemplateKWLoc;
534 // Parse the unqualified-id. We allow parsing of both constructor and
535 // destructor names and allow the action module to diagnose any semantic
538 // C++11 [class.qual]p2:
539 // [...] in a using-declaration that is a member-declaration, if the name
540 // specified after the nested-name-specifier is the same as the identifier
541 // or the simple-template-id's template-name in the last component of the
542 // nested-name-specifier, the name is [...] considered to name the
544 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
545 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
546 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
547 !SS.getScopeRep()->getAsNamespace() &&
548 !SS.getScopeRep()->getAsNamespaceAlias()) {
549 SourceLocation IdLoc = ConsumeToken();
550 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
551 Name.setConstructorName(Type, IdLoc, IdLoc);
552 } else if (ParseUnqualifiedId(
553 SS, /*EnteringContext=*/false,
554 /*AllowDestructorName=*/true,
555 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
556 NextToken().is(tok::equal)),
557 nullptr, TemplateKWLoc, Name)) {
558 SkipUntil(tok::semi);
562 ParsedAttributesWithRange Attrs(AttrFactory);
563 MaybeParseGNUAttributes(Attrs);
564 MaybeParseCXX11Attributes(Attrs);
566 // Maybe this is an alias-declaration.
567 TypeResult TypeAlias;
568 bool IsAliasDecl = Tok.is(tok::equal);
569 Decl *DeclFromDeclSpec = nullptr;
571 // If we had any misplaced attributes from earlier, this is where they
572 // should have been written.
573 if (MisplacedAttrs.Range.isValid()) {
574 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
575 << FixItHint::CreateInsertionFromRange(
577 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
578 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
579 Attrs.takeAllFrom(MisplacedAttrs);
584 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
585 diag::warn_cxx98_compat_alias_declaration :
586 diag::ext_alias_declaration);
588 // Type alias templates cannot be specialized.
590 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
591 Name.getKind() == UnqualifiedId::IK_TemplateId)
593 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
595 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
597 if (SpecKind != -1) {
600 Range = SourceRange(Name.TemplateId->LAngleLoc,
601 Name.TemplateId->RAngleLoc);
603 Range = TemplateInfo.getSourceRange();
604 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
605 << SpecKind << Range;
606 SkipUntil(tok::semi);
610 // Name must be an identifier.
611 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
612 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
613 // No removal fixit: can't recover from this.
614 SkipUntil(tok::semi);
616 } else if (HasTypenameKeyword)
617 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
618 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
619 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
620 else if (SS.isNotEmpty())
621 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
622 << FixItHint::CreateRemoval(SS.getRange());
624 TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind
625 ? Declarator::AliasTemplateContext
626 : Declarator::AliasDeclContext,
627 AS, &DeclFromDeclSpec, &Attrs);
629 *OwnedType = DeclFromDeclSpec;
631 // C++11 attributes are not allowed on a using-declaration, but GNU ones
633 ProhibitAttributes(MisplacedAttrs);
634 ProhibitAttributes(Attrs);
636 // Parse (optional) attributes (most likely GNU strong-using extension).
637 MaybeParseGNUAttributes(Attrs);
641 DeclEnd = Tok.getLocation();
642 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
643 !Attrs.empty() ? "attributes list"
644 : IsAliasDecl ? "alias declaration"
645 : "using declaration"))
646 SkipUntil(tok::semi);
648 // Diagnose an attempt to declare a templated using-declaration.
649 // In C++11, alias-declarations can be templates:
650 // template <...> using id = type;
651 if (TemplateInfo.Kind && !IsAliasDecl) {
652 SourceRange R = TemplateInfo.getSourceRange();
653 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
654 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
656 // Unfortunately, we have to bail out instead of recovering by
657 // ignoring the parameters, just in case the nested name specifier
658 // depends on the parameters.
662 // "typename" keyword is allowed for identifiers only,
663 // because it may be a type definition.
664 if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
665 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
666 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
667 // Proceed parsing, but reset the HasTypenameKeyword flag.
668 HasTypenameKeyword = false;
672 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
673 MultiTemplateParamsArg TemplateParamsArg(
674 TemplateParams ? TemplateParams->data() : nullptr,
675 TemplateParams ? TemplateParams->size() : 0);
676 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
677 UsingLoc, Name, Attrs.getList(),
678 TypeAlias, DeclFromDeclSpec);
681 return Actions.ActOnUsingDeclaration(getCurScope(), AS,
682 /* HasUsingKeyword */ true, UsingLoc,
683 SS, Name, Attrs.getList(),
684 HasTypenameKeyword, TypenameLoc);
687 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
689 /// [C++0x] static_assert-declaration:
690 /// static_assert ( constant-expression , string-literal ) ;
692 /// [C11] static_assert-declaration:
693 /// _Static_assert ( constant-expression , string-literal ) ;
695 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
696 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
697 "Not a static_assert declaration");
699 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
700 Diag(Tok, diag::ext_c11_static_assert);
701 if (Tok.is(tok::kw_static_assert))
702 Diag(Tok, diag::warn_cxx98_compat_static_assert);
704 SourceLocation StaticAssertLoc = ConsumeToken();
706 BalancedDelimiterTracker T(*this, tok::l_paren);
707 if (T.consumeOpen()) {
708 Diag(Tok, diag::err_expected) << tok::l_paren;
713 ExprResult AssertExpr(ParseConstantExpression());
714 if (AssertExpr.isInvalid()) {
719 ExprResult AssertMessage;
720 if (Tok.is(tok::r_paren)) {
721 Diag(Tok, getLangOpts().CPlusPlus1z
722 ? diag::warn_cxx14_compat_static_assert_no_message
723 : diag::ext_static_assert_no_message)
724 << (getLangOpts().CPlusPlus1z
726 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
728 if (ExpectAndConsume(tok::comma)) {
729 SkipUntil(tok::semi);
733 if (!isTokenStringLiteral()) {
734 Diag(Tok, diag::err_expected_string_literal)
735 << /*Source='static_assert'*/1;
740 AssertMessage = ParseStringLiteralExpression();
741 if (AssertMessage.isInvalid()) {
749 DeclEnd = Tok.getLocation();
750 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
752 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
755 T.getCloseLocation());
758 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
760 /// 'decltype' ( expression )
761 /// 'decltype' ( 'auto' ) [C++1y]
763 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
764 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
765 && "Not a decltype specifier");
768 SourceLocation StartLoc = Tok.getLocation();
769 SourceLocation EndLoc;
771 if (Tok.is(tok::annot_decltype)) {
772 Result = getExprAnnotation(Tok);
773 EndLoc = Tok.getAnnotationEndLoc();
775 if (Result.isInvalid()) {
776 DS.SetTypeSpecError();
780 if (Tok.getIdentifierInfo()->isStr("decltype"))
781 Diag(Tok, diag::warn_cxx98_compat_decltype);
785 BalancedDelimiterTracker T(*this, tok::l_paren);
786 if (T.expectAndConsume(diag::err_expected_lparen_after,
787 "decltype", tok::r_paren)) {
788 DS.SetTypeSpecError();
789 return T.getOpenLocation() == Tok.getLocation() ?
790 StartLoc : T.getOpenLocation();
793 // Check for C++1y 'decltype(auto)'.
794 if (Tok.is(tok::kw_auto)) {
795 // No need to disambiguate here: an expression can't start with 'auto',
796 // because the typename-specifier in a function-style cast operation can't
798 Diag(Tok.getLocation(),
799 getLangOpts().CPlusPlus14
800 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
801 : diag::ext_decltype_auto_type_specifier);
804 // Parse the expression
806 // C++11 [dcl.type.simple]p4:
807 // The operand of the decltype specifier is an unevaluated operand.
808 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
809 nullptr,/*IsDecltype=*/true);
811 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
812 return E->hasPlaceholderType() ? ExprError() : E;
814 if (Result.isInvalid()) {
815 DS.SetTypeSpecError();
816 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
817 EndLoc = ConsumeParen();
819 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
820 // Backtrack to get the location of the last token before the semi.
821 PP.RevertCachedTokens(2);
822 ConsumeToken(); // the semi.
823 EndLoc = ConsumeAnyToken();
824 assert(Tok.is(tok::semi));
826 EndLoc = Tok.getLocation();
832 Result = Actions.ActOnDecltypeExpression(Result.get());
837 if (T.getCloseLocation().isInvalid()) {
838 DS.SetTypeSpecError();
839 // FIXME: this should return the location of the last token
840 // that was consumed (by "consumeClose()")
841 return T.getCloseLocation();
844 if (Result.isInvalid()) {
845 DS.SetTypeSpecError();
846 return T.getCloseLocation();
849 EndLoc = T.getCloseLocation();
851 assert(!Result.isInvalid());
853 const char *PrevSpec = nullptr;
855 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
856 // Check for duplicate type specifiers (e.g. "int decltype(a)").
858 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
859 DiagID, Result.get(), Policy)
860 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
862 Diag(StartLoc, DiagID) << PrevSpec;
863 DS.SetTypeSpecError();
868 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
869 SourceLocation StartLoc,
870 SourceLocation EndLoc) {
871 // make sure we have a token we can turn into an annotation token
872 if (PP.isBacktrackEnabled())
873 PP.RevertCachedTokens(1);
877 Tok.setKind(tok::annot_decltype);
878 setExprAnnotation(Tok,
879 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
880 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
882 Tok.setAnnotationEndLoc(EndLoc);
883 Tok.setLocation(StartLoc);
884 PP.AnnotateCachedTokens(Tok);
887 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
888 assert(Tok.is(tok::kw___underlying_type) &&
889 "Not an underlying type specifier");
891 SourceLocation StartLoc = ConsumeToken();
892 BalancedDelimiterTracker T(*this, tok::l_paren);
893 if (T.expectAndConsume(diag::err_expected_lparen_after,
894 "__underlying_type", tok::r_paren)) {
898 TypeResult Result = ParseTypeName();
899 if (Result.isInvalid()) {
900 SkipUntil(tok::r_paren, StopAtSemi);
906 if (T.getCloseLocation().isInvalid())
909 const char *PrevSpec = nullptr;
911 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
912 DiagID, Result.get(),
913 Actions.getASTContext().getPrintingPolicy()))
914 Diag(StartLoc, DiagID) << PrevSpec;
915 DS.setTypeofParensRange(T.getRange());
918 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
919 /// class name or decltype-specifier. Note that we only check that the result
920 /// names a type; semantic analysis will need to verify that the type names a
921 /// class. The result is either a type or null, depending on whether a type
924 /// base-type-specifier: [C++11 class.derived]
925 /// class-or-decltype
926 /// class-or-decltype: [C++11 class.derived]
927 /// nested-name-specifier[opt] class-name
928 /// decltype-specifier
929 /// class-name: [C++ class.name]
931 /// simple-template-id
933 /// In C++98, instead of base-type-specifier, we have:
935 /// ::[opt] nested-name-specifier[opt] class-name
936 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
937 SourceLocation &EndLocation) {
938 // Ignore attempts to use typename
939 if (Tok.is(tok::kw_typename)) {
940 Diag(Tok, diag::err_expected_class_name_not_template)
941 << FixItHint::CreateRemoval(Tok.getLocation());
945 // Parse optional nested-name-specifier
947 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
949 BaseLoc = Tok.getLocation();
951 // Parse decltype-specifier
952 // tok == kw_decltype is just error recovery, it can only happen when SS
954 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
956 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
957 << FixItHint::CreateRemoval(SS.getRange());
958 // Fake up a Declarator to use with ActOnTypeName.
959 DeclSpec DS(AttrFactory);
961 EndLocation = ParseDecltypeSpecifier(DS);
963 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
964 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
967 // Check whether we have a template-id that names a type.
968 if (Tok.is(tok::annot_template_id)) {
969 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
970 if (TemplateId->Kind == TNK_Type_template ||
971 TemplateId->Kind == TNK_Dependent_template_name) {
972 AnnotateTemplateIdTokenAsType();
974 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
975 ParsedType Type = getTypeAnnotation(Tok);
976 EndLocation = Tok.getAnnotationEndLoc();
984 // Fall through to produce an error below.
987 if (Tok.isNot(tok::identifier)) {
988 Diag(Tok, diag::err_expected_class_name);
992 IdentifierInfo *Id = Tok.getIdentifierInfo();
993 SourceLocation IdLoc = ConsumeToken();
995 if (Tok.is(tok::less)) {
996 // It looks the user intended to write a template-id here, but the
997 // template-name was wrong. Try to fix that.
998 TemplateNameKind TNK = TNK_Type_template;
1000 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
1001 &SS, Template, TNK)) {
1002 Diag(IdLoc, diag::err_unknown_template_name)
1007 TemplateArgList TemplateArgs;
1008 SourceLocation LAngleLoc, RAngleLoc;
1009 ParseTemplateIdAfterTemplateName(nullptr, IdLoc, SS, true, LAngleLoc,
1010 TemplateArgs, RAngleLoc);
1014 // Form the template name
1015 UnqualifiedId TemplateName;
1016 TemplateName.setIdentifier(Id, IdLoc);
1018 // Parse the full template-id, then turn it into a type.
1019 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1020 TemplateName, true))
1022 if (TNK == TNK_Dependent_template_name)
1023 AnnotateTemplateIdTokenAsType();
1025 // If we didn't end up with a typename token, there's nothing more we
1027 if (Tok.isNot(tok::annot_typename))
1030 // Retrieve the type from the annotation token, consume that token, and
1032 EndLocation = Tok.getAnnotationEndLoc();
1033 ParsedType Type = getTypeAnnotation(Tok);
1038 // We have an identifier; check whether it is actually a type.
1039 IdentifierInfo *CorrectedII = nullptr;
1041 Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true, false, nullptr,
1042 /*IsCtorOrDtorName=*/false,
1043 /*NonTrivialTypeSourceInfo=*/true, &CorrectedII);
1045 Diag(IdLoc, diag::err_expected_class_name);
1049 // Consume the identifier.
1050 EndLocation = IdLoc;
1052 // Fake up a Declarator to use with ActOnTypeName.
1053 DeclSpec DS(AttrFactory);
1054 DS.SetRangeStart(IdLoc);
1055 DS.SetRangeEnd(EndLocation);
1056 DS.getTypeSpecScope() = SS;
1058 const char *PrevSpec = nullptr;
1060 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1061 Actions.getASTContext().getPrintingPolicy());
1063 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1064 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1067 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1068 while (Tok.isOneOf(tok::kw___single_inheritance,
1069 tok::kw___multiple_inheritance,
1070 tok::kw___virtual_inheritance)) {
1071 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1072 SourceLocation AttrNameLoc = ConsumeToken();
1073 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1074 AttributeList::AS_Keyword);
1078 /// Determine whether the following tokens are valid after a type-specifier
1079 /// which could be a standalone declaration. This will conservatively return
1080 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1081 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1082 // This switch enumerates the valid "follow" set for type-specifiers.
1083 switch (Tok.getKind()) {
1085 case tok::semi: // struct foo {...} ;
1086 case tok::star: // struct foo {...} * P;
1087 case tok::amp: // struct foo {...} & R = ...
1088 case tok::ampamp: // struct foo {...} && R = ...
1089 case tok::identifier: // struct foo {...} V ;
1090 case tok::r_paren: //(struct foo {...} ) {4}
1091 case tok::annot_cxxscope: // struct foo {...} a:: b;
1092 case tok::annot_typename: // struct foo {...} a ::b;
1093 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1094 case tok::l_paren: // struct foo {...} ( x);
1095 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1096 case tok::kw_operator: // struct foo operator ++() {...}
1097 case tok::kw___declspec: // struct foo {...} __declspec(...)
1098 case tok::l_square: // void f(struct f [ 3])
1099 case tok::ellipsis: // void f(struct f ... [Ns])
1100 // FIXME: we should emit semantic diagnostic when declaration
1101 // attribute is in type attribute position.
1102 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1103 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1104 // struct foo {...} _Pragma(section(...));
1105 case tok::annot_pragma_ms_pragma:
1106 // struct foo {...} _Pragma(vtordisp(pop));
1107 case tok::annot_pragma_ms_vtordisp:
1108 // struct foo {...} _Pragma(pointers_to_members(...));
1109 case tok::annot_pragma_ms_pointers_to_members:
1112 return CouldBeBitfield; // enum E { ... } : 2;
1113 // Microsoft compatibility
1114 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1115 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1116 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1117 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1118 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1119 // We will diagnose these calling-convention specifiers on non-function
1120 // declarations later, so claim they are valid after a type specifier.
1121 return getLangOpts().MicrosoftExt;
1123 case tok::kw_const: // struct foo {...} const x;
1124 case tok::kw_volatile: // struct foo {...} volatile x;
1125 case tok::kw_restrict: // struct foo {...} restrict x;
1126 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1127 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1128 // Function specifiers
1129 // Note, no 'explicit'. An explicit function must be either a conversion
1130 // operator or a constructor. Either way, it can't have a return type.
1131 case tok::kw_inline: // struct foo inline f();
1132 case tok::kw_virtual: // struct foo virtual f();
1133 case tok::kw_friend: // struct foo friend f();
1134 // Storage-class specifiers
1135 case tok::kw_static: // struct foo {...} static x;
1136 case tok::kw_extern: // struct foo {...} extern x;
1137 case tok::kw_typedef: // struct foo {...} typedef x;
1138 case tok::kw_register: // struct foo {...} register x;
1139 case tok::kw_auto: // struct foo {...} auto x;
1140 case tok::kw_mutable: // struct foo {...} mutable x;
1141 case tok::kw_thread_local: // struct foo {...} thread_local x;
1142 case tok::kw_constexpr: // struct foo {...} constexpr x;
1143 // As shown above, type qualifiers and storage class specifiers absolutely
1144 // can occur after class specifiers according to the grammar. However,
1145 // almost no one actually writes code like this. If we see one of these,
1146 // it is much more likely that someone missed a semi colon and the
1147 // type/storage class specifier we're seeing is part of the *next*
1148 // intended declaration, as in:
1150 // struct foo { ... }
1153 // We'd really like to emit a missing semicolon error instead of emitting
1154 // an error on the 'int' saying that you can't have two type specifiers in
1155 // the same declaration of X. Because of this, we look ahead past this
1156 // token to see if it's a type specifier. If so, we know the code is
1157 // otherwise invalid, so we can produce the expected semi error.
1158 if (!isKnownToBeTypeSpecifier(NextToken()))
1161 case tok::r_brace: // struct bar { struct foo {...} }
1162 // Missing ';' at end of struct is accepted as an extension in C mode.
1163 if (!getLangOpts().CPlusPlus)
1167 // template<class T = class X>
1168 return getLangOpts().CPlusPlus;
1173 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1174 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1175 /// until we reach the start of a definition or see a token that
1176 /// cannot start a definition.
1178 /// class-specifier: [C++ class]
1179 /// class-head '{' member-specification[opt] '}'
1180 /// class-head '{' member-specification[opt] '}' attributes[opt]
1182 /// class-key identifier[opt] base-clause[opt]
1183 /// class-key nested-name-specifier identifier base-clause[opt]
1184 /// class-key nested-name-specifier[opt] simple-template-id
1185 /// base-clause[opt]
1186 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1187 /// [GNU] class-key attributes[opt] nested-name-specifier
1188 /// identifier base-clause[opt]
1189 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1190 /// simple-template-id base-clause[opt]
1196 /// elaborated-type-specifier: [C++ dcl.type.elab]
1197 /// class-key ::[opt] nested-name-specifier[opt] identifier
1198 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1199 /// simple-template-id
1201 /// Note that the C++ class-specifier and elaborated-type-specifier,
1202 /// together, subsume the C99 struct-or-union-specifier:
1204 /// struct-or-union-specifier: [C99 6.7.2.1]
1205 /// struct-or-union identifier[opt] '{' struct-contents '}'
1206 /// struct-or-union identifier
1207 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1208 /// '}' attributes[opt]
1209 /// [GNU] struct-or-union attributes[opt] identifier
1210 /// struct-or-union:
1213 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1214 SourceLocation StartLoc, DeclSpec &DS,
1215 const ParsedTemplateInfo &TemplateInfo,
1217 bool EnteringContext, DeclSpecContext DSC,
1218 ParsedAttributesWithRange &Attributes) {
1219 DeclSpec::TST TagType;
1220 if (TagTokKind == tok::kw_struct)
1221 TagType = DeclSpec::TST_struct;
1222 else if (TagTokKind == tok::kw___interface)
1223 TagType = DeclSpec::TST_interface;
1224 else if (TagTokKind == tok::kw_class)
1225 TagType = DeclSpec::TST_class;
1227 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1228 TagType = DeclSpec::TST_union;
1231 if (Tok.is(tok::code_completion)) {
1232 // Code completion for a struct, class, or union name.
1233 Actions.CodeCompleteTag(getCurScope(), TagType);
1234 return cutOffParsing();
1237 // C++03 [temp.explicit] 14.7.2/8:
1238 // The usual access checking rules do not apply to names used to specify
1239 // explicit instantiations.
1241 // As an extension we do not perform access checking on the names used to
1242 // specify explicit specializations either. This is important to allow
1243 // specializing traits classes for private types.
1245 // Note that we don't suppress if this turns out to be an elaborated
1247 bool shouldDelayDiagsInTag =
1248 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1249 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1250 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1252 ParsedAttributesWithRange attrs(AttrFactory);
1253 // If attributes exist after tag, parse them.
1254 MaybeParseGNUAttributes(attrs);
1255 MaybeParseMicrosoftDeclSpecs(attrs);
1257 // Parse inheritance specifiers.
1258 if (Tok.isOneOf(tok::kw___single_inheritance,
1259 tok::kw___multiple_inheritance,
1260 tok::kw___virtual_inheritance))
1261 ParseMicrosoftInheritanceClassAttributes(attrs);
1263 // If C++0x attributes exist here, parse them.
1264 // FIXME: Are we consistent with the ordering of parsing of different
1265 // styles of attributes?
1266 MaybeParseCXX11Attributes(attrs);
1268 // Source location used by FIXIT to insert misplaced
1270 SourceLocation AttrFixitLoc = Tok.getLocation();
1272 if (TagType == DeclSpec::TST_struct &&
1273 Tok.isNot(tok::identifier) &&
1274 !Tok.isAnnotation() &&
1275 Tok.getIdentifierInfo() &&
1276 Tok.isOneOf(tok::kw___is_abstract,
1277 tok::kw___is_arithmetic,
1279 tok::kw___is_assignable,
1280 tok::kw___is_base_of,
1282 tok::kw___is_complete_type,
1283 tok::kw___is_compound,
1285 tok::kw___is_constructible,
1286 tok::kw___is_convertible,
1287 tok::kw___is_convertible_to,
1288 tok::kw___is_destructible,
1291 tok::kw___is_floating_point,
1293 tok::kw___is_function,
1294 tok::kw___is_fundamental,
1295 tok::kw___is_integral,
1296 tok::kw___is_interface_class,
1297 tok::kw___is_literal,
1298 tok::kw___is_lvalue_expr,
1299 tok::kw___is_lvalue_reference,
1300 tok::kw___is_member_function_pointer,
1301 tok::kw___is_member_object_pointer,
1302 tok::kw___is_member_pointer,
1303 tok::kw___is_nothrow_assignable,
1304 tok::kw___is_nothrow_constructible,
1305 tok::kw___is_nothrow_destructible,
1306 tok::kw___is_object,
1308 tok::kw___is_pointer,
1309 tok::kw___is_polymorphic,
1310 tok::kw___is_reference,
1311 tok::kw___is_rvalue_expr,
1312 tok::kw___is_rvalue_reference,
1314 tok::kw___is_scalar,
1315 tok::kw___is_sealed,
1316 tok::kw___is_signed,
1317 tok::kw___is_standard_layout,
1318 tok::kw___is_trivial,
1319 tok::kw___is_trivially_assignable,
1320 tok::kw___is_trivially_constructible,
1321 tok::kw___is_trivially_copyable,
1323 tok::kw___is_unsigned,
1325 tok::kw___is_volatile))
1326 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1327 // name of struct templates, but some are keywords in GCC >= 4.3
1328 // and Clang. Therefore, when we see the token sequence "struct
1329 // X", make X into a normal identifier rather than a keyword, to
1330 // allow libstdc++ 4.2 and libc++ to work properly.
1331 TryKeywordIdentFallback(true);
1333 struct PreserveAtomicIdentifierInfoRAII {
1334 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1335 : AtomicII(nullptr) {
1338 assert(Tok.is(tok::kw__Atomic));
1339 AtomicII = Tok.getIdentifierInfo();
1340 AtomicII->revertTokenIDToIdentifier();
1341 Tok.setKind(tok::identifier);
1343 ~PreserveAtomicIdentifierInfoRAII() {
1346 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1348 IdentifierInfo *AtomicII;
1351 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1352 // implementation for VS2013 uses _Atomic as an identifier for one of the
1353 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1354 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1355 // use '_Atomic' in its own header files.
1356 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1357 Tok.is(tok::kw__Atomic) &&
1358 TagType == DeclSpec::TST_struct;
1359 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1360 Tok, ShouldChangeAtomicToIdentifier);
1362 // Parse the (optional) nested-name-specifier.
1363 CXXScopeSpec &SS = DS.getTypeSpecScope();
1364 if (getLangOpts().CPlusPlus) {
1365 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1366 // is a base-specifier-list.
1367 ColonProtectionRAIIObject X(*this);
1370 bool HasValidSpec = true;
1371 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
1372 DS.SetTypeSpecError();
1373 HasValidSpec = false;
1376 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1377 Diag(Tok, diag::err_expected) << tok::identifier;
1378 HasValidSpec = false;
1384 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1386 // Parse the (optional) class name or simple-template-id.
1387 IdentifierInfo *Name = nullptr;
1388 SourceLocation NameLoc;
1389 TemplateIdAnnotation *TemplateId = nullptr;
1390 if (Tok.is(tok::identifier)) {
1391 Name = Tok.getIdentifierInfo();
1392 NameLoc = ConsumeToken();
1394 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1395 // The name was supposed to refer to a template, but didn't.
1396 // Eat the template argument list and try to continue parsing this as
1397 // a class (or template thereof).
1398 TemplateArgList TemplateArgs;
1399 SourceLocation LAngleLoc, RAngleLoc;
1400 if (ParseTemplateIdAfterTemplateName(
1401 nullptr, NameLoc, SS, true, LAngleLoc, TemplateArgs, RAngleLoc)) {
1402 // We couldn't parse the template argument list at all, so don't
1403 // try to give any location information for the list.
1404 LAngleLoc = RAngleLoc = SourceLocation();
1407 Diag(NameLoc, diag::err_explicit_spec_non_template)
1408 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1409 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1411 // Strip off the last template parameter list if it was empty, since
1412 // we've removed its template argument list.
1413 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1414 if (TemplateParams->size() > 1) {
1415 TemplateParams->pop_back();
1417 TemplateParams = nullptr;
1418 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1419 = ParsedTemplateInfo::NonTemplate;
1421 } else if (TemplateInfo.Kind
1422 == ParsedTemplateInfo::ExplicitInstantiation) {
1423 // Pretend this is just a forward declaration.
1424 TemplateParams = nullptr;
1425 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1426 = ParsedTemplateInfo::NonTemplate;
1427 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1429 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1433 } else if (Tok.is(tok::annot_template_id)) {
1434 TemplateId = takeTemplateIdAnnotation(Tok);
1435 NameLoc = ConsumeToken();
1437 if (TemplateId->Kind != TNK_Type_template &&
1438 TemplateId->Kind != TNK_Dependent_template_name) {
1439 // The template-name in the simple-template-id refers to
1440 // something other than a class template. Give an appropriate
1441 // error message and skip to the ';'.
1442 SourceRange Range(NameLoc);
1443 if (SS.isNotEmpty())
1444 Range.setBegin(SS.getBeginLoc());
1446 // FIXME: Name may be null here.
1447 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1448 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1450 DS.SetTypeSpecError();
1451 SkipUntil(tok::semi, StopBeforeMatch);
1456 // There are four options here.
1457 // - If we are in a trailing return type, this is always just a reference,
1458 // and we must not try to parse a definition. For instance,
1459 // [] () -> struct S { };
1460 // does not define a type.
1461 // - If we have 'struct foo {...', 'struct foo :...',
1462 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1463 // - If we have 'struct foo;', then this is either a forward declaration
1464 // or a friend declaration, which have to be treated differently.
1465 // - Otherwise we have something like 'struct foo xyz', a reference.
1467 // We also detect these erroneous cases to provide better diagnostic for
1468 // C++11 attributes parsing.
1469 // - attributes follow class name:
1470 // struct foo [[]] {};
1471 // - attributes appear before or after 'final':
1472 // struct foo [[]] final [[]] {};
1474 // However, in type-specifier-seq's, things look like declarations but are
1475 // just references, e.g.
1478 // &T::operator struct s;
1479 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
1481 // If there are attributes after class name, parse them.
1482 MaybeParseCXX11Attributes(Attributes);
1484 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1485 Sema::TagUseKind TUK;
1486 if (DSC == DSC_trailing)
1487 TUK = Sema::TUK_Reference;
1488 else if (Tok.is(tok::l_brace) ||
1489 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1490 (isCXX11FinalKeyword() &&
1491 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1492 if (DS.isFriendSpecified()) {
1493 // C++ [class.friend]p2:
1494 // A class shall not be defined in a friend declaration.
1495 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1496 << SourceRange(DS.getFriendSpecLoc());
1498 // Skip everything up to the semicolon, so that this looks like a proper
1499 // friend class (or template thereof) declaration.
1500 SkipUntil(tok::semi, StopBeforeMatch);
1501 TUK = Sema::TUK_Friend;
1503 // Okay, this is a class definition.
1504 TUK = Sema::TUK_Definition;
1506 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1507 NextToken().is(tok::kw_alignas))) {
1508 // We can't tell if this is a definition or reference
1509 // until we skipped the 'final' and C++11 attribute specifiers.
1510 TentativeParsingAction PA(*this);
1512 // Skip the 'final' keyword.
1515 // Skip C++11 attribute specifiers.
1517 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1519 if (!SkipUntil(tok::r_square, StopAtSemi))
1521 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1524 if (!SkipUntil(tok::r_paren, StopAtSemi))
1531 if (Tok.isOneOf(tok::l_brace, tok::colon))
1532 TUK = Sema::TUK_Definition;
1534 TUK = Sema::TUK_Reference;
1537 } else if (!isTypeSpecifier(DSC) &&
1538 (Tok.is(tok::semi) ||
1539 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1540 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1541 if (Tok.isNot(tok::semi)) {
1542 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1543 // A semicolon was missing after this declaration. Diagnose and recover.
1544 ExpectAndConsume(tok::semi, diag::err_expected_after,
1545 DeclSpec::getSpecifierName(TagType, PPol));
1547 Tok.setKind(tok::semi);
1550 TUK = Sema::TUK_Reference;
1552 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1553 // to caller to handle.
1554 if (TUK != Sema::TUK_Reference) {
1555 // If this is not a reference, then the only possible
1556 // valid place for C++11 attributes to appear here
1557 // is between class-key and class-name. If there are
1558 // any attributes after class-name, we try a fixit to move
1559 // them to the right place.
1560 SourceRange AttrRange = Attributes.Range;
1561 if (AttrRange.isValid()) {
1562 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1564 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1565 CharSourceRange(AttrRange, true))
1566 << FixItHint::CreateRemoval(AttrRange);
1568 // Recover by adding misplaced attributes to the attribute list
1569 // of the class so they can be applied on the class later.
1570 attrs.takeAllFrom(Attributes);
1574 // If this is an elaborated type specifier, and we delayed
1575 // diagnostics before, just merge them into the current pool.
1576 if (shouldDelayDiagsInTag) {
1577 diagsFromTag.done();
1578 if (TUK == Sema::TUK_Reference)
1579 diagsFromTag.redelay();
1582 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1583 TUK != Sema::TUK_Definition)) {
1584 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1585 // We have a declaration or reference to an anonymous class.
1586 Diag(StartLoc, diag::err_anon_type_definition)
1587 << DeclSpec::getSpecifierName(TagType, Policy);
1590 // If we are parsing a definition and stop at a base-clause, continue on
1591 // until the semicolon. Continuing from the comma will just trick us into
1592 // thinking we are seeing a variable declaration.
1593 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1594 SkipUntil(tok::semi, StopBeforeMatch);
1596 SkipUntil(tok::comma, StopAtSemi);
1600 // Create the tag portion of the class or class template.
1601 DeclResult TagOrTempResult = true; // invalid
1602 TypeResult TypeResult = true; // invalid
1605 Sema::SkipBodyInfo SkipBody;
1607 // Explicit specialization, class template partial specialization,
1608 // or explicit instantiation.
1609 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1610 TemplateId->NumArgs);
1611 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1612 TUK == Sema::TUK_Declaration) {
1613 // This is an explicit instantiation of a class template.
1614 ProhibitAttributes(attrs);
1617 = Actions.ActOnExplicitInstantiation(getCurScope(),
1618 TemplateInfo.ExternLoc,
1619 TemplateInfo.TemplateLoc,
1623 TemplateId->Template,
1624 TemplateId->TemplateNameLoc,
1625 TemplateId->LAngleLoc,
1627 TemplateId->RAngleLoc,
1630 // Friend template-ids are treated as references unless
1631 // they have template headers, in which case they're ill-formed
1632 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1633 // We diagnose this error in ActOnClassTemplateSpecialization.
1634 } else if (TUK == Sema::TUK_Reference ||
1635 (TUK == Sema::TUK_Friend &&
1636 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1637 ProhibitAttributes(attrs);
1638 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1640 TemplateId->TemplateKWLoc,
1641 TemplateId->Template,
1642 TemplateId->TemplateNameLoc,
1643 TemplateId->LAngleLoc,
1645 TemplateId->RAngleLoc);
1647 // This is an explicit specialization or a class template
1648 // partial specialization.
1649 TemplateParameterLists FakedParamLists;
1650 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1651 // This looks like an explicit instantiation, because we have
1654 // template class Foo<X>
1656 // but it actually has a definition. Most likely, this was
1657 // meant to be an explicit specialization, but the user forgot
1658 // the '<>' after 'template'.
1659 // It this is friend declaration however, since it cannot have a
1660 // template header, it is most likely that the user meant to
1661 // remove the 'template' keyword.
1662 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1663 "Expected a definition here");
1665 if (TUK == Sema::TUK_Friend) {
1666 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1667 TemplateParams = nullptr;
1669 SourceLocation LAngleLoc =
1670 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1671 Diag(TemplateId->TemplateNameLoc,
1672 diag::err_explicit_instantiation_with_definition)
1673 << SourceRange(TemplateInfo.TemplateLoc)
1674 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1676 // Create a fake template parameter list that contains only
1677 // "template<>", so that we treat this construct as a class
1678 // template specialization.
1679 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1680 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1681 LAngleLoc, nullptr));
1682 TemplateParams = &FakedParamLists;
1686 // Build the class template specialization.
1687 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1688 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1689 *TemplateId, attrs.getList(),
1690 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1692 TemplateParams ? TemplateParams->size() : 0),
1695 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1696 TUK == Sema::TUK_Declaration) {
1697 // Explicit instantiation of a member of a class template
1698 // specialization, e.g.,
1700 // template struct Outer<int>::Inner;
1702 ProhibitAttributes(attrs);
1705 = Actions.ActOnExplicitInstantiation(getCurScope(),
1706 TemplateInfo.ExternLoc,
1707 TemplateInfo.TemplateLoc,
1708 TagType, StartLoc, SS, Name,
1709 NameLoc, attrs.getList());
1710 } else if (TUK == Sema::TUK_Friend &&
1711 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1712 ProhibitAttributes(attrs);
1715 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1716 TagType, StartLoc, SS,
1717 Name, NameLoc, attrs.getList(),
1718 MultiTemplateParamsArg(
1719 TemplateParams? &(*TemplateParams)[0]
1721 TemplateParams? TemplateParams->size() : 0));
1723 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1724 ProhibitAttributes(attrs);
1726 if (TUK == Sema::TUK_Definition &&
1727 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1728 // If the declarator-id is not a template-id, issue a diagnostic and
1729 // recover by ignoring the 'template' keyword.
1730 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1731 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1732 TemplateParams = nullptr;
1735 bool IsDependent = false;
1737 // Don't pass down template parameter lists if this is just a tag
1738 // reference. For example, we don't need the template parameters here:
1739 // template <class T> class A *makeA(T t);
1740 MultiTemplateParamsArg TParams;
1741 if (TUK != Sema::TUK_Reference && TemplateParams)
1743 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1745 handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
1747 // Declaration or definition of a class type
1748 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1749 SS, Name, NameLoc, attrs.getList(), AS,
1750 DS.getModulePrivateSpecLoc(),
1751 TParams, Owned, IsDependent,
1752 SourceLocation(), false,
1753 clang::TypeResult(),
1754 DSC == DSC_type_specifier,
1757 // If ActOnTag said the type was dependent, try again with the
1758 // less common call.
1760 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1761 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1762 SS, Name, StartLoc, NameLoc);
1766 // If there is a body, parse it and inform the actions module.
1767 if (TUK == Sema::TUK_Definition) {
1768 assert(Tok.is(tok::l_brace) ||
1769 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1770 isCXX11FinalKeyword());
1771 if (SkipBody.ShouldSkip)
1772 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1773 TagOrTempResult.get());
1774 else if (getLangOpts().CPlusPlus)
1775 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1776 TagOrTempResult.get());
1778 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1781 const char *PrevSpec = nullptr;
1784 if (!TypeResult.isInvalid()) {
1785 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1786 NameLoc.isValid() ? NameLoc : StartLoc,
1787 PrevSpec, DiagID, TypeResult.get(), Policy);
1788 } else if (!TagOrTempResult.isInvalid()) {
1789 Result = DS.SetTypeSpecType(TagType, StartLoc,
1790 NameLoc.isValid() ? NameLoc : StartLoc,
1791 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1794 DS.SetTypeSpecError();
1799 Diag(StartLoc, DiagID) << PrevSpec;
1801 // At this point, we've successfully parsed a class-specifier in 'definition'
1802 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1803 // going to look at what comes after it to improve error recovery. If an
1804 // impossible token occurs next, we assume that the programmer forgot a ; at
1805 // the end of the declaration and recover that way.
1807 // Also enforce C++ [temp]p3:
1808 // In a template-declaration which defines a class, no declarator
1811 // After a type-specifier, we don't expect a semicolon. This only happens in
1812 // C, since definitions are not permitted in this context in C++.
1813 if (TUK == Sema::TUK_Definition &&
1814 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1815 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1816 if (Tok.isNot(tok::semi)) {
1817 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1818 ExpectAndConsume(tok::semi, diag::err_expected_after,
1819 DeclSpec::getSpecifierName(TagType, PPol));
1820 // Push this token back into the preprocessor and change our current token
1821 // to ';' so that the rest of the code recovers as though there were an
1822 // ';' after the definition.
1824 Tok.setKind(tok::semi);
1829 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1831 /// base-clause : [C++ class.derived]
1832 /// ':' base-specifier-list
1833 /// base-specifier-list:
1834 /// base-specifier '...'[opt]
1835 /// base-specifier-list ',' base-specifier '...'[opt]
1836 void Parser::ParseBaseClause(Decl *ClassDecl) {
1837 assert(Tok.is(tok::colon) && "Not a base clause");
1840 // Build up an array of parsed base specifiers.
1841 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1844 // Parse a base-specifier.
1845 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1846 if (Result.isInvalid()) {
1847 // Skip the rest of this base specifier, up until the comma or
1849 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
1851 // Add this to our array of base specifiers.
1852 BaseInfo.push_back(Result.get());
1855 // If the next token is a comma, consume it and keep reading
1857 if (!TryConsumeToken(tok::comma))
1861 // Attach the base specifiers
1862 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
1865 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1866 /// one entry in the base class list of a class specifier, for example:
1867 /// class foo : public bar, virtual private baz {
1868 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1870 /// base-specifier: [C++ class.derived]
1871 /// attribute-specifier-seq[opt] base-type-specifier
1872 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
1873 /// base-type-specifier
1874 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
1875 /// base-type-specifier
1876 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1877 bool IsVirtual = false;
1878 SourceLocation StartLoc = Tok.getLocation();
1880 ParsedAttributesWithRange Attributes(AttrFactory);
1881 MaybeParseCXX11Attributes(Attributes);
1883 // Parse the 'virtual' keyword.
1884 if (TryConsumeToken(tok::kw_virtual))
1887 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1889 // Parse an (optional) access specifier.
1890 AccessSpecifier Access = getAccessSpecifierIfPresent();
1891 if (Access != AS_none)
1894 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1896 // Parse the 'virtual' keyword (again!), in case it came after the
1897 // access specifier.
1898 if (Tok.is(tok::kw_virtual)) {
1899 SourceLocation VirtualLoc = ConsumeToken();
1901 // Complain about duplicate 'virtual'
1902 Diag(VirtualLoc, diag::err_dup_virtual)
1903 << FixItHint::CreateRemoval(VirtualLoc);
1909 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1911 // Parse the class-name.
1913 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1914 // implementation for VS2013 uses _Atomic as an identifier for one of the
1915 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
1916 // parsing the class-name for a base specifier.
1917 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
1918 NextToken().is(tok::less))
1919 Tok.setKind(tok::identifier);
1921 SourceLocation EndLocation;
1922 SourceLocation BaseLoc;
1923 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1924 if (BaseType.isInvalid())
1927 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1928 // actually part of the base-specifier-list grammar productions, but we
1929 // parse it here for convenience.
1930 SourceLocation EllipsisLoc;
1931 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1933 // Find the complete source range for the base-specifier.
1934 SourceRange Range(StartLoc, EndLocation);
1936 // Notify semantic analysis that we have parsed a complete
1938 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
1939 Access, BaseType.get(), BaseLoc,
1943 /// getAccessSpecifierIfPresent - Determine whether the next token is
1944 /// a C++ access-specifier.
1946 /// access-specifier: [C++ class.derived]
1950 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1951 switch (Tok.getKind()) {
1952 default: return AS_none;
1953 case tok::kw_private: return AS_private;
1954 case tok::kw_protected: return AS_protected;
1955 case tok::kw_public: return AS_public;
1959 /// \brief If the given declarator has any parts for which parsing has to be
1960 /// delayed, e.g., default arguments or an exception-specification, create a
1961 /// late-parsed method declaration record to handle the parsing at the end of
1962 /// the class definition.
1963 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1965 DeclaratorChunk::FunctionTypeInfo &FTI
1966 = DeclaratorInfo.getFunctionTypeInfo();
1967 // If there was a late-parsed exception-specification, we'll need a
1969 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
1971 if (!NeedLateParse) {
1972 // Look ahead to see if there are any default args
1973 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
1974 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
1975 if (Param->hasUnparsedDefaultArg()) {
1976 NeedLateParse = true;
1982 if (NeedLateParse) {
1983 // Push this method onto the stack of late-parsed method
1985 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1986 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1987 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1989 // Stash the exception-specification tokens in the late-pased method.
1990 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
1991 FTI.ExceptionSpecTokens = nullptr;
1993 // Push tokens for each parameter. Those that do not have
1994 // defaults will be NULL.
1995 LateMethod->DefaultArgs.reserve(FTI.NumParams);
1996 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
1997 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
1998 FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
2002 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2008 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2009 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2010 return VirtSpecifiers::VS_None;
2012 IdentifierInfo *II = Tok.getIdentifierInfo();
2014 // Initialize the contextual keywords.
2016 Ident_final = &PP.getIdentifierTable().get("final");
2017 if (getLangOpts().MicrosoftExt)
2018 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2019 Ident_override = &PP.getIdentifierTable().get("override");
2022 if (II == Ident_override)
2023 return VirtSpecifiers::VS_Override;
2025 if (II == Ident_sealed)
2026 return VirtSpecifiers::VS_Sealed;
2028 if (II == Ident_final)
2029 return VirtSpecifiers::VS_Final;
2031 return VirtSpecifiers::VS_None;
2034 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2036 /// virt-specifier-seq:
2038 /// virt-specifier-seq virt-specifier
2039 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2041 SourceLocation FriendLoc) {
2043 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2044 if (Specifier == VirtSpecifiers::VS_None)
2047 if (FriendLoc.isValid()) {
2048 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2049 << VirtSpecifiers::getSpecifierName(Specifier)
2050 << FixItHint::CreateRemoval(Tok.getLocation())
2051 << SourceRange(FriendLoc, FriendLoc);
2056 // C++ [class.mem]p8:
2057 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2058 const char *PrevSpec = nullptr;
2059 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2060 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2062 << FixItHint::CreateRemoval(Tok.getLocation());
2064 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2065 Specifier == VirtSpecifiers::VS_Sealed)) {
2066 Diag(Tok.getLocation(), diag::err_override_control_interface)
2067 << VirtSpecifiers::getSpecifierName(Specifier);
2068 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2069 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2071 Diag(Tok.getLocation(),
2072 getLangOpts().CPlusPlus11
2073 ? diag::warn_cxx98_compat_override_control_keyword
2074 : diag::ext_override_control_keyword)
2075 << VirtSpecifiers::getSpecifierName(Specifier);
2081 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2082 /// 'final' or Microsoft 'sealed' contextual keyword.
2083 bool Parser::isCXX11FinalKeyword() const {
2084 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2085 return Specifier == VirtSpecifiers::VS_Final ||
2086 Specifier == VirtSpecifiers::VS_Sealed;
2089 /// \brief Parse a C++ member-declarator up to, but not including, the optional
2090 /// brace-or-equal-initializer or pure-specifier.
2091 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2092 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2093 LateParsedAttrList &LateParsedAttrs) {
2094 // member-declarator:
2095 // declarator pure-specifier[opt]
2096 // declarator brace-or-equal-initializer[opt]
2097 // identifier[opt] ':' constant-expression
2098 if (Tok.isNot(tok::colon))
2099 ParseDeclarator(DeclaratorInfo);
2101 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2103 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2104 assert(DeclaratorInfo.isPastIdentifier() &&
2105 "don't know where identifier would go yet?");
2106 BitfieldSize = ParseConstantExpression();
2107 if (BitfieldSize.isInvalid())
2108 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2110 ParseOptionalCXX11VirtSpecifierSeq(
2111 VS, getCurrentClass().IsInterface,
2112 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2114 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2117 // If a simple-asm-expr is present, parse it.
2118 if (Tok.is(tok::kw_asm)) {
2120 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2121 if (AsmLabel.isInvalid())
2122 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2124 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2125 DeclaratorInfo.SetRangeEnd(Loc);
2128 // If attributes exist after the declarator, but before an '{', parse them.
2129 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2131 // For compatibility with code written to older Clang, also accept a
2132 // virt-specifier *after* the GNU attributes.
2133 if (BitfieldSize.isUnset() && VS.isUnset()) {
2134 ParseOptionalCXX11VirtSpecifierSeq(
2135 VS, getCurrentClass().IsInterface,
2136 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2137 if (!VS.isUnset()) {
2138 // If we saw any GNU-style attributes that are known to GCC followed by a
2139 // virt-specifier, issue a GCC-compat warning.
2140 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2142 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2143 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2144 Attr = Attr->getNext();
2146 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2150 // If this has neither a name nor a bit width, something has gone seriously
2151 // wrong. Skip until the semi-colon or }.
2152 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2153 // If so, skip until the semi-colon or a }.
2154 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2160 /// \brief Look for declaration specifiers possibly occurring after C++11
2161 /// virt-specifier-seq and diagnose them.
2162 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2164 VirtSpecifiers &VS) {
2165 DeclSpec DS(AttrFactory);
2167 // GNU-style and C++11 attributes are not allowed here, but they will be
2168 // handled by the caller. Diagnose everything else.
2169 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, false);
2170 D.ExtendWithDeclSpec(DS);
2172 if (D.isFunctionDeclarator()) {
2173 auto &Function = D.getFunctionTypeInfo();
2174 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2175 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2176 const char *FixItName,
2177 SourceLocation SpecLoc,
2178 unsigned* QualifierLoc) {
2179 FixItHint Insertion;
2180 if (DS.getTypeQualifiers() & TypeQual) {
2181 if (!(Function.TypeQuals & TypeQual)) {
2182 std::string Name(FixItName);
2184 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name.c_str());
2185 Function.TypeQuals |= TypeQual;
2186 *QualifierLoc = SpecLoc.getRawEncoding();
2188 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2190 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2191 << FixItHint::CreateRemoval(SpecLoc)
2195 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2196 &Function.ConstQualifierLoc);
2197 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2198 &Function.VolatileQualifierLoc);
2199 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2200 &Function.RestrictQualifierLoc);
2203 // Parse ref-qualifiers.
2204 bool RefQualifierIsLValueRef = true;
2205 SourceLocation RefQualifierLoc;
2206 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2207 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2208 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2209 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2210 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2212 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2213 << (RefQualifierIsLValueRef ? "&" : "&&")
2214 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2215 << FixItHint::CreateRemoval(RefQualifierLoc)
2217 D.SetRangeEnd(RefQualifierLoc);
2222 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2224 /// member-declaration:
2225 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2226 /// function-definition ';'[opt]
2227 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2228 /// using-declaration [TODO]
2229 /// [C++0x] static_assert-declaration
2230 /// template-declaration
2231 /// [GNU] '__extension__' member-declaration
2233 /// member-declarator-list:
2234 /// member-declarator
2235 /// member-declarator-list ',' member-declarator
2237 /// member-declarator:
2238 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2239 /// declarator constant-initializer[opt]
2240 /// [C++11] declarator brace-or-equal-initializer[opt]
2241 /// identifier[opt] ':' constant-expression
2243 /// virt-specifier-seq:
2245 /// virt-specifier-seq virt-specifier
2255 /// constant-initializer:
2256 /// '=' constant-expression
2258 Parser::DeclGroupPtrTy
2259 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2260 AttributeList *AccessAttrs,
2261 const ParsedTemplateInfo &TemplateInfo,
2262 ParsingDeclRAIIObject *TemplateDiags) {
2263 if (Tok.is(tok::at)) {
2264 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2265 Diag(Tok, diag::err_at_defs_cxx);
2267 Diag(Tok, diag::err_at_in_class);
2270 SkipUntil(tok::r_brace, StopAtSemi);
2274 // Turn on colon protection early, while parsing declspec, although there is
2275 // nothing to protect there. It prevents from false errors if error recovery
2276 // incorrectly determines where the declspec ends, as in the example:
2277 // struct A { enum class B { C }; };
2279 // struct D { A::B : C; };
2280 ColonProtectionRAIIObject X(*this);
2282 // Access declarations.
2283 bool MalformedTypeSpec = false;
2284 if (!TemplateInfo.Kind &&
2285 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2286 if (TryAnnotateCXXScopeToken())
2287 MalformedTypeSpec = true;
2290 if (Tok.isNot(tok::annot_cxxscope))
2291 isAccessDecl = false;
2292 else if (NextToken().is(tok::identifier))
2293 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2295 isAccessDecl = NextToken().is(tok::kw_operator);
2298 // Collect the scope specifier token we annotated earlier.
2300 ParseOptionalCXXScopeSpecifier(SS, nullptr,
2301 /*EnteringContext=*/false);
2303 if (SS.isInvalid()) {
2304 SkipUntil(tok::semi);
2308 // Try to parse an unqualified-id.
2309 SourceLocation TemplateKWLoc;
2311 if (ParseUnqualifiedId(SS, false, true, true, nullptr, TemplateKWLoc,
2313 SkipUntil(tok::semi);
2317 // TODO: recover from mistakenly-qualified operator declarations.
2318 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2319 "access declaration")) {
2320 SkipUntil(tok::semi);
2324 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2326 /* HasUsingKeyword */ false, SourceLocation(), SS, Name,
2327 /* AttrList */ nullptr,
2328 /* HasTypenameKeyword */ false, SourceLocation())));
2332 // static_assert-declaration. A templated static_assert declaration is
2333 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2334 if (!TemplateInfo.Kind &&
2335 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2336 SourceLocation DeclEnd;
2337 return DeclGroupPtrTy::make(
2338 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2341 if (Tok.is(tok::kw_template)) {
2342 assert(!TemplateInfo.TemplateParams &&
2343 "Nested template improperly parsed?");
2344 SourceLocation DeclEnd;
2345 return DeclGroupPtrTy::make(
2346 DeclGroupRef(ParseDeclarationStartingWithTemplate(
2347 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
2350 // Handle: member-declaration ::= '__extension__' member-declaration
2351 if (Tok.is(tok::kw___extension__)) {
2352 // __extension__ silences extension warnings in the subexpression.
2353 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2355 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2356 TemplateInfo, TemplateDiags);
2359 ParsedAttributesWithRange attrs(AttrFactory);
2360 ParsedAttributesWithRange FnAttrs(AttrFactory);
2361 // Optional C++11 attribute-specifier
2362 MaybeParseCXX11Attributes(attrs);
2363 // We need to keep these attributes for future diagnostic
2364 // before they are taken over by declaration specifier.
2365 FnAttrs.addAll(attrs.getList());
2366 FnAttrs.Range = attrs.Range;
2368 MaybeParseMicrosoftAttributes(attrs);
2370 if (Tok.is(tok::kw_using)) {
2371 ProhibitAttributes(attrs);
2374 SourceLocation UsingLoc = ConsumeToken();
2376 if (Tok.is(tok::kw_namespace)) {
2377 Diag(UsingLoc, diag::err_using_namespace_in_class);
2378 SkipUntil(tok::semi, StopBeforeMatch);
2381 SourceLocation DeclEnd;
2382 // Otherwise, it must be a using-declaration or an alias-declaration.
2383 return DeclGroupPtrTy::make(DeclGroupRef(ParseUsingDeclaration(
2384 Declarator::MemberContext, TemplateInfo, UsingLoc, DeclEnd, AS)));
2387 // Hold late-parsed attributes so we can attach a Decl to them later.
2388 LateParsedAttrList CommonLateParsedAttrs;
2390 // decl-specifier-seq:
2391 // Parse the common declaration-specifiers piece.
2392 ParsingDeclSpec DS(*this, TemplateDiags);
2393 DS.takeAttributesFrom(attrs);
2394 if (MalformedTypeSpec)
2395 DS.SetTypeSpecError();
2397 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2398 &CommonLateParsedAttrs);
2400 // Turn off colon protection that was set for declspec.
2403 // If we had a free-standing type definition with a missing semicolon, we
2404 // may get this far before the problem becomes obvious.
2405 if (DS.hasTagDefinition() &&
2406 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2407 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2408 &CommonLateParsedAttrs))
2411 MultiTemplateParamsArg TemplateParams(
2412 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2414 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2416 if (TryConsumeToken(tok::semi)) {
2417 if (DS.isFriendSpecified())
2418 ProhibitAttributes(FnAttrs);
2420 RecordDecl *AnonRecord = nullptr;
2421 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2422 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2423 DS.complete(TheDecl);
2425 Decl* decls[] = {AnonRecord, TheDecl};
2426 return Actions.BuildDeclaratorGroup(decls, /*TypeMayContainAuto=*/false);
2428 return Actions.ConvertDeclToDeclGroup(TheDecl);
2431 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2434 // Hold late-parsed attributes so we can attach a Decl to them later.
2435 LateParsedAttrList LateParsedAttrs;
2437 SourceLocation EqualLoc;
2438 SourceLocation PureSpecLoc;
2440 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2441 if (Tok.isNot(tok::equal))
2444 auto &Zero = NextToken();
2445 SmallString<8> Buffer;
2446 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2447 PP.getSpelling(Zero, Buffer) != "0")
2450 auto &After = GetLookAheadToken(2);
2451 if (!After.isOneOf(tok::semi, tok::comma) &&
2452 !(AllowDefinition &&
2453 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2456 EqualLoc = ConsumeToken();
2457 PureSpecLoc = ConsumeToken();
2461 SmallVector<Decl *, 8> DeclsInGroup;
2462 ExprResult BitfieldSize;
2463 bool ExpectSemi = true;
2465 // Parse the first declarator.
2466 if (ParseCXXMemberDeclaratorBeforeInitializer(
2467 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2468 TryConsumeToken(tok::semi);
2472 // Check for a member function definition.
2473 if (BitfieldSize.isUnset()) {
2474 // MSVC permits pure specifier on inline functions defined at class scope.
2475 // Hence check for =0 before checking for function definition.
2476 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2477 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2479 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2480 // function-definition:
2482 // In C++11, a non-function declarator followed by an open brace is a
2483 // braced-init-list for an in-class member initialization, not an
2484 // erroneous function definition.
2485 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2486 DefinitionKind = FDK_Definition;
2487 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2488 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2489 DefinitionKind = FDK_Definition;
2490 } else if (Tok.is(tok::equal)) {
2491 const Token &KW = NextToken();
2492 if (KW.is(tok::kw_default))
2493 DefinitionKind = FDK_Defaulted;
2494 else if (KW.is(tok::kw_delete))
2495 DefinitionKind = FDK_Deleted;
2498 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2500 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2501 // to a friend declaration, that declaration shall be a definition.
2502 if (DeclaratorInfo.isFunctionDeclarator() &&
2503 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2504 // Diagnose attributes that appear before decl specifier:
2505 // [[]] friend int foo();
2506 ProhibitAttributes(FnAttrs);
2509 if (DefinitionKind != FDK_Declaration) {
2510 if (!DeclaratorInfo.isFunctionDeclarator()) {
2511 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2513 SkipUntil(tok::r_brace);
2515 // Consume the optional ';'
2516 TryConsumeToken(tok::semi);
2521 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2522 Diag(DeclaratorInfo.getIdentifierLoc(),
2523 diag::err_function_declared_typedef);
2525 // Recover by treating the 'typedef' as spurious.
2526 DS.ClearStorageClassSpecs();
2530 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2534 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2535 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2537 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2538 LateParsedAttrs[i]->addDecl(FunDecl);
2541 LateParsedAttrs.clear();
2543 // Consume the ';' - it's optional unless we have a delete or default
2544 if (Tok.is(tok::semi))
2545 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2547 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2551 // member-declarator-list:
2552 // member-declarator
2553 // member-declarator-list ',' member-declarator
2556 InClassInitStyle HasInClassInit = ICIS_NoInit;
2557 bool HasStaticInitializer = false;
2558 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2559 if (BitfieldSize.get()) {
2560 Diag(Tok, diag::err_bitfield_member_init);
2561 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2562 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2563 // It's a pure-specifier.
2564 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2565 // Parse it as an expression so that Sema can diagnose it.
2566 HasStaticInitializer = true;
2567 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2568 DeclSpec::SCS_static &&
2569 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2570 DeclSpec::SCS_typedef &&
2571 !DS.isFriendSpecified()) {
2572 // It's a default member initializer.
2573 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2575 HasStaticInitializer = true;
2579 // NOTE: If Sema is the Action module and declarator is an instance field,
2580 // this call will *not* return the created decl; It will return null.
2581 // See Sema::ActOnCXXMemberDeclarator for details.
2583 NamedDecl *ThisDecl = nullptr;
2584 if (DS.isFriendSpecified()) {
2585 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2586 // to a friend declaration, that declaration shall be a definition.
2588 // Diagnose attributes that appear in a friend member function declarator:
2589 // friend int foo [[]] ();
2590 SmallVector<SourceRange, 4> Ranges;
2591 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2592 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2593 E = Ranges.end(); I != E; ++I)
2594 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2596 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2599 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2603 VS, HasInClassInit);
2605 if (VarTemplateDecl *VT =
2606 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2607 // Re-direct this decl to refer to the templated decl so that we can
2609 ThisDecl = VT->getTemplatedDecl();
2611 if (ThisDecl && AccessAttrs)
2612 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2615 // Error recovery might have converted a non-static member into a static
2617 if (HasInClassInit != ICIS_NoInit &&
2618 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2619 DeclSpec::SCS_static) {
2620 HasInClassInit = ICIS_NoInit;
2621 HasStaticInitializer = true;
2624 if (ThisDecl && PureSpecLoc.isValid())
2625 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2627 // Handle the initializer.
2628 if (HasInClassInit != ICIS_NoInit) {
2629 // The initializer was deferred; parse it and cache the tokens.
2630 Diag(Tok, getLangOpts().CPlusPlus11
2631 ? diag::warn_cxx98_compat_nonstatic_member_init
2632 : diag::ext_nonstatic_member_init);
2634 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2635 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2636 // declarator is followed by an initializer.
2638 // A brace-or-equal-initializer for a member-declarator is not an
2639 // initializer in the grammar, so this is ill-formed.
2640 Diag(Tok, diag::err_incomplete_array_member_init);
2641 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2643 // Avoid later warnings about a class member of incomplete type.
2645 ThisDecl->setInvalidDecl();
2647 ParseCXXNonStaticMemberInitializer(ThisDecl);
2648 } else if (HasStaticInitializer) {
2649 // Normal initializer.
2650 ExprResult Init = ParseCXXMemberInitializer(
2651 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2653 if (Init.isInvalid())
2654 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2656 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2657 DS.containsPlaceholderType());
2658 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2660 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
2663 if (!ThisDecl->isInvalidDecl()) {
2664 // Set the Decl for any late parsed attributes
2665 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2666 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2668 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2669 LateParsedAttrs[i]->addDecl(ThisDecl);
2671 Actions.FinalizeDeclaration(ThisDecl);
2672 DeclsInGroup.push_back(ThisDecl);
2674 if (DeclaratorInfo.isFunctionDeclarator() &&
2675 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2676 DeclSpec::SCS_typedef)
2677 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2679 LateParsedAttrs.clear();
2681 DeclaratorInfo.complete(ThisDecl);
2683 // If we don't have a comma, it is either the end of the list (a ';')
2684 // or an error, bail out.
2685 SourceLocation CommaLoc;
2686 if (!TryConsumeToken(tok::comma, CommaLoc))
2689 if (Tok.isAtStartOfLine() &&
2690 !MightBeDeclarator(Declarator::MemberContext)) {
2691 // This comma was followed by a line-break and something which can't be
2692 // the start of a declarator. The comma was probably a typo for a
2694 Diag(CommaLoc, diag::err_expected_semi_declaration)
2695 << FixItHint::CreateReplacement(CommaLoc, ";");
2700 // Parse the next declarator.
2701 DeclaratorInfo.clear();
2703 BitfieldSize = ExprResult(/*Invalid=*/false);
2704 EqualLoc = PureSpecLoc = SourceLocation();
2705 DeclaratorInfo.setCommaLoc(CommaLoc);
2707 // GNU attributes are allowed before the second and subsequent declarator.
2708 MaybeParseGNUAttributes(DeclaratorInfo);
2710 if (ParseCXXMemberDeclaratorBeforeInitializer(
2711 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2716 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2717 // Skip to end of block or statement.
2718 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2719 // If we stopped at a ';', eat it.
2720 TryConsumeToken(tok::semi);
2724 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2727 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2728 /// Also detect and reject any attempted defaulted/deleted function definition.
2729 /// The location of the '=', if any, will be placed in EqualLoc.
2731 /// This does not check for a pure-specifier; that's handled elsewhere.
2733 /// brace-or-equal-initializer:
2734 /// '=' initializer-expression
2735 /// braced-init-list
2737 /// initializer-clause:
2738 /// assignment-expression
2739 /// braced-init-list
2741 /// defaulted/deleted function-definition:
2745 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2746 /// be a constant-expression.
2747 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2748 SourceLocation &EqualLoc) {
2749 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2750 && "Data member initializer not starting with '=' or '{'");
2752 EnterExpressionEvaluationContext Context(Actions,
2753 Sema::PotentiallyEvaluated,
2755 if (TryConsumeToken(tok::equal, EqualLoc)) {
2756 if (Tok.is(tok::kw_delete)) {
2757 // In principle, an initializer of '= delete p;' is legal, but it will
2758 // never type-check. It's better to diagnose it as an ill-formed expression
2759 // than as an ill-formed deleted non-function member.
2760 // An initializer of '= delete p, foo' will never be parsed, because
2761 // a top-level comma always ends the initializer expression.
2762 const Token &Next = NextToken();
2763 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2765 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2768 Diag(ConsumeToken(), diag::err_deleted_non_function);
2771 } else if (Tok.is(tok::kw_default)) {
2773 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2776 Diag(ConsumeToken(), diag::err_default_special_members);
2780 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2781 Diag(Tok, diag::err_ms_property_initializer) << PD;
2784 return ParseInitializer();
2787 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2788 SourceLocation AttrFixitLoc,
2789 unsigned TagType, Decl *TagDecl) {
2790 // Skip the optional 'final' keyword.
2791 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2792 assert(isCXX11FinalKeyword() && "not a class definition");
2795 // Diagnose any C++11 attributes after 'final' keyword.
2796 // We deliberately discard these attributes.
2797 ParsedAttributesWithRange Attrs(AttrFactory);
2798 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2800 // This can only happen if we had malformed misplaced attributes;
2801 // we only get called if there is a colon or left-brace after the
2803 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2807 // Skip the base clauses. This requires actually parsing them, because
2808 // otherwise we can't be sure where they end (a left brace may appear
2809 // within a template argument).
2810 if (Tok.is(tok::colon)) {
2811 // Enter the scope of the class so that we can correctly parse its bases.
2812 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2813 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2814 TagType == DeclSpec::TST_interface);
2816 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2818 // Parse the bases but don't attach them to the class.
2819 ParseBaseClause(nullptr);
2821 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2823 if (!Tok.is(tok::l_brace)) {
2824 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2825 diag::err_expected_lbrace_after_base_specifiers);
2831 assert(Tok.is(tok::l_brace));
2832 BalancedDelimiterTracker T(*this, tok::l_brace);
2836 // Parse and discard any trailing attributes.
2837 ParsedAttributes Attrs(AttrFactory);
2838 if (Tok.is(tok::kw___attribute))
2839 MaybeParseGNUAttributes(Attrs);
2842 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
2843 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2844 DeclSpec::TST TagType, Decl *TagDecl) {
2845 if (getLangOpts().MicrosoftExt &&
2846 Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
2847 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
2851 // Check for extraneous top-level semicolon.
2852 if (Tok.is(tok::semi)) {
2853 ConsumeExtraSemi(InsideStruct, TagType);
2857 if (Tok.is(tok::annot_pragma_vis)) {
2858 HandlePragmaVisibility();
2862 if (Tok.is(tok::annot_pragma_pack)) {
2867 if (Tok.is(tok::annot_pragma_align)) {
2868 HandlePragmaAlign();
2872 if (Tok.is(tok::annot_pragma_ms_pointers_to_members)) {
2873 HandlePragmaMSPointersToMembers();
2877 if (Tok.is(tok::annot_pragma_ms_pragma)) {
2878 HandlePragmaMSPragma();
2882 if (Tok.is(tok::annot_pragma_ms_vtordisp)) {
2883 HandlePragmaMSVtorDisp();
2887 // If we see a namespace here, a close brace was missing somewhere.
2888 if (Tok.is(tok::kw_namespace)) {
2889 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
2893 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
2894 if (NewAS != AS_none) {
2895 // Current token is a C++ access specifier.
2897 SourceLocation ASLoc = Tok.getLocation();
2898 unsigned TokLength = Tok.getLength();
2900 AccessAttrs.clear();
2901 MaybeParseGNUAttributes(AccessAttrs);
2903 SourceLocation EndLoc;
2904 if (TryConsumeToken(tok::colon, EndLoc)) {
2905 } else if (TryConsumeToken(tok::semi, EndLoc)) {
2906 Diag(EndLoc, diag::err_expected)
2907 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
2909 EndLoc = ASLoc.getLocWithOffset(TokLength);
2910 Diag(EndLoc, diag::err_expected)
2911 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
2914 // The Microsoft extension __interface does not permit non-public
2915 // access specifiers.
2916 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
2917 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
2920 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
2921 AccessAttrs.getList())) {
2922 // found another attribute than only annotations
2923 AccessAttrs.clear();
2929 if (Tok.is(tok::annot_pragma_openmp))
2930 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
2933 // Parse all the comma separated declarators.
2934 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
2937 /// ParseCXXMemberSpecification - Parse the class definition.
2939 /// member-specification:
2940 /// member-declaration member-specification[opt]
2941 /// access-specifier ':' member-specification[opt]
2943 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2944 SourceLocation AttrFixitLoc,
2945 ParsedAttributesWithRange &Attrs,
2946 unsigned TagType, Decl *TagDecl) {
2947 assert((TagType == DeclSpec::TST_struct ||
2948 TagType == DeclSpec::TST_interface ||
2949 TagType == DeclSpec::TST_union ||
2950 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2952 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2953 "parsing struct/union/class body");
2955 // Determine whether this is a non-nested class. Note that local
2956 // classes are *not* considered to be nested classes.
2957 bool NonNestedClass = true;
2958 if (!ClassStack.empty()) {
2959 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2960 if (S->isClassScope()) {
2961 // We're inside a class scope, so this is a nested class.
2962 NonNestedClass = false;
2964 // The Microsoft extension __interface does not permit nested classes.
2965 if (getCurrentClass().IsInterface) {
2966 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2968 << (isa<NamedDecl>(TagDecl)
2969 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2975 if ((S->getFlags() & Scope::FnScope))
2976 // If we're in a function or function template then this is a local
2977 // class rather than a nested class.
2982 // Enter a scope for the class.
2983 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2985 // Note that we are parsing a new (potentially-nested) class definition.
2986 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2987 TagType == DeclSpec::TST_interface);
2990 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2992 SourceLocation FinalLoc;
2993 bool IsFinalSpelledSealed = false;
2995 // Parse the optional 'final' keyword.
2996 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2997 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2998 assert((Specifier == VirtSpecifiers::VS_Final ||
2999 Specifier == VirtSpecifiers::VS_Sealed) &&
3000 "not a class definition");
3001 FinalLoc = ConsumeToken();
3002 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
3004 if (TagType == DeclSpec::TST_interface)
3005 Diag(FinalLoc, diag::err_override_control_interface)
3006 << VirtSpecifiers::getSpecifierName(Specifier);
3007 else if (Specifier == VirtSpecifiers::VS_Final)
3008 Diag(FinalLoc, getLangOpts().CPlusPlus11
3009 ? diag::warn_cxx98_compat_override_control_keyword
3010 : diag::ext_override_control_keyword)
3011 << VirtSpecifiers::getSpecifierName(Specifier);
3012 else if (Specifier == VirtSpecifiers::VS_Sealed)
3013 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3015 // Parse any C++11 attributes after 'final' keyword.
3016 // These attributes are not allowed to appear here,
3017 // and the only possible place for them to appertain
3018 // to the class would be between class-key and class-name.
3019 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3021 // ParseClassSpecifier() does only a superficial check for attributes before
3022 // deciding to call this method. For example, for
3023 // `class C final alignas ([l) {` it will decide that this looks like a
3024 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3025 // attribute parsing code will try to parse the '[' as a constexpr lambda
3026 // and consume enough tokens that the alignas parsing code will eat the
3027 // opening '{'. So bail out if the next token isn't one we expect.
3028 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3030 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3035 if (Tok.is(tok::colon)) {
3036 ParseBaseClause(TagDecl);
3037 if (!Tok.is(tok::l_brace)) {
3038 bool SuggestFixIt = false;
3039 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3040 if (Tok.isAtStartOfLine()) {
3041 switch (Tok.getKind()) {
3042 case tok::kw_private:
3043 case tok::kw_protected:
3044 case tok::kw_public:
3045 SuggestFixIt = NextToken().getKind() == tok::colon;
3047 case tok::kw_static_assert:
3050 // base-clause can have simple-template-id; 'template' can't be there
3051 case tok::kw_template:
3052 SuggestFixIt = true;
3054 case tok::identifier:
3055 SuggestFixIt = isConstructorDeclarator(true);
3058 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3062 DiagnosticBuilder LBraceDiag =
3063 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3065 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3066 // Try recovering from missing { after base-clause.
3068 Tok.setKind(tok::l_brace);
3071 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3077 assert(Tok.is(tok::l_brace));
3078 BalancedDelimiterTracker T(*this, tok::l_brace);
3082 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3083 IsFinalSpelledSealed,
3084 T.getOpenLocation());
3086 // C++ 11p3: Members of a class defined with the keyword class are private
3087 // by default. Members of a class defined with the keywords struct or union
3088 // are public by default.
3089 AccessSpecifier CurAS;
3090 if (TagType == DeclSpec::TST_class)
3094 ParsedAttributesWithRange AccessAttrs(AttrFactory);
3097 // While we still have something to read, read the member-declarations.
3098 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3099 Tok.isNot(tok::eof)) {
3100 // Each iteration of this loop reads one member-declaration.
3101 ParseCXXClassMemberDeclarationWithPragmas(
3102 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3106 SkipUntil(tok::r_brace);
3109 // If attributes exist after class contents, parse them.
3110 ParsedAttributes attrs(AttrFactory);
3111 MaybeParseGNUAttributes(attrs);
3114 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3115 T.getOpenLocation(),
3116 T.getCloseLocation(),
3119 // C++11 [class.mem]p2:
3120 // Within the class member-specification, the class is regarded as complete
3121 // within function bodies, default arguments, exception-specifications, and
3122 // brace-or-equal-initializers for non-static data members (including such
3123 // things in nested classes).
3124 if (TagDecl && NonNestedClass) {
3125 // We are not inside a nested class. This class and its nested classes
3126 // are complete and we can parse the delayed portions of method
3127 // declarations and the lexed inline method definitions, along with any
3128 // delayed attributes.
3129 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3130 ParseLexedAttributes(getCurrentClass());
3131 ParseLexedMethodDeclarations(getCurrentClass());
3133 // We've finished with all pending member declarations.
3134 Actions.ActOnFinishCXXMemberDecls();
3136 ParseLexedMemberInitializers(getCurrentClass());
3137 ParseLexedMethodDefs(getCurrentClass());
3138 PrevTokLocation = SavedPrevTokLocation;
3140 // We've finished parsing everything, including default argument
3142 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3146 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3148 // Leave the class scope.
3153 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3154 assert(Tok.is(tok::kw_namespace));
3156 // FIXME: Suggest where the close brace should have gone by looking
3157 // at indentation changes within the definition body.
3158 Diag(D->getLocation(),
3159 diag::err_missing_end_of_definition) << D;
3160 Diag(Tok.getLocation(),
3161 diag::note_missing_end_of_definition_before) << D;
3163 // Push '};' onto the token stream to recover.
3167 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3168 Tok.setKind(tok::semi);
3171 Tok.setKind(tok::r_brace);
3174 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3175 /// which explicitly initializes the members or base classes of a
3176 /// class (C++ [class.base.init]). For example, the three initializers
3177 /// after the ':' in the Derived constructor below:
3181 /// class Derived : Base {
3185 /// Derived(float f) : Base(), x(17), f(f) { }
3189 /// [C++] ctor-initializer:
3190 /// ':' mem-initializer-list
3192 /// [C++] mem-initializer-list:
3193 /// mem-initializer ...[opt]
3194 /// mem-initializer ...[opt] , mem-initializer-list
3195 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3196 assert(Tok.is(tok::colon) &&
3197 "Constructor initializer always starts with ':'");
3199 // Poison the SEH identifiers so they are flagged as illegal in constructor
3201 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3202 SourceLocation ColonLoc = ConsumeToken();
3204 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3205 bool AnyErrors = false;
3208 if (Tok.is(tok::code_completion)) {
3209 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3211 return cutOffParsing();
3214 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3215 if (!MemInit.isInvalid())
3216 MemInitializers.push_back(MemInit.get());
3220 if (Tok.is(tok::comma))
3222 else if (Tok.is(tok::l_brace))
3224 // If the previous initializer was valid and the next token looks like a
3225 // base or member initializer, assume that we're just missing a comma.
3226 else if (!MemInit.isInvalid() &&
3227 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3228 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3229 Diag(Loc, diag::err_ctor_init_missing_comma)
3230 << FixItHint::CreateInsertion(Loc, ", ");
3232 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3233 if (!MemInit.isInvalid())
3234 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3236 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3241 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3245 /// ParseMemInitializer - Parse a C++ member initializer, which is
3246 /// part of a constructor initializer that explicitly initializes one
3247 /// member or base class (C++ [class.base.init]). See
3248 /// ParseConstructorInitializer for an example.
3250 /// [C++] mem-initializer:
3251 /// mem-initializer-id '(' expression-list[opt] ')'
3252 /// [C++0x] mem-initializer-id braced-init-list
3254 /// [C++] mem-initializer-id:
3255 /// '::'[opt] nested-name-specifier[opt] class-name
3257 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3258 // parse '::'[opt] nested-name-specifier[opt]
3260 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
3261 ParsedType TemplateTypeTy;
3262 if (Tok.is(tok::annot_template_id)) {
3263 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3264 if (TemplateId->Kind == TNK_Type_template ||
3265 TemplateId->Kind == TNK_Dependent_template_name) {
3266 AnnotateTemplateIdTokenAsType();
3267 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3268 TemplateTypeTy = getTypeAnnotation(Tok);
3271 // Uses of decltype will already have been converted to annot_decltype by
3272 // ParseOptionalCXXScopeSpecifier at this point.
3273 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
3274 && Tok.isNot(tok::annot_decltype)) {
3275 Diag(Tok, diag::err_expected_member_or_base_name);
3279 IdentifierInfo *II = nullptr;
3280 DeclSpec DS(AttrFactory);
3281 SourceLocation IdLoc = Tok.getLocation();
3282 if (Tok.is(tok::annot_decltype)) {
3283 // Get the decltype expression, if there is one.
3284 ParseDecltypeSpecifier(DS);
3286 if (Tok.is(tok::identifier))
3287 // Get the identifier. This may be a member name or a class name,
3288 // but we'll let the semantic analysis determine which it is.
3289 II = Tok.getIdentifierInfo();
3295 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3296 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3298 ExprResult InitList = ParseBraceInitializer();
3299 if (InitList.isInvalid())
3302 SourceLocation EllipsisLoc;
3303 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3305 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3306 TemplateTypeTy, DS, IdLoc,
3307 InitList.get(), EllipsisLoc);
3308 } else if(Tok.is(tok::l_paren)) {
3309 BalancedDelimiterTracker T(*this, tok::l_paren);
3312 // Parse the optional expression-list.
3313 ExprVector ArgExprs;
3314 CommaLocsTy CommaLocs;
3315 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
3316 SkipUntil(tok::r_paren, StopAtSemi);
3322 SourceLocation EllipsisLoc;
3323 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3325 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3326 TemplateTypeTy, DS, IdLoc,
3327 T.getOpenLocation(), ArgExprs,
3328 T.getCloseLocation(), EllipsisLoc);
3331 if (getLangOpts().CPlusPlus11)
3332 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3334 return Diag(Tok, diag::err_expected) << tok::l_paren;
3337 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
3339 /// exception-specification:
3340 /// dynamic-exception-specification
3341 /// noexcept-specification
3343 /// noexcept-specification:
3345 /// 'noexcept' '(' constant-expression ')'
3346 ExceptionSpecificationType
3347 Parser::tryParseExceptionSpecification(bool Delayed,
3348 SourceRange &SpecificationRange,
3349 SmallVectorImpl<ParsedType> &DynamicExceptions,
3350 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3351 ExprResult &NoexceptExpr,
3352 CachedTokens *&ExceptionSpecTokens) {
3353 ExceptionSpecificationType Result = EST_None;
3354 ExceptionSpecTokens = nullptr;
3356 // Handle delayed parsing of exception-specifications.
3358 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3361 // Consume and cache the starting token.
3362 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3363 Token StartTok = Tok;
3364 SpecificationRange = SourceRange(ConsumeToken());
3367 if (!Tok.is(tok::l_paren)) {
3368 // If this is a bare 'noexcept', we're done.
3370 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3371 NoexceptExpr = nullptr;
3372 return EST_BasicNoexcept;
3375 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3376 return EST_DynamicNone;
3379 // Cache the tokens for the exception-specification.
3380 ExceptionSpecTokens = new CachedTokens;
3381 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3382 ExceptionSpecTokens->push_back(Tok); // '('
3383 SpecificationRange.setEnd(ConsumeParen()); // '('
3385 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3386 /*StopAtSemi=*/true,
3387 /*ConsumeFinalToken=*/true);
3388 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3390 return EST_Unparsed;
3393 // See if there's a dynamic specification.
3394 if (Tok.is(tok::kw_throw)) {
3395 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3397 DynamicExceptionRanges);
3398 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3399 "Produced different number of exception types and ranges.");
3402 // If there's no noexcept specification, we're done.
3403 if (Tok.isNot(tok::kw_noexcept))
3406 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3408 // If we already had a dynamic specification, parse the noexcept for,
3409 // recovery, but emit a diagnostic and don't store the results.
3410 SourceRange NoexceptRange;
3411 ExceptionSpecificationType NoexceptType = EST_None;
3413 SourceLocation KeywordLoc = ConsumeToken();
3414 if (Tok.is(tok::l_paren)) {
3415 // There is an argument.
3416 BalancedDelimiterTracker T(*this, tok::l_paren);
3418 NoexceptType = EST_ComputedNoexcept;
3419 NoexceptExpr = ParseConstantExpression();
3421 // The argument must be contextually convertible to bool. We use
3422 // CheckBooleanCondition for this purpose.
3423 // FIXME: Add a proper Sema entry point for this.
3424 if (!NoexceptExpr.isInvalid()) {
3426 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
3427 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3429 NoexceptType = EST_None;
3432 // There is no argument.
3433 NoexceptType = EST_BasicNoexcept;
3434 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3437 if (Result == EST_None) {
3438 SpecificationRange = NoexceptRange;
3439 Result = NoexceptType;
3441 // If there's a dynamic specification after a noexcept specification,
3442 // parse that and ignore the results.
3443 if (Tok.is(tok::kw_throw)) {
3444 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3445 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3446 DynamicExceptionRanges);
3449 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3455 static void diagnoseDynamicExceptionSpecification(
3456 Parser &P, SourceRange Range, bool IsNoexcept) {
3457 if (P.getLangOpts().CPlusPlus11) {
3458 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3459 P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
3460 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3461 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3465 /// ParseDynamicExceptionSpecification - Parse a C++
3466 /// dynamic-exception-specification (C++ [except.spec]).
3468 /// dynamic-exception-specification:
3469 /// 'throw' '(' type-id-list [opt] ')'
3470 /// [MS] 'throw' '(' '...' ')'
3473 /// type-id ... [opt]
3474 /// type-id-list ',' type-id ... [opt]
3476 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3477 SourceRange &SpecificationRange,
3478 SmallVectorImpl<ParsedType> &Exceptions,
3479 SmallVectorImpl<SourceRange> &Ranges) {
3480 assert(Tok.is(tok::kw_throw) && "expected throw");
3482 SpecificationRange.setBegin(ConsumeToken());
3483 BalancedDelimiterTracker T(*this, tok::l_paren);
3484 if (T.consumeOpen()) {
3485 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3486 SpecificationRange.setEnd(SpecificationRange.getBegin());
3487 return EST_DynamicNone;
3490 // Parse throw(...), a Microsoft extension that means "this function
3491 // can throw anything".
3492 if (Tok.is(tok::ellipsis)) {
3493 SourceLocation EllipsisLoc = ConsumeToken();
3494 if (!getLangOpts().MicrosoftExt)
3495 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3497 SpecificationRange.setEnd(T.getCloseLocation());
3498 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3502 // Parse the sequence of type-ids.
3504 while (Tok.isNot(tok::r_paren)) {
3505 TypeResult Res(ParseTypeName(&Range));
3507 if (Tok.is(tok::ellipsis)) {
3508 // C++0x [temp.variadic]p5:
3509 // - In a dynamic-exception-specification (15.4); the pattern is a
3511 SourceLocation Ellipsis = ConsumeToken();
3512 Range.setEnd(Ellipsis);
3513 if (!Res.isInvalid())
3514 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3517 if (!Res.isInvalid()) {
3518 Exceptions.push_back(Res.get());
3519 Ranges.push_back(Range);
3522 if (!TryConsumeToken(tok::comma))
3527 SpecificationRange.setEnd(T.getCloseLocation());
3528 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3529 Exceptions.empty());
3530 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3533 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3534 /// function declaration.
3535 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3536 assert(Tok.is(tok::arrow) && "expected arrow");
3540 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3543 /// \brief We have just started parsing the definition of a new class,
3544 /// so push that class onto our stack of classes that is currently
3546 Sema::ParsingClassState
3547 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3549 assert((NonNestedClass || !ClassStack.empty()) &&
3550 "Nested class without outer class");
3551 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3552 return Actions.PushParsingClass();
3555 /// \brief Deallocate the given parsed class and all of its nested
3557 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3558 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3559 delete Class->LateParsedDeclarations[I];
3563 /// \brief Pop the top class of the stack of classes that are
3564 /// currently being parsed.
3566 /// This routine should be called when we have finished parsing the
3567 /// definition of a class, but have not yet popped the Scope
3568 /// associated with the class's definition.
3569 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3570 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3572 Actions.PopParsingClass(state);
3574 ParsingClass *Victim = ClassStack.top();
3576 if (Victim->TopLevelClass) {
3577 // Deallocate all of the nested classes of this class,
3578 // recursively: we don't need to keep any of this information.
3579 DeallocateParsedClasses(Victim);
3582 assert(!ClassStack.empty() && "Missing top-level class?");
3584 if (Victim->LateParsedDeclarations.empty()) {
3585 // The victim is a nested class, but we will not need to perform
3586 // any processing after the definition of this class since it has
3587 // no members whose handling was delayed. Therefore, we can just
3588 // remove this nested class.
3589 DeallocateParsedClasses(Victim);
3593 // This nested class has some members that will need to be processed
3594 // after the top-level class is completely defined. Therefore, add
3595 // it to the list of nested classes within its parent.
3596 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3597 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3598 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3601 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3603 /// \return the parsed identifier on success, and 0 if the next token is not an
3604 /// attribute-token.
3606 /// C++11 [dcl.attr.grammar]p3:
3607 /// If a keyword or an alternative token that satisfies the syntactic
3608 /// requirements of an identifier is contained in an attribute-token,
3609 /// it is considered an identifier.
3610 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3611 switch (Tok.getKind()) {
3613 // Identifiers and keywords have identifier info attached.
3614 if (!Tok.isAnnotation()) {
3615 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3616 Loc = ConsumeToken();
3622 case tok::ampamp: // 'and'
3623 case tok::pipe: // 'bitor'
3624 case tok::pipepipe: // 'or'
3625 case tok::caret: // 'xor'
3626 case tok::tilde: // 'compl'
3627 case tok::amp: // 'bitand'
3628 case tok::ampequal: // 'and_eq'
3629 case tok::pipeequal: // 'or_eq'
3630 case tok::caretequal: // 'xor_eq'
3631 case tok::exclaim: // 'not'
3632 case tok::exclaimequal: // 'not_eq'
3633 // Alternative tokens do not have identifier info, but their spelling
3634 // starts with an alphabetical character.
3635 SmallString<8> SpellingBuf;
3636 SourceLocation SpellingLoc =
3637 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3638 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3639 if (isLetter(Spelling[0])) {
3640 Loc = ConsumeToken();
3641 return &PP.getIdentifierTable().get(Spelling);
3647 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3648 IdentifierInfo *ScopeName) {
3649 switch (AttributeList::getKind(AttrName, ScopeName,
3650 AttributeList::AS_CXX11)) {
3651 case AttributeList::AT_CarriesDependency:
3652 case AttributeList::AT_Deprecated:
3653 case AttributeList::AT_FallThrough:
3654 case AttributeList::AT_CXX11NoReturn:
3656 case AttributeList::AT_WarnUnusedResult:
3657 return !ScopeName && AttrName->getName().equals("nodiscard");
3658 case AttributeList::AT_Unused:
\r
3659 return !ScopeName && AttrName->getName().equals("maybe_unused");
\r
3665 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3667 /// [C++11] attribute-argument-clause:
3668 /// '(' balanced-token-seq ')'
3670 /// [C++11] balanced-token-seq:
3672 /// balanced-token-seq balanced-token
3674 /// [C++11] balanced-token:
3675 /// '(' balanced-token-seq ')'
3676 /// '[' balanced-token-seq ']'
3677 /// '{' balanced-token-seq '}'
3678 /// any token but '(', ')', '[', ']', '{', or '}'
3679 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3680 SourceLocation AttrNameLoc,
3681 ParsedAttributes &Attrs,
3682 SourceLocation *EndLoc,
3683 IdentifierInfo *ScopeName,
3684 SourceLocation ScopeLoc) {
3685 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3686 SourceLocation LParenLoc = Tok.getLocation();
3688 // If the attribute isn't known, we will not attempt to parse any
3690 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
3691 getTargetInfo(), getLangOpts())) {
3692 // Eat the left paren, then skip to the ending right paren.
3694 SkipUntil(tok::r_paren);
3698 if (ScopeName && ScopeName->getName() == "gnu")
3699 // GNU-scoped attributes have some special cases to handle GNU-specific
3701 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3702 ScopeLoc, AttributeList::AS_CXX11, nullptr);
3705 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3706 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3708 const AttributeList *Attr = Attrs.getList();
3709 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3710 // If the attribute is a standard or built-in attribute and we are
3711 // parsing an argument list, we need to determine whether this attribute
3712 // was allowed to have an argument list (such as [[deprecated]]), and how
3713 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3714 if (Attr->getMaxArgs() && !NumArgs) {
3715 // The attribute was allowed to have arguments, but none were provided
3716 // even though the attribute parsed successfully. This is an error.
3717 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3718 Attr->setInvalid(true);
3719 } else if (!Attr->getMaxArgs()) {
3720 // The attribute parsed successfully, but was not allowed to have any
3721 // arguments. It doesn't matter whether any were provided -- the
3722 // presence of the argument list (even if empty) is diagnosed.
3723 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3725 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3726 Attr->setInvalid(true);
3733 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
3735 /// [C++11] attribute-specifier:
3736 /// '[' '[' attribute-list ']' ']'
3737 /// alignment-specifier
3739 /// [C++11] attribute-list:
3741 /// attribute-list ',' attribute[opt]
3743 /// attribute-list ',' attribute '...'
3745 /// [C++11] attribute:
3746 /// attribute-token attribute-argument-clause[opt]
3748 /// [C++11] attribute-token:
3750 /// attribute-scoped-token
3752 /// [C++11] attribute-scoped-token:
3753 /// attribute-namespace '::' identifier
3755 /// [C++11] attribute-namespace:
3757 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3758 SourceLocation *endLoc) {
3759 if (Tok.is(tok::kw_alignas)) {
3760 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3761 ParseAlignmentSpecifier(attrs, endLoc);
3765 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3766 && "Not a C++11 attribute list");
3768 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3773 SourceLocation CommonScopeLoc;
3774 IdentifierInfo *CommonScopeName = nullptr;
3775 if (Tok.is(tok::kw_using)) {
3776 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
3777 ? diag::warn_cxx14_compat_using_attribute_ns
3778 : diag::ext_using_attribute_ns);
3781 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3782 if (!CommonScopeName) {
3783 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3784 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3786 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3787 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3790 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3792 while (Tok.isNot(tok::r_square)) {
3793 // attribute not present
3794 if (TryConsumeToken(tok::comma))
3797 SourceLocation ScopeLoc, AttrLoc;
3798 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3800 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3802 // Break out to the "expected ']'" diagnostic.
3806 if (TryConsumeToken(tok::coloncolon)) {
3807 ScopeName = AttrName;
3810 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3812 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3813 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3818 if (CommonScopeName) {
3820 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
3821 << SourceRange(CommonScopeLoc);
3823 ScopeName = CommonScopeName;
3824 ScopeLoc = CommonScopeLoc;
3828 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
3829 bool AttrParsed = false;
3832 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3833 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
3834 << AttrName << SourceRange(SeenAttrs[AttrName]);
3836 // Parse attribute arguments
3837 if (Tok.is(tok::l_paren))
3838 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3839 ScopeName, ScopeLoc);
3842 attrs.addNew(AttrName,
3843 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3845 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
3847 if (TryConsumeToken(tok::ellipsis))
3848 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3849 << AttrName->getName();
3852 if (ExpectAndConsume(tok::r_square))
3853 SkipUntil(tok::r_square);
3855 *endLoc = Tok.getLocation();
3856 if (ExpectAndConsume(tok::r_square))
3857 SkipUntil(tok::r_square);
3860 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3862 /// attribute-specifier-seq:
3863 /// attribute-specifier-seq[opt] attribute-specifier
3864 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3865 SourceLocation *endLoc) {
3866 assert(getLangOpts().CPlusPlus11);
3868 SourceLocation StartLoc = Tok.getLocation(), Loc;
3873 ParseCXX11AttributeSpecifier(attrs, endLoc);
3874 } while (isCXX11AttributeSpecifier());
3876 attrs.Range = SourceRange(StartLoc, *endLoc);
3879 void Parser::DiagnoseAndSkipCXX11Attributes() {
3880 // Start and end location of an attribute or an attribute list.
3881 SourceLocation StartLoc = Tok.getLocation();
3882 SourceLocation EndLoc = SkipCXX11Attributes();
3884 if (EndLoc.isValid()) {
3885 SourceRange Range(StartLoc, EndLoc);
3886 Diag(StartLoc, diag::err_attributes_not_allowed)
3891 SourceLocation Parser::SkipCXX11Attributes() {
3892 SourceLocation EndLoc;
3894 if (!isCXX11AttributeSpecifier())
3898 if (Tok.is(tok::l_square)) {
3899 BalancedDelimiterTracker T(*this, tok::l_square);
3902 EndLoc = T.getCloseLocation();
3904 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
3906 BalancedDelimiterTracker T(*this, tok::l_paren);
3907 if (!T.consumeOpen())
3909 EndLoc = T.getCloseLocation();
3911 } while (isCXX11AttributeSpecifier());
3916 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
3918 /// [MS] ms-attribute:
3919 /// '[' token-seq ']'
3921 /// [MS] ms-attribute-seq:
3922 /// ms-attribute[opt]
3923 /// ms-attribute ms-attribute-seq
3924 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3925 SourceLocation *endLoc) {
3926 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3929 // FIXME: If this is actually a C++11 attribute, parse it as one.
3930 BalancedDelimiterTracker T(*this, tok::l_square);
3932 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
3935 *endLoc = T.getCloseLocation();
3936 } while (Tok.is(tok::l_square));
3939 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3940 AccessSpecifier& CurAS) {
3941 IfExistsCondition Result;
3942 if (ParseMicrosoftIfExistsCondition(Result))
3945 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3946 if (Braces.consumeOpen()) {
3947 Diag(Tok, diag::err_expected) << tok::l_brace;
3951 switch (Result.Behavior) {
3953 // Parse the declarations below.
3957 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3958 << Result.IsIfExists;
3959 // Fall through to skip.
3966 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
3967 // __if_exists, __if_not_exists can nest.
3968 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
3969 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3973 // Check for extraneous top-level semicolon.
3974 if (Tok.is(tok::semi)) {
3975 ConsumeExtraSemi(InsideStruct, TagType);
3979 AccessSpecifier AS = getAccessSpecifierIfPresent();
3980 if (AS != AS_none) {
3981 // Current token is a C++ access specifier.
3983 SourceLocation ASLoc = Tok.getLocation();
3985 if (Tok.is(tok::colon))
3986 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3988 Diag(Tok, diag::err_expected) << tok::colon;
3993 // Parse all the comma separated declarators.
3994 ParseCXXClassMemberDeclaration(CurAS, nullptr);
3997 Braces.consumeClose();