1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++ Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/Basic/Attributes.h"
18 #include "clang/Basic/CharInfo.h"
19 #include "clang/Basic/OperatorKinds.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Parse/ParseDiagnostic.h"
22 #include "clang/Parse/RAIIObjectsForParser.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/SmallString.h"
30 using namespace clang;
32 /// ParseNamespace - We know that the current token is a namespace keyword. This
33 /// may either be a top level namespace or a block-level namespace alias. If
34 /// there was an inline keyword, it has already been parsed.
36 /// namespace-definition: [C++ 7.3: basic.namespace]
37 /// named-namespace-definition
38 /// unnamed-namespace-definition
40 /// unnamed-namespace-definition:
41 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
43 /// named-namespace-definition:
44 /// original-namespace-definition
45 /// extension-namespace-definition
47 /// original-namespace-definition:
48 /// 'inline'[opt] 'namespace' identifier attributes[opt]
49 /// '{' namespace-body '}'
51 /// extension-namespace-definition:
52 /// 'inline'[opt] 'namespace' original-namespace-name
53 /// '{' namespace-body '}'
55 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
56 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
58 Parser::DeclGroupPtrTy Parser::ParseNamespace(unsigned Context,
59 SourceLocation &DeclEnd,
60 SourceLocation InlineLoc) {
61 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
62 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
63 ObjCDeclContextSwitch ObjCDC(*this);
65 if (Tok.is(tok::code_completion)) {
66 Actions.CodeCompleteNamespaceDecl(getCurScope());
71 SourceLocation IdentLoc;
72 IdentifierInfo *Ident = nullptr;
73 std::vector<SourceLocation> ExtraIdentLoc;
74 std::vector<IdentifierInfo*> ExtraIdent;
75 std::vector<SourceLocation> ExtraNamespaceLoc;
77 ParsedAttributesWithRange attrs(AttrFactory);
78 SourceLocation attrLoc;
79 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
80 if (!getLangOpts().CPlusPlus1z)
81 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
83 attrLoc = Tok.getLocation();
84 ParseCXX11Attributes(attrs);
87 if (Tok.is(tok::identifier)) {
88 Ident = Tok.getIdentifierInfo();
89 IdentLoc = ConsumeToken(); // eat the identifier.
90 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
91 ExtraNamespaceLoc.push_back(ConsumeToken());
92 ExtraIdent.push_back(Tok.getIdentifierInfo());
93 ExtraIdentLoc.push_back(ConsumeToken());
97 // A nested namespace definition cannot have attributes.
98 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
99 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
101 // Read label attributes, if present.
102 if (Tok.is(tok::kw___attribute)) {
103 attrLoc = Tok.getLocation();
104 ParseGNUAttributes(attrs);
107 if (Tok.is(tok::equal)) {
109 Diag(Tok, diag::err_expected) << tok::identifier;
110 // Skip to end of the definition and eat the ';'.
111 SkipUntil(tok::semi);
114 if (attrLoc.isValid())
115 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
116 if (InlineLoc.isValid())
117 Diag(InlineLoc, diag::err_inline_namespace_alias)
118 << FixItHint::CreateRemoval(InlineLoc);
119 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
120 return Actions.ConvertDeclToDeclGroup(NSAlias);
123 BalancedDelimiterTracker T(*this, tok::l_brace);
124 if (T.consumeOpen()) {
126 Diag(Tok, diag::err_expected) << tok::l_brace;
128 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
132 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
133 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
134 getCurScope()->getFnParent()) {
135 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
136 SkipUntil(tok::r_brace);
140 if (ExtraIdent.empty()) {
141 // Normal namespace definition, not a nested-namespace-definition.
142 } else if (InlineLoc.isValid()) {
143 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
144 } else if (getLangOpts().CPlusPlus1z) {
145 Diag(ExtraNamespaceLoc[0],
146 diag::warn_cxx14_compat_nested_namespace_definition);
148 TentativeParsingAction TPA(*this);
149 SkipUntil(tok::r_brace, StopBeforeMatch);
150 Token rBraceToken = Tok;
153 if (!rBraceToken.is(tok::r_brace)) {
154 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
155 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
157 std::string NamespaceFix;
158 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
159 E = ExtraIdent.end(); I != E; ++I) {
160 NamespaceFix += " { namespace ";
161 NamespaceFix += (*I)->getName();
165 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
168 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
169 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
170 ExtraIdentLoc.back()),
172 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
176 // If we're still good, complain about inline namespaces in non-C++0x now.
177 if (InlineLoc.isValid())
178 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
179 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
181 // Enter a scope for the namespace.
182 ParseScope NamespaceScope(this, Scope::DeclScope);
184 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
186 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
187 IdentLoc, Ident, T.getOpenLocation(),
188 attrs.getList(), ImplicitUsingDirectiveDecl);
190 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
191 "parsing namespace");
193 // Parse the contents of the namespace. This includes parsing recovery on
194 // any improperly nested namespaces.
195 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
196 InlineLoc, attrs, T);
198 // Leave the namespace scope.
199 NamespaceScope.Exit();
201 DeclEnd = T.getCloseLocation();
202 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
204 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
205 ImplicitUsingDirectiveDecl);
208 /// ParseInnerNamespace - Parse the contents of a namespace.
209 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
210 std::vector<IdentifierInfo *> &Ident,
211 std::vector<SourceLocation> &NamespaceLoc,
212 unsigned int index, SourceLocation &InlineLoc,
213 ParsedAttributes &attrs,
214 BalancedDelimiterTracker &Tracker) {
215 if (index == Ident.size()) {
216 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
217 Tok.isNot(tok::eof)) {
218 ParsedAttributesWithRange attrs(AttrFactory);
219 MaybeParseCXX11Attributes(attrs);
220 ParseExternalDeclaration(attrs);
223 // The caller is what called check -- we are simply calling
225 Tracker.consumeClose();
230 // Handle a nested namespace definition.
231 // FIXME: Preserve the source information through to the AST rather than
232 // desugaring it here.
233 ParseScope NamespaceScope(this, Scope::DeclScope);
234 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
236 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
237 NamespaceLoc[index], IdentLoc[index],
238 Ident[index], Tracker.getOpenLocation(),
239 attrs.getList(), ImplicitUsingDirectiveDecl);
240 assert(!ImplicitUsingDirectiveDecl &&
241 "nested namespace definition cannot define anonymous namespace");
243 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
246 NamespaceScope.Exit();
247 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
250 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
251 /// alias definition.
253 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
254 SourceLocation AliasLoc,
255 IdentifierInfo *Alias,
256 SourceLocation &DeclEnd) {
257 assert(Tok.is(tok::equal) && "Not equal token");
259 ConsumeToken(); // eat the '='.
261 if (Tok.is(tok::code_completion)) {
262 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
268 // Parse (optional) nested-name-specifier.
269 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
270 /*MayBePseudoDestructor=*/nullptr,
271 /*IsTypename=*/false,
273 /*OnlyNamespace=*/true);
275 if (Tok.isNot(tok::identifier)) {
276 Diag(Tok, diag::err_expected_namespace_name);
277 // Skip to end of the definition and eat the ';'.
278 SkipUntil(tok::semi);
282 if (SS.isInvalid()) {
283 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
284 // Skip to end of the definition and eat the ';'.
285 SkipUntil(tok::semi);
290 IdentifierInfo *Ident = Tok.getIdentifierInfo();
291 SourceLocation IdentLoc = ConsumeToken();
294 DeclEnd = Tok.getLocation();
295 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
296 SkipUntil(tok::semi);
298 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
299 Alias, SS, IdentLoc, Ident);
302 /// ParseLinkage - We know that the current token is a string_literal
303 /// and just before that, that extern was seen.
305 /// linkage-specification: [C++ 7.5p2: dcl.link]
306 /// 'extern' string-literal '{' declaration-seq[opt] '}'
307 /// 'extern' string-literal declaration
309 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
310 assert(isTokenStringLiteral() && "Not a string literal!");
311 ExprResult Lang = ParseStringLiteralExpression(false);
313 ParseScope LinkageScope(this, Scope::DeclScope);
317 : Actions.ActOnStartLinkageSpecification(
318 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
319 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
321 ParsedAttributesWithRange attrs(AttrFactory);
322 MaybeParseCXX11Attributes(attrs);
324 if (Tok.isNot(tok::l_brace)) {
325 // Reset the source range in DS, as the leading "extern"
326 // does not really belong to the inner declaration ...
327 DS.SetRangeStart(SourceLocation());
328 DS.SetRangeEnd(SourceLocation());
329 // ... but anyway remember that such an "extern" was seen.
330 DS.setExternInLinkageSpec(true);
331 ParseExternalDeclaration(attrs, &DS);
332 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
333 getCurScope(), LinkageSpec, SourceLocation())
339 ProhibitAttributes(attrs);
341 BalancedDelimiterTracker T(*this, tok::l_brace);
344 unsigned NestedModules = 0;
346 switch (Tok.getKind()) {
347 case tok::annot_module_begin:
352 case tok::annot_module_end:
359 case tok::annot_module_include:
371 ParsedAttributesWithRange attrs(AttrFactory);
372 MaybeParseCXX11Attributes(attrs);
373 ParseExternalDeclaration(attrs);
381 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
382 getCurScope(), LinkageSpec, T.getCloseLocation())
386 /// Parse a C++ Modules TS export-declaration.
388 /// export-declaration:
389 /// 'export' declaration
390 /// 'export' '{' declaration-seq[opt] '}'
392 Decl *Parser::ParseExportDeclaration() {
393 assert(Tok.is(tok::kw_export));
394 SourceLocation ExportLoc = ConsumeToken();
396 ParseScope ExportScope(this, Scope::DeclScope);
397 Decl *ExportDecl = Actions.ActOnStartExportDecl(
398 getCurScope(), ExportLoc,
399 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
401 if (Tok.isNot(tok::l_brace)) {
402 // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
403 ParsedAttributesWithRange Attrs(AttrFactory);
404 MaybeParseCXX11Attributes(Attrs);
405 MaybeParseMicrosoftAttributes(Attrs);
406 ParseExternalDeclaration(Attrs);
407 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
411 BalancedDelimiterTracker T(*this, tok::l_brace);
414 // The Modules TS draft says "An export-declaration shall declare at least one
415 // entity", but the intent is that it shall contain at least one declaration.
416 if (Tok.is(tok::r_brace))
417 Diag(ExportLoc, diag::err_export_empty)
418 << SourceRange(ExportLoc, Tok.getLocation());
420 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
421 Tok.isNot(tok::eof)) {
422 ParsedAttributesWithRange Attrs(AttrFactory);
423 MaybeParseCXX11Attributes(Attrs);
424 MaybeParseMicrosoftAttributes(Attrs);
425 ParseExternalDeclaration(Attrs);
429 return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
430 T.getCloseLocation());
433 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
434 /// using-directive. Assumes that current token is 'using'.
435 Parser::DeclGroupPtrTy
436 Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
437 const ParsedTemplateInfo &TemplateInfo,
438 SourceLocation &DeclEnd,
439 ParsedAttributesWithRange &attrs) {
440 assert(Tok.is(tok::kw_using) && "Not using token");
441 ObjCDeclContextSwitch ObjCDC(*this);
444 SourceLocation UsingLoc = ConsumeToken();
446 if (Tok.is(tok::code_completion)) {
447 Actions.CodeCompleteUsing(getCurScope());
452 // 'using namespace' means this is a using-directive.
453 if (Tok.is(tok::kw_namespace)) {
454 // Template parameters are always an error here.
455 if (TemplateInfo.Kind) {
456 SourceRange R = TemplateInfo.getSourceRange();
457 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
458 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
461 Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
462 return Actions.ConvertDeclToDeclGroup(UsingDir);
465 // Otherwise, it must be a using-declaration or an alias-declaration.
467 // Using declarations can't have attributes.
468 ProhibitAttributes(attrs);
470 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
474 /// ParseUsingDirective - Parse C++ using-directive, assumes
475 /// that current token is 'namespace' and 'using' was already parsed.
477 /// using-directive: [C++ 7.3.p4: namespace.udir]
478 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
480 /// [GNU] using-directive:
481 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
482 /// namespace-name attributes[opt] ;
484 Decl *Parser::ParseUsingDirective(unsigned Context,
485 SourceLocation UsingLoc,
486 SourceLocation &DeclEnd,
487 ParsedAttributes &attrs) {
488 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
491 SourceLocation NamespcLoc = ConsumeToken();
493 if (Tok.is(tok::code_completion)) {
494 Actions.CodeCompleteUsingDirective(getCurScope());
500 // Parse (optional) nested-name-specifier.
501 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false,
502 /*MayBePseudoDestructor=*/nullptr,
503 /*IsTypename=*/false,
505 /*OnlyNamespace=*/true);
507 IdentifierInfo *NamespcName = nullptr;
508 SourceLocation IdentLoc = SourceLocation();
510 // Parse namespace-name.
511 if (Tok.isNot(tok::identifier)) {
512 Diag(Tok, diag::err_expected_namespace_name);
513 // If there was invalid namespace name, skip to end of decl, and eat ';'.
514 SkipUntil(tok::semi);
515 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
519 if (SS.isInvalid()) {
520 // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
521 // Skip to end of the definition and eat the ';'.
522 SkipUntil(tok::semi);
527 NamespcName = Tok.getIdentifierInfo();
528 IdentLoc = ConsumeToken();
530 // Parse (optional) attributes (most likely GNU strong-using extension).
531 bool GNUAttr = false;
532 if (Tok.is(tok::kw___attribute)) {
534 ParseGNUAttributes(attrs);
538 DeclEnd = Tok.getLocation();
539 if (ExpectAndConsume(tok::semi,
540 GNUAttr ? diag::err_expected_semi_after_attribute_list
541 : diag::err_expected_semi_after_namespace_name))
542 SkipUntil(tok::semi);
544 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
545 IdentLoc, NamespcName, attrs.getList());
548 /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
550 /// using-declarator:
551 /// 'typename'[opt] nested-name-specifier unqualified-id
553 bool Parser::ParseUsingDeclarator(unsigned Context, UsingDeclarator &D) {
556 // Ignore optional 'typename'.
557 // FIXME: This is wrong; we should parse this as a typename-specifier.
558 TryConsumeToken(tok::kw_typename, D.TypenameLoc);
560 if (Tok.is(tok::kw___super)) {
561 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
565 // Parse nested-name-specifier.
566 IdentifierInfo *LastII = nullptr;
567 ParseOptionalCXXScopeSpecifier(D.SS, nullptr, /*EnteringContext=*/false,
568 /*MayBePseudoDtor=*/nullptr,
569 /*IsTypename=*/false,
571 if (D.SS.isInvalid())
574 // Parse the unqualified-id. We allow parsing of both constructor and
575 // destructor names and allow the action module to diagnose any semantic
578 // C++11 [class.qual]p2:
579 // [...] in a using-declaration that is a member-declaration, if the name
580 // specified after the nested-name-specifier is the same as the identifier
581 // or the simple-template-id's template-name in the last component of the
582 // nested-name-specifier, the name is [...] considered to name the
584 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
585 Tok.is(tok::identifier) &&
586 (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
587 NextToken().is(tok::ellipsis)) &&
588 D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
589 !D.SS.getScopeRep()->getAsNamespace() &&
590 !D.SS.getScopeRep()->getAsNamespaceAlias()) {
591 SourceLocation IdLoc = ConsumeToken();
593 Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
594 D.Name.setConstructorName(Type, IdLoc, IdLoc);
596 if (ParseUnqualifiedId(
597 D.SS, /*EnteringContext=*/false,
598 /*AllowDestructorName=*/true,
599 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
600 NextToken().is(tok::equal)),
601 /*AllowDeductionGuide=*/false,
602 nullptr, D.TemplateKWLoc, D.Name))
606 if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
607 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z ?
608 diag::warn_cxx1z_compat_using_declaration_pack :
609 diag::ext_using_declaration_pack);
614 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
615 /// Assumes that 'using' was already seen.
617 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
618 /// 'using' using-declarator-list[opt] ;
620 /// using-declarator-list: [C++1z]
621 /// using-declarator '...'[opt]
622 /// using-declarator-list ',' using-declarator '...'[opt]
624 /// using-declarator-list: [C++98-14]
627 /// alias-declaration: C++11 [dcl.dcl]p1
628 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
630 Parser::DeclGroupPtrTy
631 Parser::ParseUsingDeclaration(unsigned Context,
632 const ParsedTemplateInfo &TemplateInfo,
633 SourceLocation UsingLoc, SourceLocation &DeclEnd,
634 AccessSpecifier AS) {
635 // Check for misplaced attributes before the identifier in an
636 // alias-declaration.
637 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
638 MaybeParseCXX11Attributes(MisplacedAttrs);
641 bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
643 ParsedAttributesWithRange Attrs(AttrFactory);
644 MaybeParseGNUAttributes(Attrs);
645 MaybeParseCXX11Attributes(Attrs);
647 // Maybe this is an alias-declaration.
648 if (Tok.is(tok::equal)) {
649 if (InvalidDeclarator) {
650 SkipUntil(tok::semi);
654 // If we had any misplaced attributes from earlier, this is where they
655 // should have been written.
656 if (MisplacedAttrs.Range.isValid()) {
657 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
658 << FixItHint::CreateInsertionFromRange(
660 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
661 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
662 Attrs.takeAllFrom(MisplacedAttrs);
665 Decl *DeclFromDeclSpec = nullptr;
666 Decl *AD = ParseAliasDeclarationAfterDeclarator(
667 TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
668 return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
671 // C++11 attributes are not allowed on a using-declaration, but GNU ones
673 ProhibitAttributes(MisplacedAttrs);
674 ProhibitAttributes(Attrs);
676 // Diagnose an attempt to declare a templated using-declaration.
677 // In C++11, alias-declarations can be templates:
678 // template <...> using id = type;
679 if (TemplateInfo.Kind) {
680 SourceRange R = TemplateInfo.getSourceRange();
681 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
682 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
684 // Unfortunately, we have to bail out instead of recovering by
685 // ignoring the parameters, just in case the nested name specifier
686 // depends on the parameters.
690 SmallVector<Decl *, 8> DeclsInGroup;
692 // Parse (optional) attributes (most likely GNU strong-using extension).
693 MaybeParseGNUAttributes(Attrs);
695 if (InvalidDeclarator)
696 SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
698 // "typename" keyword is allowed for identifiers only,
699 // because it may be a type definition.
700 if (D.TypenameLoc.isValid() &&
701 D.Name.getKind() != UnqualifiedId::IK_Identifier) {
702 Diag(D.Name.getSourceRange().getBegin(),
703 diag::err_typename_identifiers_only)
704 << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
705 // Proceed parsing, but discard the typename keyword.
706 D.TypenameLoc = SourceLocation();
709 Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
710 D.TypenameLoc, D.SS, D.Name,
711 D.EllipsisLoc, Attrs.getList());
713 DeclsInGroup.push_back(UD);
716 if (!TryConsumeToken(tok::comma))
719 // Parse another using-declarator.
721 InvalidDeclarator = ParseUsingDeclarator(Context, D);
724 if (DeclsInGroup.size() > 1)
725 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z ?
726 diag::warn_cxx1z_compat_multi_using_declaration :
727 diag::ext_multi_using_declaration);
730 DeclEnd = Tok.getLocation();
731 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
732 !Attrs.empty() ? "attributes list"
733 : "using declaration"))
734 SkipUntil(tok::semi);
736 return Actions.BuildDeclaratorGroup(DeclsInGroup);
739 Decl *Parser::ParseAliasDeclarationAfterDeclarator(
740 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
741 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
742 ParsedAttributes &Attrs, Decl **OwnedType) {
743 if (ExpectAndConsume(tok::equal)) {
744 SkipUntil(tok::semi);
748 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
749 diag::warn_cxx98_compat_alias_declaration :
750 diag::ext_alias_declaration);
752 // Type alias templates cannot be specialized.
754 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
755 D.Name.getKind() == UnqualifiedId::IK_TemplateId)
757 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
759 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
761 if (SpecKind != -1) {
764 Range = SourceRange(D.Name.TemplateId->LAngleLoc,
765 D.Name.TemplateId->RAngleLoc);
767 Range = TemplateInfo.getSourceRange();
768 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
769 << SpecKind << Range;
770 SkipUntil(tok::semi);
774 // Name must be an identifier.
775 if (D.Name.getKind() != UnqualifiedId::IK_Identifier) {
776 Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
777 // No removal fixit: can't recover from this.
778 SkipUntil(tok::semi);
780 } else if (D.TypenameLoc.isValid())
781 Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
782 << FixItHint::CreateRemoval(SourceRange(
784 D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
785 else if (D.SS.isNotEmpty())
786 Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
787 << FixItHint::CreateRemoval(D.SS.getRange());
788 if (D.EllipsisLoc.isValid())
789 Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
790 << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
792 Decl *DeclFromDeclSpec = nullptr;
793 TypeResult TypeAlias =
794 ParseTypeName(nullptr,
795 TemplateInfo.Kind ? Declarator::AliasTemplateContext
796 : Declarator::AliasDeclContext,
797 AS, &DeclFromDeclSpec, &Attrs);
799 *OwnedType = DeclFromDeclSpec;
802 DeclEnd = Tok.getLocation();
803 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
804 !Attrs.empty() ? "attributes list"
805 : "alias declaration"))
806 SkipUntil(tok::semi);
808 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
809 MultiTemplateParamsArg TemplateParamsArg(
810 TemplateParams ? TemplateParams->data() : nullptr,
811 TemplateParams ? TemplateParams->size() : 0);
812 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
813 UsingLoc, D.Name, Attrs.getList(),
814 TypeAlias, DeclFromDeclSpec);
817 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
819 /// [C++0x] static_assert-declaration:
820 /// static_assert ( constant-expression , string-literal ) ;
822 /// [C11] static_assert-declaration:
823 /// _Static_assert ( constant-expression , string-literal ) ;
825 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
826 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
827 "Not a static_assert declaration");
829 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
830 Diag(Tok, diag::ext_c11_static_assert);
831 if (Tok.is(tok::kw_static_assert))
832 Diag(Tok, diag::warn_cxx98_compat_static_assert);
834 SourceLocation StaticAssertLoc = ConsumeToken();
836 BalancedDelimiterTracker T(*this, tok::l_paren);
837 if (T.consumeOpen()) {
838 Diag(Tok, diag::err_expected) << tok::l_paren;
843 EnterExpressionEvaluationContext ConstantEvaluated(
844 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
845 ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
846 if (AssertExpr.isInvalid()) {
851 ExprResult AssertMessage;
852 if (Tok.is(tok::r_paren)) {
853 Diag(Tok, getLangOpts().CPlusPlus1z
854 ? diag::warn_cxx14_compat_static_assert_no_message
855 : diag::ext_static_assert_no_message)
856 << (getLangOpts().CPlusPlus1z
858 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
860 if (ExpectAndConsume(tok::comma)) {
861 SkipUntil(tok::semi);
865 if (!isTokenStringLiteral()) {
866 Diag(Tok, diag::err_expected_string_literal)
867 << /*Source='static_assert'*/1;
872 AssertMessage = ParseStringLiteralExpression();
873 if (AssertMessage.isInvalid()) {
881 DeclEnd = Tok.getLocation();
882 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
884 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
887 T.getCloseLocation());
890 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
892 /// 'decltype' ( expression )
893 /// 'decltype' ( 'auto' ) [C++1y]
895 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
896 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
897 && "Not a decltype specifier");
900 SourceLocation StartLoc = Tok.getLocation();
901 SourceLocation EndLoc;
903 if (Tok.is(tok::annot_decltype)) {
904 Result = getExprAnnotation(Tok);
905 EndLoc = Tok.getAnnotationEndLoc();
906 ConsumeAnnotationToken();
907 if (Result.isInvalid()) {
908 DS.SetTypeSpecError();
912 if (Tok.getIdentifierInfo()->isStr("decltype"))
913 Diag(Tok, diag::warn_cxx98_compat_decltype);
917 BalancedDelimiterTracker T(*this, tok::l_paren);
918 if (T.expectAndConsume(diag::err_expected_lparen_after,
919 "decltype", tok::r_paren)) {
920 DS.SetTypeSpecError();
921 return T.getOpenLocation() == Tok.getLocation() ?
922 StartLoc : T.getOpenLocation();
925 // Check for C++1y 'decltype(auto)'.
926 if (Tok.is(tok::kw_auto)) {
927 // No need to disambiguate here: an expression can't start with 'auto',
928 // because the typename-specifier in a function-style cast operation can't
930 Diag(Tok.getLocation(),
931 getLangOpts().CPlusPlus14
932 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
933 : diag::ext_decltype_auto_type_specifier);
936 // Parse the expression
938 // C++11 [dcl.type.simple]p4:
939 // The operand of the decltype specifier is an unevaluated operand.
940 EnterExpressionEvaluationContext Unevaluated(
941 Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
942 /*IsDecltype=*/true);
944 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
945 return E->hasPlaceholderType() ? ExprError() : E;
947 if (Result.isInvalid()) {
948 DS.SetTypeSpecError();
949 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
950 EndLoc = ConsumeParen();
952 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
953 // Backtrack to get the location of the last token before the semi.
954 PP.RevertCachedTokens(2);
955 ConsumeToken(); // the semi.
956 EndLoc = ConsumeAnyToken();
957 assert(Tok.is(tok::semi));
959 EndLoc = Tok.getLocation();
965 Result = Actions.ActOnDecltypeExpression(Result.get());
970 if (T.getCloseLocation().isInvalid()) {
971 DS.SetTypeSpecError();
972 // FIXME: this should return the location of the last token
973 // that was consumed (by "consumeClose()")
974 return T.getCloseLocation();
977 if (Result.isInvalid()) {
978 DS.SetTypeSpecError();
979 return T.getCloseLocation();
982 EndLoc = T.getCloseLocation();
984 assert(!Result.isInvalid());
986 const char *PrevSpec = nullptr;
988 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
989 // Check for duplicate type specifiers (e.g. "int decltype(a)").
991 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
992 DiagID, Result.get(), Policy)
993 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
995 Diag(StartLoc, DiagID) << PrevSpec;
996 DS.SetTypeSpecError();
1001 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
1002 SourceLocation StartLoc,
1003 SourceLocation EndLoc) {
1004 // make sure we have a token we can turn into an annotation token
1005 if (PP.isBacktrackEnabled())
1006 PP.RevertCachedTokens(1);
1010 Tok.setKind(tok::annot_decltype);
1011 setExprAnnotation(Tok,
1012 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
1013 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
1015 Tok.setAnnotationEndLoc(EndLoc);
1016 Tok.setLocation(StartLoc);
1017 PP.AnnotateCachedTokens(Tok);
1020 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
1021 assert(Tok.is(tok::kw___underlying_type) &&
1022 "Not an underlying type specifier");
1024 SourceLocation StartLoc = ConsumeToken();
1025 BalancedDelimiterTracker T(*this, tok::l_paren);
1026 if (T.expectAndConsume(diag::err_expected_lparen_after,
1027 "__underlying_type", tok::r_paren)) {
1031 TypeResult Result = ParseTypeName();
1032 if (Result.isInvalid()) {
1033 SkipUntil(tok::r_paren, StopAtSemi);
1039 if (T.getCloseLocation().isInvalid())
1042 const char *PrevSpec = nullptr;
1044 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
1045 DiagID, Result.get(),
1046 Actions.getASTContext().getPrintingPolicy()))
1047 Diag(StartLoc, DiagID) << PrevSpec;
1048 DS.setTypeofParensRange(T.getRange());
1051 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
1052 /// class name or decltype-specifier. Note that we only check that the result
1053 /// names a type; semantic analysis will need to verify that the type names a
1054 /// class. The result is either a type or null, depending on whether a type
1057 /// base-type-specifier: [C++11 class.derived]
1058 /// class-or-decltype
1059 /// class-or-decltype: [C++11 class.derived]
1060 /// nested-name-specifier[opt] class-name
1061 /// decltype-specifier
1062 /// class-name: [C++ class.name]
1064 /// simple-template-id
1066 /// In C++98, instead of base-type-specifier, we have:
1068 /// ::[opt] nested-name-specifier[opt] class-name
1069 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
1070 SourceLocation &EndLocation) {
1071 // Ignore attempts to use typename
1072 if (Tok.is(tok::kw_typename)) {
1073 Diag(Tok, diag::err_expected_class_name_not_template)
1074 << FixItHint::CreateRemoval(Tok.getLocation());
1078 // Parse optional nested-name-specifier
1080 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
1082 BaseLoc = Tok.getLocation();
1084 // Parse decltype-specifier
1085 // tok == kw_decltype is just error recovery, it can only happen when SS
1087 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
1088 if (SS.isNotEmpty())
1089 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
1090 << FixItHint::CreateRemoval(SS.getRange());
1091 // Fake up a Declarator to use with ActOnTypeName.
1092 DeclSpec DS(AttrFactory);
1094 EndLocation = ParseDecltypeSpecifier(DS);
1096 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1097 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1100 // Check whether we have a template-id that names a type.
1101 if (Tok.is(tok::annot_template_id)) {
1102 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1103 if (TemplateId->Kind == TNK_Type_template ||
1104 TemplateId->Kind == TNK_Dependent_template_name) {
1105 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1107 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
1108 ParsedType Type = getTypeAnnotation(Tok);
1109 EndLocation = Tok.getAnnotationEndLoc();
1110 ConsumeAnnotationToken();
1117 // Fall through to produce an error below.
1120 if (Tok.isNot(tok::identifier)) {
1121 Diag(Tok, diag::err_expected_class_name);
1125 IdentifierInfo *Id = Tok.getIdentifierInfo();
1126 SourceLocation IdLoc = ConsumeToken();
1128 if (Tok.is(tok::less)) {
1129 // It looks the user intended to write a template-id here, but the
1130 // template-name was wrong. Try to fix that.
1131 TemplateNameKind TNK = TNK_Type_template;
1132 TemplateTy Template;
1133 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
1134 &SS, Template, TNK)) {
1135 Diag(IdLoc, diag::err_unknown_template_name)
1140 TemplateArgList TemplateArgs;
1141 SourceLocation LAngleLoc, RAngleLoc;
1142 ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1147 // Form the template name
1148 UnqualifiedId TemplateName;
1149 TemplateName.setIdentifier(Id, IdLoc);
1151 // Parse the full template-id, then turn it into a type.
1152 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1155 if (TNK == TNK_Type_template || TNK == TNK_Dependent_template_name)
1156 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
1158 // If we didn't end up with a typename token, there's nothing more we
1160 if (Tok.isNot(tok::annot_typename))
1163 // Retrieve the type from the annotation token, consume that token, and
1165 EndLocation = Tok.getAnnotationEndLoc();
1166 ParsedType Type = getTypeAnnotation(Tok);
1167 ConsumeAnnotationToken();
1171 // We have an identifier; check whether it is actually a type.
1172 IdentifierInfo *CorrectedII = nullptr;
1173 ParsedType Type = Actions.getTypeName(
1174 *Id, IdLoc, getCurScope(), &SS, /*IsClassName=*/true, false, nullptr,
1175 /*IsCtorOrDtorName=*/false,
1176 /*NonTrivialTypeSourceInfo=*/true,
1177 /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
1179 Diag(IdLoc, diag::err_expected_class_name);
1183 // Consume the identifier.
1184 EndLocation = IdLoc;
1186 // Fake up a Declarator to use with ActOnTypeName.
1187 DeclSpec DS(AttrFactory);
1188 DS.SetRangeStart(IdLoc);
1189 DS.SetRangeEnd(EndLocation);
1190 DS.getTypeSpecScope() = SS;
1192 const char *PrevSpec = nullptr;
1194 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1195 Actions.getASTContext().getPrintingPolicy());
1197 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1198 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1201 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1202 while (Tok.isOneOf(tok::kw___single_inheritance,
1203 tok::kw___multiple_inheritance,
1204 tok::kw___virtual_inheritance)) {
1205 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1206 SourceLocation AttrNameLoc = ConsumeToken();
1207 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1208 AttributeList::AS_Keyword);
1212 /// Determine whether the following tokens are valid after a type-specifier
1213 /// which could be a standalone declaration. This will conservatively return
1214 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1215 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1216 // This switch enumerates the valid "follow" set for type-specifiers.
1217 switch (Tok.getKind()) {
1219 case tok::semi: // struct foo {...} ;
1220 case tok::star: // struct foo {...} * P;
1221 case tok::amp: // struct foo {...} & R = ...
1222 case tok::ampamp: // struct foo {...} && R = ...
1223 case tok::identifier: // struct foo {...} V ;
1224 case tok::r_paren: //(struct foo {...} ) {4}
1225 case tok::annot_cxxscope: // struct foo {...} a:: b;
1226 case tok::annot_typename: // struct foo {...} a ::b;
1227 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1228 case tok::l_paren: // struct foo {...} ( x);
1229 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1230 case tok::kw_operator: // struct foo operator ++() {...}
1231 case tok::kw___declspec: // struct foo {...} __declspec(...)
1232 case tok::l_square: // void f(struct f [ 3])
1233 case tok::ellipsis: // void f(struct f ... [Ns])
1234 // FIXME: we should emit semantic diagnostic when declaration
1235 // attribute is in type attribute position.
1236 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1237 case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
1238 // struct foo {...} _Pragma(section(...));
1239 case tok::annot_pragma_ms_pragma:
1240 // struct foo {...} _Pragma(vtordisp(pop));
1241 case tok::annot_pragma_ms_vtordisp:
1242 // struct foo {...} _Pragma(pointers_to_members(...));
1243 case tok::annot_pragma_ms_pointers_to_members:
1246 return CouldBeBitfield; // enum E { ... } : 2;
1247 // Microsoft compatibility
1248 case tok::kw___cdecl: // struct foo {...} __cdecl x;
1249 case tok::kw___fastcall: // struct foo {...} __fastcall x;
1250 case tok::kw___stdcall: // struct foo {...} __stdcall x;
1251 case tok::kw___thiscall: // struct foo {...} __thiscall x;
1252 case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
1253 // We will diagnose these calling-convention specifiers on non-function
1254 // declarations later, so claim they are valid after a type specifier.
1255 return getLangOpts().MicrosoftExt;
1257 case tok::kw_const: // struct foo {...} const x;
1258 case tok::kw_volatile: // struct foo {...} volatile x;
1259 case tok::kw_restrict: // struct foo {...} restrict x;
1260 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1261 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1262 // Function specifiers
1263 // Note, no 'explicit'. An explicit function must be either a conversion
1264 // operator or a constructor. Either way, it can't have a return type.
1265 case tok::kw_inline: // struct foo inline f();
1266 case tok::kw_virtual: // struct foo virtual f();
1267 case tok::kw_friend: // struct foo friend f();
1268 // Storage-class specifiers
1269 case tok::kw_static: // struct foo {...} static x;
1270 case tok::kw_extern: // struct foo {...} extern x;
1271 case tok::kw_typedef: // struct foo {...} typedef x;
1272 case tok::kw_register: // struct foo {...} register x;
1273 case tok::kw_auto: // struct foo {...} auto x;
1274 case tok::kw_mutable: // struct foo {...} mutable x;
1275 case tok::kw_thread_local: // struct foo {...} thread_local x;
1276 case tok::kw_constexpr: // struct foo {...} constexpr x;
1277 // As shown above, type qualifiers and storage class specifiers absolutely
1278 // can occur after class specifiers according to the grammar. However,
1279 // almost no one actually writes code like this. If we see one of these,
1280 // it is much more likely that someone missed a semi colon and the
1281 // type/storage class specifier we're seeing is part of the *next*
1282 // intended declaration, as in:
1284 // struct foo { ... }
1287 // We'd really like to emit a missing semicolon error instead of emitting
1288 // an error on the 'int' saying that you can't have two type specifiers in
1289 // the same declaration of X. Because of this, we look ahead past this
1290 // token to see if it's a type specifier. If so, we know the code is
1291 // otherwise invalid, so we can produce the expected semi error.
1292 if (!isKnownToBeTypeSpecifier(NextToken()))
1295 case tok::r_brace: // struct bar { struct foo {...} }
1296 // Missing ';' at end of struct is accepted as an extension in C mode.
1297 if (!getLangOpts().CPlusPlus)
1301 // template<class T = class X>
1302 return getLangOpts().CPlusPlus;
1307 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1308 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1309 /// until we reach the start of a definition or see a token that
1310 /// cannot start a definition.
1312 /// class-specifier: [C++ class]
1313 /// class-head '{' member-specification[opt] '}'
1314 /// class-head '{' member-specification[opt] '}' attributes[opt]
1316 /// class-key identifier[opt] base-clause[opt]
1317 /// class-key nested-name-specifier identifier base-clause[opt]
1318 /// class-key nested-name-specifier[opt] simple-template-id
1319 /// base-clause[opt]
1320 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1321 /// [GNU] class-key attributes[opt] nested-name-specifier
1322 /// identifier base-clause[opt]
1323 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1324 /// simple-template-id base-clause[opt]
1330 /// elaborated-type-specifier: [C++ dcl.type.elab]
1331 /// class-key ::[opt] nested-name-specifier[opt] identifier
1332 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1333 /// simple-template-id
1335 /// Note that the C++ class-specifier and elaborated-type-specifier,
1336 /// together, subsume the C99 struct-or-union-specifier:
1338 /// struct-or-union-specifier: [C99 6.7.2.1]
1339 /// struct-or-union identifier[opt] '{' struct-contents '}'
1340 /// struct-or-union identifier
1341 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1342 /// '}' attributes[opt]
1343 /// [GNU] struct-or-union attributes[opt] identifier
1344 /// struct-or-union:
1347 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1348 SourceLocation StartLoc, DeclSpec &DS,
1349 const ParsedTemplateInfo &TemplateInfo,
1351 bool EnteringContext, DeclSpecContext DSC,
1352 ParsedAttributesWithRange &Attributes) {
1353 DeclSpec::TST TagType;
1354 if (TagTokKind == tok::kw_struct)
1355 TagType = DeclSpec::TST_struct;
1356 else if (TagTokKind == tok::kw___interface)
1357 TagType = DeclSpec::TST_interface;
1358 else if (TagTokKind == tok::kw_class)
1359 TagType = DeclSpec::TST_class;
1361 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1362 TagType = DeclSpec::TST_union;
1365 if (Tok.is(tok::code_completion)) {
1366 // Code completion for a struct, class, or union name.
1367 Actions.CodeCompleteTag(getCurScope(), TagType);
1368 return cutOffParsing();
1371 // C++03 [temp.explicit] 14.7.2/8:
1372 // The usual access checking rules do not apply to names used to specify
1373 // explicit instantiations.
1375 // As an extension we do not perform access checking on the names used to
1376 // specify explicit specializations either. This is important to allow
1377 // specializing traits classes for private types.
1379 // Note that we don't suppress if this turns out to be an elaborated
1381 bool shouldDelayDiagsInTag =
1382 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1383 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1384 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1386 ParsedAttributesWithRange attrs(AttrFactory);
1387 // If attributes exist after tag, parse them.
1388 MaybeParseGNUAttributes(attrs);
1389 MaybeParseMicrosoftDeclSpecs(attrs);
1391 // Parse inheritance specifiers.
1392 if (Tok.isOneOf(tok::kw___single_inheritance,
1393 tok::kw___multiple_inheritance,
1394 tok::kw___virtual_inheritance))
1395 ParseMicrosoftInheritanceClassAttributes(attrs);
1397 // If C++0x attributes exist here, parse them.
1398 // FIXME: Are we consistent with the ordering of parsing of different
1399 // styles of attributes?
1400 MaybeParseCXX11Attributes(attrs);
1402 // Source location used by FIXIT to insert misplaced
1404 SourceLocation AttrFixitLoc = Tok.getLocation();
1406 if (TagType == DeclSpec::TST_struct &&
1407 Tok.isNot(tok::identifier) &&
1408 !Tok.isAnnotation() &&
1409 Tok.getIdentifierInfo() &&
1410 Tok.isOneOf(tok::kw___is_abstract,
1411 tok::kw___is_aggregate,
1412 tok::kw___is_arithmetic,
1414 tok::kw___is_assignable,
1415 tok::kw___is_base_of,
1417 tok::kw___is_complete_type,
1418 tok::kw___is_compound,
1420 tok::kw___is_constructible,
1421 tok::kw___is_convertible,
1422 tok::kw___is_convertible_to,
1423 tok::kw___is_destructible,
1426 tok::kw___is_floating_point,
1428 tok::kw___is_function,
1429 tok::kw___is_fundamental,
1430 tok::kw___is_integral,
1431 tok::kw___is_interface_class,
1432 tok::kw___is_literal,
1433 tok::kw___is_lvalue_expr,
1434 tok::kw___is_lvalue_reference,
1435 tok::kw___is_member_function_pointer,
1436 tok::kw___is_member_object_pointer,
1437 tok::kw___is_member_pointer,
1438 tok::kw___is_nothrow_assignable,
1439 tok::kw___is_nothrow_constructible,
1440 tok::kw___is_nothrow_destructible,
1441 tok::kw___is_object,
1443 tok::kw___is_pointer,
1444 tok::kw___is_polymorphic,
1445 tok::kw___is_reference,
1446 tok::kw___is_rvalue_expr,
1447 tok::kw___is_rvalue_reference,
1449 tok::kw___is_scalar,
1450 tok::kw___is_sealed,
1451 tok::kw___is_signed,
1452 tok::kw___is_standard_layout,
1453 tok::kw___is_trivial,
1454 tok::kw___is_trivially_assignable,
1455 tok::kw___is_trivially_constructible,
1456 tok::kw___is_trivially_copyable,
1458 tok::kw___is_unsigned,
1460 tok::kw___is_volatile))
1461 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1462 // name of struct templates, but some are keywords in GCC >= 4.3
1463 // and Clang. Therefore, when we see the token sequence "struct
1464 // X", make X into a normal identifier rather than a keyword, to
1465 // allow libstdc++ 4.2 and libc++ to work properly.
1466 TryKeywordIdentFallback(true);
1468 struct PreserveAtomicIdentifierInfoRAII {
1469 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1470 : AtomicII(nullptr) {
1473 assert(Tok.is(tok::kw__Atomic));
1474 AtomicII = Tok.getIdentifierInfo();
1475 AtomicII->revertTokenIDToIdentifier();
1476 Tok.setKind(tok::identifier);
1478 ~PreserveAtomicIdentifierInfoRAII() {
1481 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1483 IdentifierInfo *AtomicII;
1486 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1487 // implementation for VS2013 uses _Atomic as an identifier for one of the
1488 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1489 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1490 // use '_Atomic' in its own header files.
1491 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1492 Tok.is(tok::kw__Atomic) &&
1493 TagType == DeclSpec::TST_struct;
1494 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1495 Tok, ShouldChangeAtomicToIdentifier);
1497 // Parse the (optional) nested-name-specifier.
1498 CXXScopeSpec &SS = DS.getTypeSpecScope();
1499 if (getLangOpts().CPlusPlus) {
1500 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1501 // is a base-specifier-list.
1502 ColonProtectionRAIIObject X(*this);
1505 bool HasValidSpec = true;
1506 if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
1507 DS.SetTypeSpecError();
1508 HasValidSpec = false;
1511 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1512 Diag(Tok, diag::err_expected) << tok::identifier;
1513 HasValidSpec = false;
1519 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1521 // Parse the (optional) class name or simple-template-id.
1522 IdentifierInfo *Name = nullptr;
1523 SourceLocation NameLoc;
1524 TemplateIdAnnotation *TemplateId = nullptr;
1525 if (Tok.is(tok::identifier)) {
1526 Name = Tok.getIdentifierInfo();
1527 NameLoc = ConsumeToken();
1529 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1530 // The name was supposed to refer to a template, but didn't.
1531 // Eat the template argument list and try to continue parsing this as
1532 // a class (or template thereof).
1533 TemplateArgList TemplateArgs;
1534 SourceLocation LAngleLoc, RAngleLoc;
1535 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
1537 // We couldn't parse the template argument list at all, so don't
1538 // try to give any location information for the list.
1539 LAngleLoc = RAngleLoc = SourceLocation();
1542 Diag(NameLoc, diag::err_explicit_spec_non_template)
1543 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1544 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1546 // Strip off the last template parameter list if it was empty, since
1547 // we've removed its template argument list.
1548 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1549 if (TemplateParams->size() > 1) {
1550 TemplateParams->pop_back();
1552 TemplateParams = nullptr;
1553 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1554 = ParsedTemplateInfo::NonTemplate;
1556 } else if (TemplateInfo.Kind
1557 == ParsedTemplateInfo::ExplicitInstantiation) {
1558 // Pretend this is just a forward declaration.
1559 TemplateParams = nullptr;
1560 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1561 = ParsedTemplateInfo::NonTemplate;
1562 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1564 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1568 } else if (Tok.is(tok::annot_template_id)) {
1569 TemplateId = takeTemplateIdAnnotation(Tok);
1570 NameLoc = ConsumeAnnotationToken();
1572 if (TemplateId->Kind != TNK_Type_template &&
1573 TemplateId->Kind != TNK_Dependent_template_name) {
1574 // The template-name in the simple-template-id refers to
1575 // something other than a class template. Give an appropriate
1576 // error message and skip to the ';'.
1577 SourceRange Range(NameLoc);
1578 if (SS.isNotEmpty())
1579 Range.setBegin(SS.getBeginLoc());
1581 // FIXME: Name may be null here.
1582 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1583 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1585 DS.SetTypeSpecError();
1586 SkipUntil(tok::semi, StopBeforeMatch);
1591 // There are four options here.
1592 // - If we are in a trailing return type, this is always just a reference,
1593 // and we must not try to parse a definition. For instance,
1594 // [] () -> struct S { };
1595 // does not define a type.
1596 // - If we have 'struct foo {...', 'struct foo :...',
1597 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1598 // - If we have 'struct foo;', then this is either a forward declaration
1599 // or a friend declaration, which have to be treated differently.
1600 // - Otherwise we have something like 'struct foo xyz', a reference.
1602 // We also detect these erroneous cases to provide better diagnostic for
1603 // C++11 attributes parsing.
1604 // - attributes follow class name:
1605 // struct foo [[]] {};
1606 // - attributes appear before or after 'final':
1607 // struct foo [[]] final [[]] {};
1609 // However, in type-specifier-seq's, things look like declarations but are
1610 // just references, e.g.
1613 // &T::operator struct s;
1614 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
1616 // If there are attributes after class name, parse them.
1617 MaybeParseCXX11Attributes(Attributes);
1619 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1620 Sema::TagUseKind TUK;
1621 if (DSC == DSC_trailing)
1622 TUK = Sema::TUK_Reference;
1623 else if (Tok.is(tok::l_brace) ||
1624 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1625 (isCXX11FinalKeyword() &&
1626 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1627 if (DS.isFriendSpecified()) {
1628 // C++ [class.friend]p2:
1629 // A class shall not be defined in a friend declaration.
1630 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1631 << SourceRange(DS.getFriendSpecLoc());
1633 // Skip everything up to the semicolon, so that this looks like a proper
1634 // friend class (or template thereof) declaration.
1635 SkipUntil(tok::semi, StopBeforeMatch);
1636 TUK = Sema::TUK_Friend;
1638 // Okay, this is a class definition.
1639 TUK = Sema::TUK_Definition;
1641 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1642 NextToken().is(tok::kw_alignas))) {
1643 // We can't tell if this is a definition or reference
1644 // until we skipped the 'final' and C++11 attribute specifiers.
1645 TentativeParsingAction PA(*this);
1647 // Skip the 'final' keyword.
1650 // Skip C++11 attribute specifiers.
1652 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1654 if (!SkipUntil(tok::r_square, StopAtSemi))
1656 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1659 if (!SkipUntil(tok::r_paren, StopAtSemi))
1666 if (Tok.isOneOf(tok::l_brace, tok::colon))
1667 TUK = Sema::TUK_Definition;
1669 TUK = Sema::TUK_Reference;
1672 } else if (!isTypeSpecifier(DSC) &&
1673 (Tok.is(tok::semi) ||
1674 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1675 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1676 if (Tok.isNot(tok::semi)) {
1677 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1678 // A semicolon was missing after this declaration. Diagnose and recover.
1679 ExpectAndConsume(tok::semi, diag::err_expected_after,
1680 DeclSpec::getSpecifierName(TagType, PPol));
1682 Tok.setKind(tok::semi);
1685 TUK = Sema::TUK_Reference;
1687 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1688 // to caller to handle.
1689 if (TUK != Sema::TUK_Reference) {
1690 // If this is not a reference, then the only possible
1691 // valid place for C++11 attributes to appear here
1692 // is between class-key and class-name. If there are
1693 // any attributes after class-name, we try a fixit to move
1694 // them to the right place.
1695 SourceRange AttrRange = Attributes.Range;
1696 if (AttrRange.isValid()) {
1697 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1699 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1700 CharSourceRange(AttrRange, true))
1701 << FixItHint::CreateRemoval(AttrRange);
1703 // Recover by adding misplaced attributes to the attribute list
1704 // of the class so they can be applied on the class later.
1705 attrs.takeAllFrom(Attributes);
1709 // If this is an elaborated type specifier, and we delayed
1710 // diagnostics before, just merge them into the current pool.
1711 if (shouldDelayDiagsInTag) {
1712 diagsFromTag.done();
1713 if (TUK == Sema::TUK_Reference)
1714 diagsFromTag.redelay();
1717 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1718 TUK != Sema::TUK_Definition)) {
1719 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1720 // We have a declaration or reference to an anonymous class.
1721 Diag(StartLoc, diag::err_anon_type_definition)
1722 << DeclSpec::getSpecifierName(TagType, Policy);
1725 // If we are parsing a definition and stop at a base-clause, continue on
1726 // until the semicolon. Continuing from the comma will just trick us into
1727 // thinking we are seeing a variable declaration.
1728 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1729 SkipUntil(tok::semi, StopBeforeMatch);
1731 SkipUntil(tok::comma, StopAtSemi);
1735 // Create the tag portion of the class or class template.
1736 DeclResult TagOrTempResult = true; // invalid
1737 TypeResult TypeResult = true; // invalid
1740 Sema::SkipBodyInfo SkipBody;
1742 // Explicit specialization, class template partial specialization,
1743 // or explicit instantiation.
1744 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1745 TemplateId->NumArgs);
1746 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1747 TUK == Sema::TUK_Declaration) {
1748 // This is an explicit instantiation of a class template.
1749 ProhibitAttributes(attrs);
1752 = Actions.ActOnExplicitInstantiation(getCurScope(),
1753 TemplateInfo.ExternLoc,
1754 TemplateInfo.TemplateLoc,
1758 TemplateId->Template,
1759 TemplateId->TemplateNameLoc,
1760 TemplateId->LAngleLoc,
1762 TemplateId->RAngleLoc,
1765 // Friend template-ids are treated as references unless
1766 // they have template headers, in which case they're ill-formed
1767 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1768 // We diagnose this error in ActOnClassTemplateSpecialization.
1769 } else if (TUK == Sema::TUK_Reference ||
1770 (TUK == Sema::TUK_Friend &&
1771 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1772 ProhibitAttributes(attrs);
1773 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1775 TemplateId->TemplateKWLoc,
1776 TemplateId->Template,
1777 TemplateId->TemplateNameLoc,
1778 TemplateId->LAngleLoc,
1780 TemplateId->RAngleLoc);
1782 // This is an explicit specialization or a class template
1783 // partial specialization.
1784 TemplateParameterLists FakedParamLists;
1785 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1786 // This looks like an explicit instantiation, because we have
1789 // template class Foo<X>
1791 // but it actually has a definition. Most likely, this was
1792 // meant to be an explicit specialization, but the user forgot
1793 // the '<>' after 'template'.
1794 // It this is friend declaration however, since it cannot have a
1795 // template header, it is most likely that the user meant to
1796 // remove the 'template' keyword.
1797 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1798 "Expected a definition here");
1800 if (TUK == Sema::TUK_Friend) {
1801 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1802 TemplateParams = nullptr;
1804 SourceLocation LAngleLoc =
1805 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1806 Diag(TemplateId->TemplateNameLoc,
1807 diag::err_explicit_instantiation_with_definition)
1808 << SourceRange(TemplateInfo.TemplateLoc)
1809 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1811 // Create a fake template parameter list that contains only
1812 // "template<>", so that we treat this construct as a class
1813 // template specialization.
1814 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1815 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1816 LAngleLoc, nullptr));
1817 TemplateParams = &FakedParamLists;
1821 // Build the class template specialization.
1822 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1823 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1824 *TemplateId, attrs.getList(),
1825 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1827 TemplateParams ? TemplateParams->size() : 0),
1830 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1831 TUK == Sema::TUK_Declaration) {
1832 // Explicit instantiation of a member of a class template
1833 // specialization, e.g.,
1835 // template struct Outer<int>::Inner;
1837 ProhibitAttributes(attrs);
1840 = Actions.ActOnExplicitInstantiation(getCurScope(),
1841 TemplateInfo.ExternLoc,
1842 TemplateInfo.TemplateLoc,
1843 TagType, StartLoc, SS, Name,
1844 NameLoc, attrs.getList());
1845 } else if (TUK == Sema::TUK_Friend &&
1846 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1847 ProhibitAttributes(attrs);
1850 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1851 TagType, StartLoc, SS,
1852 Name, NameLoc, attrs.getList(),
1853 MultiTemplateParamsArg(
1854 TemplateParams? &(*TemplateParams)[0]
1856 TemplateParams? TemplateParams->size() : 0));
1858 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1859 ProhibitAttributes(attrs);
1861 if (TUK == Sema::TUK_Definition &&
1862 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1863 // If the declarator-id is not a template-id, issue a diagnostic and
1864 // recover by ignoring the 'template' keyword.
1865 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1866 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1867 TemplateParams = nullptr;
1870 bool IsDependent = false;
1872 // Don't pass down template parameter lists if this is just a tag
1873 // reference. For example, we don't need the template parameters here:
1874 // template <class T> class A *makeA(T t);
1875 MultiTemplateParamsArg TParams;
1876 if (TUK != Sema::TUK_Reference && TemplateParams)
1878 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1880 stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
1882 // Declaration or definition of a class type
1883 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1884 SS, Name, NameLoc, attrs.getList(), AS,
1885 DS.getModulePrivateSpecLoc(),
1886 TParams, Owned, IsDependent,
1887 SourceLocation(), false,
1888 clang::TypeResult(),
1889 DSC == DSC_type_specifier,
1890 DSC == DSC_template_param ||
1891 DSC == DSC_template_type_arg, &SkipBody);
1893 // If ActOnTag said the type was dependent, try again with the
1894 // less common call.
1896 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1897 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1898 SS, Name, StartLoc, NameLoc);
1902 // If there is a body, parse it and inform the actions module.
1903 if (TUK == Sema::TUK_Definition) {
1904 assert(Tok.is(tok::l_brace) ||
1905 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1906 isCXX11FinalKeyword());
1907 if (SkipBody.ShouldSkip)
1908 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1909 TagOrTempResult.get());
1910 else if (getLangOpts().CPlusPlus)
1911 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1912 TagOrTempResult.get());
1915 SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
1916 // Parse the definition body.
1917 ParseStructUnionBody(StartLoc, TagType, D);
1918 if (SkipBody.CheckSameAsPrevious &&
1919 !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
1921 DS.SetTypeSpecError();
1927 if (!TagOrTempResult.isInvalid())
1928 // Delayed processing of attributes.
1929 Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs.getList());
1931 const char *PrevSpec = nullptr;
1934 if (!TypeResult.isInvalid()) {
1935 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1936 NameLoc.isValid() ? NameLoc : StartLoc,
1937 PrevSpec, DiagID, TypeResult.get(), Policy);
1938 } else if (!TagOrTempResult.isInvalid()) {
1939 Result = DS.SetTypeSpecType(TagType, StartLoc,
1940 NameLoc.isValid() ? NameLoc : StartLoc,
1941 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1944 DS.SetTypeSpecError();
1949 Diag(StartLoc, DiagID) << PrevSpec;
1951 // At this point, we've successfully parsed a class-specifier in 'definition'
1952 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1953 // going to look at what comes after it to improve error recovery. If an
1954 // impossible token occurs next, we assume that the programmer forgot a ; at
1955 // the end of the declaration and recover that way.
1957 // Also enforce C++ [temp]p3:
1958 // In a template-declaration which defines a class, no declarator
1961 // After a type-specifier, we don't expect a semicolon. This only happens in
1962 // C, since definitions are not permitted in this context in C++.
1963 if (TUK == Sema::TUK_Definition &&
1964 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1965 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1966 if (Tok.isNot(tok::semi)) {
1967 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1968 ExpectAndConsume(tok::semi, diag::err_expected_after,
1969 DeclSpec::getSpecifierName(TagType, PPol));
1970 // Push this token back into the preprocessor and change our current token
1971 // to ';' so that the rest of the code recovers as though there were an
1972 // ';' after the definition.
1974 Tok.setKind(tok::semi);
1979 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1981 /// base-clause : [C++ class.derived]
1982 /// ':' base-specifier-list
1983 /// base-specifier-list:
1984 /// base-specifier '...'[opt]
1985 /// base-specifier-list ',' base-specifier '...'[opt]
1986 void Parser::ParseBaseClause(Decl *ClassDecl) {
1987 assert(Tok.is(tok::colon) && "Not a base clause");
1990 // Build up an array of parsed base specifiers.
1991 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1994 // Parse a base-specifier.
1995 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1996 if (Result.isInvalid()) {
1997 // Skip the rest of this base specifier, up until the comma or
1999 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
2001 // Add this to our array of base specifiers.
2002 BaseInfo.push_back(Result.get());
2005 // If the next token is a comma, consume it and keep reading
2007 if (!TryConsumeToken(tok::comma))
2011 // Attach the base specifiers
2012 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
2015 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
2016 /// one entry in the base class list of a class specifier, for example:
2017 /// class foo : public bar, virtual private baz {
2018 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2020 /// base-specifier: [C++ class.derived]
2021 /// attribute-specifier-seq[opt] base-type-specifier
2022 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
2023 /// base-type-specifier
2024 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
2025 /// base-type-specifier
2026 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
2027 bool IsVirtual = false;
2028 SourceLocation StartLoc = Tok.getLocation();
2030 ParsedAttributesWithRange Attributes(AttrFactory);
2031 MaybeParseCXX11Attributes(Attributes);
2033 // Parse the 'virtual' keyword.
2034 if (TryConsumeToken(tok::kw_virtual))
2037 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2039 // Parse an (optional) access specifier.
2040 AccessSpecifier Access = getAccessSpecifierIfPresent();
2041 if (Access != AS_none)
2044 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2046 // Parse the 'virtual' keyword (again!), in case it came after the
2047 // access specifier.
2048 if (Tok.is(tok::kw_virtual)) {
2049 SourceLocation VirtualLoc = ConsumeToken();
2051 // Complain about duplicate 'virtual'
2052 Diag(VirtualLoc, diag::err_dup_virtual)
2053 << FixItHint::CreateRemoval(VirtualLoc);
2059 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
2061 // Parse the class-name.
2063 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
2064 // implementation for VS2013 uses _Atomic as an identifier for one of the
2065 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
2066 // parsing the class-name for a base specifier.
2067 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
2068 NextToken().is(tok::less))
2069 Tok.setKind(tok::identifier);
2071 SourceLocation EndLocation;
2072 SourceLocation BaseLoc;
2073 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
2074 if (BaseType.isInvalid())
2077 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
2078 // actually part of the base-specifier-list grammar productions, but we
2079 // parse it here for convenience.
2080 SourceLocation EllipsisLoc;
2081 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2083 // Find the complete source range for the base-specifier.
2084 SourceRange Range(StartLoc, EndLocation);
2086 // Notify semantic analysis that we have parsed a complete
2088 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
2089 Access, BaseType.get(), BaseLoc,
2093 /// getAccessSpecifierIfPresent - Determine whether the next token is
2094 /// a C++ access-specifier.
2096 /// access-specifier: [C++ class.derived]
2100 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
2101 switch (Tok.getKind()) {
2102 default: return AS_none;
2103 case tok::kw_private: return AS_private;
2104 case tok::kw_protected: return AS_protected;
2105 case tok::kw_public: return AS_public;
2109 /// \brief If the given declarator has any parts for which parsing has to be
2110 /// delayed, e.g., default arguments or an exception-specification, create a
2111 /// late-parsed method declaration record to handle the parsing at the end of
2112 /// the class definition.
2113 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
2115 DeclaratorChunk::FunctionTypeInfo &FTI
2116 = DeclaratorInfo.getFunctionTypeInfo();
2117 // If there was a late-parsed exception-specification, we'll need a
2119 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
2121 if (!NeedLateParse) {
2122 // Look ahead to see if there are any default args
2123 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
2124 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
2125 if (Param->hasUnparsedDefaultArg()) {
2126 NeedLateParse = true;
2132 if (NeedLateParse) {
2133 // Push this method onto the stack of late-parsed method
2135 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
2136 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
2137 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
2139 // Stash the exception-specification tokens in the late-pased method.
2140 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
2141 FTI.ExceptionSpecTokens = nullptr;
2143 // Push tokens for each parameter. Those that do not have
2144 // defaults will be NULL.
2145 LateMethod->DefaultArgs.reserve(FTI.NumParams);
2146 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
2147 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
2148 FTI.Params[ParamIdx].Param,
2149 std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
2153 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
2160 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
2161 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
2162 return VirtSpecifiers::VS_None;
2164 IdentifierInfo *II = Tok.getIdentifierInfo();
2166 // Initialize the contextual keywords.
2168 Ident_final = &PP.getIdentifierTable().get("final");
2169 if (getLangOpts().GNUKeywords)
2170 Ident_GNU_final = &PP.getIdentifierTable().get("__final");
2171 if (getLangOpts().MicrosoftExt)
2172 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2173 Ident_override = &PP.getIdentifierTable().get("override");
2176 if (II == Ident_override)
2177 return VirtSpecifiers::VS_Override;
2179 if (II == Ident_sealed)
2180 return VirtSpecifiers::VS_Sealed;
2182 if (II == Ident_final)
2183 return VirtSpecifiers::VS_Final;
2185 if (II == Ident_GNU_final)
2186 return VirtSpecifiers::VS_GNU_Final;
2188 return VirtSpecifiers::VS_None;
2191 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2193 /// virt-specifier-seq:
2195 /// virt-specifier-seq virt-specifier
2196 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2198 SourceLocation FriendLoc) {
2200 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2201 if (Specifier == VirtSpecifiers::VS_None)
2204 if (FriendLoc.isValid()) {
2205 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2206 << VirtSpecifiers::getSpecifierName(Specifier)
2207 << FixItHint::CreateRemoval(Tok.getLocation())
2208 << SourceRange(FriendLoc, FriendLoc);
2213 // C++ [class.mem]p8:
2214 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2215 const char *PrevSpec = nullptr;
2216 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2217 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2219 << FixItHint::CreateRemoval(Tok.getLocation());
2221 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2222 Specifier == VirtSpecifiers::VS_Sealed)) {
2223 Diag(Tok.getLocation(), diag::err_override_control_interface)
2224 << VirtSpecifiers::getSpecifierName(Specifier);
2225 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2226 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2227 } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
2228 Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
2230 Diag(Tok.getLocation(),
2231 getLangOpts().CPlusPlus11
2232 ? diag::warn_cxx98_compat_override_control_keyword
2233 : diag::ext_override_control_keyword)
2234 << VirtSpecifiers::getSpecifierName(Specifier);
2240 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2241 /// 'final' or Microsoft 'sealed' contextual keyword.
2242 bool Parser::isCXX11FinalKeyword() const {
2243 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2244 return Specifier == VirtSpecifiers::VS_Final ||
2245 Specifier == VirtSpecifiers::VS_GNU_Final ||
2246 Specifier == VirtSpecifiers::VS_Sealed;
2249 /// \brief Parse a C++ member-declarator up to, but not including, the optional
2250 /// brace-or-equal-initializer or pure-specifier.
2251 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2252 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2253 LateParsedAttrList &LateParsedAttrs) {
2254 // member-declarator:
2255 // declarator pure-specifier[opt]
2256 // declarator brace-or-equal-initializer[opt]
2257 // identifier[opt] ':' constant-expression
2258 if (Tok.isNot(tok::colon))
2259 ParseDeclarator(DeclaratorInfo);
2261 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2263 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2264 assert(DeclaratorInfo.isPastIdentifier() &&
2265 "don't know where identifier would go yet?");
2266 BitfieldSize = ParseConstantExpression();
2267 if (BitfieldSize.isInvalid())
2268 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2270 ParseOptionalCXX11VirtSpecifierSeq(
2271 VS, getCurrentClass().IsInterface,
2272 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2274 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2277 // If a simple-asm-expr is present, parse it.
2278 if (Tok.is(tok::kw_asm)) {
2280 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2281 if (AsmLabel.isInvalid())
2282 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2284 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2285 DeclaratorInfo.SetRangeEnd(Loc);
2288 // If attributes exist after the declarator, but before an '{', parse them.
2289 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2291 // For compatibility with code written to older Clang, also accept a
2292 // virt-specifier *after* the GNU attributes.
2293 if (BitfieldSize.isUnset() && VS.isUnset()) {
2294 ParseOptionalCXX11VirtSpecifierSeq(
2295 VS, getCurrentClass().IsInterface,
2296 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2297 if (!VS.isUnset()) {
2298 // If we saw any GNU-style attributes that are known to GCC followed by a
2299 // virt-specifier, issue a GCC-compat warning.
2300 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2302 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2303 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2304 Attr = Attr->getNext();
2306 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2310 // If this has neither a name nor a bit width, something has gone seriously
2311 // wrong. Skip until the semi-colon or }.
2312 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2313 // If so, skip until the semi-colon or a }.
2314 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2320 /// \brief Look for declaration specifiers possibly occurring after C++11
2321 /// virt-specifier-seq and diagnose them.
2322 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2324 VirtSpecifiers &VS) {
2325 DeclSpec DS(AttrFactory);
2327 // GNU-style and C++11 attributes are not allowed here, but they will be
2328 // handled by the caller. Diagnose everything else.
2329 ParseTypeQualifierListOpt(
2330 DS, AR_NoAttributesParsed, false,
2331 /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
2332 Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
2334 D.ExtendWithDeclSpec(DS);
2336 if (D.isFunctionDeclarator()) {
2337 auto &Function = D.getFunctionTypeInfo();
2338 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2339 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2340 const char *FixItName,
2341 SourceLocation SpecLoc,
2342 unsigned* QualifierLoc) {
2343 FixItHint Insertion;
2344 if (DS.getTypeQualifiers() & TypeQual) {
2345 if (!(Function.TypeQuals & TypeQual)) {
2346 std::string Name(FixItName);
2348 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2349 Function.TypeQuals |= TypeQual;
2350 *QualifierLoc = SpecLoc.getRawEncoding();
2352 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2354 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2355 << FixItHint::CreateRemoval(SpecLoc)
2359 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2360 &Function.ConstQualifierLoc);
2361 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2362 &Function.VolatileQualifierLoc);
2363 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2364 &Function.RestrictQualifierLoc);
2367 // Parse ref-qualifiers.
2368 bool RefQualifierIsLValueRef = true;
2369 SourceLocation RefQualifierLoc;
2370 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2371 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2372 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2373 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2374 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2376 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2377 << (RefQualifierIsLValueRef ? "&" : "&&")
2378 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2379 << FixItHint::CreateRemoval(RefQualifierLoc)
2381 D.SetRangeEnd(RefQualifierLoc);
2386 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2388 /// member-declaration:
2389 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2390 /// function-definition ';'[opt]
2391 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2392 /// using-declaration [TODO]
2393 /// [C++0x] static_assert-declaration
2394 /// template-declaration
2395 /// [GNU] '__extension__' member-declaration
2397 /// member-declarator-list:
2398 /// member-declarator
2399 /// member-declarator-list ',' member-declarator
2401 /// member-declarator:
2402 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2403 /// declarator constant-initializer[opt]
2404 /// [C++11] declarator brace-or-equal-initializer[opt]
2405 /// identifier[opt] ':' constant-expression
2407 /// virt-specifier-seq:
2409 /// virt-specifier-seq virt-specifier
2419 /// constant-initializer:
2420 /// '=' constant-expression
2422 Parser::DeclGroupPtrTy
2423 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2424 AttributeList *AccessAttrs,
2425 const ParsedTemplateInfo &TemplateInfo,
2426 ParsingDeclRAIIObject *TemplateDiags) {
2427 if (Tok.is(tok::at)) {
2428 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2429 Diag(Tok, diag::err_at_defs_cxx);
2431 Diag(Tok, diag::err_at_in_class);
2434 SkipUntil(tok::r_brace, StopAtSemi);
2438 // Turn on colon protection early, while parsing declspec, although there is
2439 // nothing to protect there. It prevents from false errors if error recovery
2440 // incorrectly determines where the declspec ends, as in the example:
2441 // struct A { enum class B { C }; };
2443 // struct D { A::B : C; };
2444 ColonProtectionRAIIObject X(*this);
2446 // Access declarations.
2447 bool MalformedTypeSpec = false;
2448 if (!TemplateInfo.Kind &&
2449 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2450 if (TryAnnotateCXXScopeToken())
2451 MalformedTypeSpec = true;
2454 if (Tok.isNot(tok::annot_cxxscope))
2455 isAccessDecl = false;
2456 else if (NextToken().is(tok::identifier))
2457 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2459 isAccessDecl = NextToken().is(tok::kw_operator);
2462 // Collect the scope specifier token we annotated earlier.
2464 ParseOptionalCXXScopeSpecifier(SS, nullptr,
2465 /*EnteringContext=*/false);
2467 if (SS.isInvalid()) {
2468 SkipUntil(tok::semi);
2472 // Try to parse an unqualified-id.
2473 SourceLocation TemplateKWLoc;
2475 if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
2476 TemplateKWLoc, Name)) {
2477 SkipUntil(tok::semi);
2481 // TODO: recover from mistakenly-qualified operator declarations.
2482 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2483 "access declaration")) {
2484 SkipUntil(tok::semi);
2488 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2489 getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
2490 /*TypenameLoc*/ SourceLocation(), SS, Name,
2491 /*EllipsisLoc*/ SourceLocation(), /*AttrList*/ nullptr)));
2495 // static_assert-declaration. A templated static_assert declaration is
2496 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2497 if (!TemplateInfo.Kind &&
2498 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2499 SourceLocation DeclEnd;
2500 return DeclGroupPtrTy::make(
2501 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2504 if (Tok.is(tok::kw_template)) {
2505 assert(!TemplateInfo.TemplateParams &&
2506 "Nested template improperly parsed?");
2507 ObjCDeclContextSwitch ObjCDC(*this);
2508 SourceLocation DeclEnd;
2509 return DeclGroupPtrTy::make(
2510 DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
2511 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
2514 // Handle: member-declaration ::= '__extension__' member-declaration
2515 if (Tok.is(tok::kw___extension__)) {
2516 // __extension__ silences extension warnings in the subexpression.
2517 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2519 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2520 TemplateInfo, TemplateDiags);
2523 ParsedAttributesWithRange attrs(AttrFactory);
2524 ParsedAttributesWithRange FnAttrs(AttrFactory);
2525 // Optional C++11 attribute-specifier
2526 MaybeParseCXX11Attributes(attrs);
2527 // We need to keep these attributes for future diagnostic
2528 // before they are taken over by declaration specifier.
2529 FnAttrs.addAll(attrs.getList());
2530 FnAttrs.Range = attrs.Range;
2532 MaybeParseMicrosoftAttributes(attrs);
2534 if (Tok.is(tok::kw_using)) {
2535 ProhibitAttributes(attrs);
2538 SourceLocation UsingLoc = ConsumeToken();
2540 if (Tok.is(tok::kw_namespace)) {
2541 Diag(UsingLoc, diag::err_using_namespace_in_class);
2542 SkipUntil(tok::semi, StopBeforeMatch);
2545 SourceLocation DeclEnd;
2546 // Otherwise, it must be a using-declaration or an alias-declaration.
2547 return ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2548 UsingLoc, DeclEnd, AS);
2551 // Hold late-parsed attributes so we can attach a Decl to them later.
2552 LateParsedAttrList CommonLateParsedAttrs;
2554 // decl-specifier-seq:
2555 // Parse the common declaration-specifiers piece.
2556 ParsingDeclSpec DS(*this, TemplateDiags);
2557 DS.takeAttributesFrom(attrs);
2558 if (MalformedTypeSpec)
2559 DS.SetTypeSpecError();
2561 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2562 &CommonLateParsedAttrs);
2564 // Turn off colon protection that was set for declspec.
2567 // If we had a free-standing type definition with a missing semicolon, we
2568 // may get this far before the problem becomes obvious.
2569 if (DS.hasTagDefinition() &&
2570 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2571 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2572 &CommonLateParsedAttrs))
2575 MultiTemplateParamsArg TemplateParams(
2576 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2578 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2580 if (TryConsumeToken(tok::semi)) {
2581 if (DS.isFriendSpecified())
2582 ProhibitAttributes(FnAttrs);
2584 RecordDecl *AnonRecord = nullptr;
2585 Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
2586 getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
2587 DS.complete(TheDecl);
2589 Decl* decls[] = {AnonRecord, TheDecl};
2590 return Actions.BuildDeclaratorGroup(decls);
2592 return Actions.ConvertDeclToDeclGroup(TheDecl);
2595 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2598 // Hold late-parsed attributes so we can attach a Decl to them later.
2599 LateParsedAttrList LateParsedAttrs;
2601 SourceLocation EqualLoc;
2602 SourceLocation PureSpecLoc;
2604 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2605 if (Tok.isNot(tok::equal))
2608 auto &Zero = NextToken();
2609 SmallString<8> Buffer;
2610 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2611 PP.getSpelling(Zero, Buffer) != "0")
2614 auto &After = GetLookAheadToken(2);
2615 if (!After.isOneOf(tok::semi, tok::comma) &&
2616 !(AllowDefinition &&
2617 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2620 EqualLoc = ConsumeToken();
2621 PureSpecLoc = ConsumeToken();
2625 SmallVector<Decl *, 8> DeclsInGroup;
2626 ExprResult BitfieldSize;
2627 bool ExpectSemi = true;
2629 // Parse the first declarator.
2630 if (ParseCXXMemberDeclaratorBeforeInitializer(
2631 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2632 TryConsumeToken(tok::semi);
2636 // Check for a member function definition.
2637 if (BitfieldSize.isUnset()) {
2638 // MSVC permits pure specifier on inline functions defined at class scope.
2639 // Hence check for =0 before checking for function definition.
2640 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2641 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2643 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2644 // function-definition:
2646 // In C++11, a non-function declarator followed by an open brace is a
2647 // braced-init-list for an in-class member initialization, not an
2648 // erroneous function definition.
2649 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2650 DefinitionKind = FDK_Definition;
2651 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2652 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2653 DefinitionKind = FDK_Definition;
2654 } else if (Tok.is(tok::equal)) {
2655 const Token &KW = NextToken();
2656 if (KW.is(tok::kw_default))
2657 DefinitionKind = FDK_Defaulted;
2658 else if (KW.is(tok::kw_delete))
2659 DefinitionKind = FDK_Deleted;
2662 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2664 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2665 // to a friend declaration, that declaration shall be a definition.
2666 if (DeclaratorInfo.isFunctionDeclarator() &&
2667 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2668 // Diagnose attributes that appear before decl specifier:
2669 // [[]] friend int foo();
2670 ProhibitAttributes(FnAttrs);
2673 if (DefinitionKind != FDK_Declaration) {
2674 if (!DeclaratorInfo.isFunctionDeclarator()) {
2675 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2677 SkipUntil(tok::r_brace);
2679 // Consume the optional ';'
2680 TryConsumeToken(tok::semi);
2685 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2686 Diag(DeclaratorInfo.getIdentifierLoc(),
2687 diag::err_function_declared_typedef);
2689 // Recover by treating the 'typedef' as spurious.
2690 DS.ClearStorageClassSpecs();
2694 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2698 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2699 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2701 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2702 LateParsedAttrs[i]->addDecl(FunDecl);
2705 LateParsedAttrs.clear();
2707 // Consume the ';' - it's optional unless we have a delete or default
2708 if (Tok.is(tok::semi))
2709 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2711 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2715 // member-declarator-list:
2716 // member-declarator
2717 // member-declarator-list ',' member-declarator
2720 InClassInitStyle HasInClassInit = ICIS_NoInit;
2721 bool HasStaticInitializer = false;
2722 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2723 if (BitfieldSize.get()) {
2724 Diag(Tok, diag::err_bitfield_member_init);
2725 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2726 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2727 // It's a pure-specifier.
2728 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2729 // Parse it as an expression so that Sema can diagnose it.
2730 HasStaticInitializer = true;
2731 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2732 DeclSpec::SCS_static &&
2733 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2734 DeclSpec::SCS_typedef &&
2735 !DS.isFriendSpecified()) {
2736 // It's a default member initializer.
2737 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2739 HasStaticInitializer = true;
2743 // NOTE: If Sema is the Action module and declarator is an instance field,
2744 // this call will *not* return the created decl; It will return null.
2745 // See Sema::ActOnCXXMemberDeclarator for details.
2747 NamedDecl *ThisDecl = nullptr;
2748 if (DS.isFriendSpecified()) {
2749 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2750 // to a friend declaration, that declaration shall be a definition.
2752 // Diagnose attributes that appear in a friend member function declarator:
2753 // friend int foo [[]] ();
2754 SmallVector<SourceRange, 4> Ranges;
2755 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2756 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2757 E = Ranges.end(); I != E; ++I)
2758 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2760 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2763 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2767 VS, HasInClassInit);
2769 if (VarTemplateDecl *VT =
2770 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2771 // Re-direct this decl to refer to the templated decl so that we can
2773 ThisDecl = VT->getTemplatedDecl();
2775 if (ThisDecl && AccessAttrs)
2776 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2779 // Error recovery might have converted a non-static member into a static
2781 if (HasInClassInit != ICIS_NoInit &&
2782 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2783 DeclSpec::SCS_static) {
2784 HasInClassInit = ICIS_NoInit;
2785 HasStaticInitializer = true;
2788 if (ThisDecl && PureSpecLoc.isValid())
2789 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2791 // Handle the initializer.
2792 if (HasInClassInit != ICIS_NoInit) {
2793 // The initializer was deferred; parse it and cache the tokens.
2794 Diag(Tok, getLangOpts().CPlusPlus11
2795 ? diag::warn_cxx98_compat_nonstatic_member_init
2796 : diag::ext_nonstatic_member_init);
2798 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2799 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2800 // declarator is followed by an initializer.
2802 // A brace-or-equal-initializer for a member-declarator is not an
2803 // initializer in the grammar, so this is ill-formed.
2804 Diag(Tok, diag::err_incomplete_array_member_init);
2805 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2807 // Avoid later warnings about a class member of incomplete type.
2809 ThisDecl->setInvalidDecl();
2811 ParseCXXNonStaticMemberInitializer(ThisDecl);
2812 } else if (HasStaticInitializer) {
2813 // Normal initializer.
2814 ExprResult Init = ParseCXXMemberInitializer(
2815 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2817 if (Init.isInvalid())
2818 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2820 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
2821 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2823 Actions.ActOnUninitializedDecl(ThisDecl);
2826 if (!ThisDecl->isInvalidDecl()) {
2827 // Set the Decl for any late parsed attributes
2828 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2829 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2831 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2832 LateParsedAttrs[i]->addDecl(ThisDecl);
2834 Actions.FinalizeDeclaration(ThisDecl);
2835 DeclsInGroup.push_back(ThisDecl);
2837 if (DeclaratorInfo.isFunctionDeclarator() &&
2838 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2839 DeclSpec::SCS_typedef)
2840 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2842 LateParsedAttrs.clear();
2844 DeclaratorInfo.complete(ThisDecl);
2846 // If we don't have a comma, it is either the end of the list (a ';')
2847 // or an error, bail out.
2848 SourceLocation CommaLoc;
2849 if (!TryConsumeToken(tok::comma, CommaLoc))
2852 if (Tok.isAtStartOfLine() &&
2853 !MightBeDeclarator(Declarator::MemberContext)) {
2854 // This comma was followed by a line-break and something which can't be
2855 // the start of a declarator. The comma was probably a typo for a
2857 Diag(CommaLoc, diag::err_expected_semi_declaration)
2858 << FixItHint::CreateReplacement(CommaLoc, ";");
2863 // Parse the next declarator.
2864 DeclaratorInfo.clear();
2866 BitfieldSize = ExprResult(/*Invalid=*/false);
2867 EqualLoc = PureSpecLoc = SourceLocation();
2868 DeclaratorInfo.setCommaLoc(CommaLoc);
2870 // GNU attributes are allowed before the second and subsequent declarator.
2871 MaybeParseGNUAttributes(DeclaratorInfo);
2873 if (ParseCXXMemberDeclaratorBeforeInitializer(
2874 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2879 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2880 // Skip to end of block or statement.
2881 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2882 // If we stopped at a ';', eat it.
2883 TryConsumeToken(tok::semi);
2887 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2890 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2891 /// Also detect and reject any attempted defaulted/deleted function definition.
2892 /// The location of the '=', if any, will be placed in EqualLoc.
2894 /// This does not check for a pure-specifier; that's handled elsewhere.
2896 /// brace-or-equal-initializer:
2897 /// '=' initializer-expression
2898 /// braced-init-list
2900 /// initializer-clause:
2901 /// assignment-expression
2902 /// braced-init-list
2904 /// defaulted/deleted function-definition:
2908 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2909 /// be a constant-expression.
2910 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2911 SourceLocation &EqualLoc) {
2912 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2913 && "Data member initializer not starting with '=' or '{'");
2915 EnterExpressionEvaluationContext Context(
2916 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
2917 if (TryConsumeToken(tok::equal, EqualLoc)) {
2918 if (Tok.is(tok::kw_delete)) {
2919 // In principle, an initializer of '= delete p;' is legal, but it will
2920 // never type-check. It's better to diagnose it as an ill-formed expression
2921 // than as an ill-formed deleted non-function member.
2922 // An initializer of '= delete p, foo' will never be parsed, because
2923 // a top-level comma always ends the initializer expression.
2924 const Token &Next = NextToken();
2925 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2927 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2930 Diag(ConsumeToken(), diag::err_deleted_non_function);
2933 } else if (Tok.is(tok::kw_default)) {
2935 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2938 Diag(ConsumeToken(), diag::err_default_special_members);
2942 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2943 Diag(Tok, diag::err_ms_property_initializer) << PD;
2946 return ParseInitializer();
2949 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2950 SourceLocation AttrFixitLoc,
2951 unsigned TagType, Decl *TagDecl) {
2952 // Skip the optional 'final' keyword.
2953 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2954 assert(isCXX11FinalKeyword() && "not a class definition");
2957 // Diagnose any C++11 attributes after 'final' keyword.
2958 // We deliberately discard these attributes.
2959 ParsedAttributesWithRange Attrs(AttrFactory);
2960 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2962 // This can only happen if we had malformed misplaced attributes;
2963 // we only get called if there is a colon or left-brace after the
2965 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2969 // Skip the base clauses. This requires actually parsing them, because
2970 // otherwise we can't be sure where they end (a left brace may appear
2971 // within a template argument).
2972 if (Tok.is(tok::colon)) {
2973 // Enter the scope of the class so that we can correctly parse its bases.
2974 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2975 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2976 TagType == DeclSpec::TST_interface);
2978 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2980 // Parse the bases but don't attach them to the class.
2981 ParseBaseClause(nullptr);
2983 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2985 if (!Tok.is(tok::l_brace)) {
2986 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2987 diag::err_expected_lbrace_after_base_specifiers);
2993 assert(Tok.is(tok::l_brace));
2994 BalancedDelimiterTracker T(*this, tok::l_brace);
2998 // Parse and discard any trailing attributes.
2999 ParsedAttributes Attrs(AttrFactory);
3000 if (Tok.is(tok::kw___attribute))
3001 MaybeParseGNUAttributes(Attrs);
3004 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
3005 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
3006 DeclSpec::TST TagType, Decl *TagDecl) {
3007 switch (Tok.getKind()) {
3008 case tok::kw___if_exists:
3009 case tok::kw___if_not_exists:
3010 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
3014 // Check for extraneous top-level semicolon.
3015 ConsumeExtraSemi(InsideStruct, TagType);
3018 // Handle pragmas that can appear as member declarations.
3019 case tok::annot_pragma_vis:
3020 HandlePragmaVisibility();
3022 case tok::annot_pragma_pack:
3025 case tok::annot_pragma_align:
3026 HandlePragmaAlign();
3028 case tok::annot_pragma_ms_pointers_to_members:
3029 HandlePragmaMSPointersToMembers();
3031 case tok::annot_pragma_ms_pragma:
3032 HandlePragmaMSPragma();
3034 case tok::annot_pragma_ms_vtordisp:
3035 HandlePragmaMSVtorDisp();
3037 case tok::annot_pragma_dump:
3041 case tok::kw_namespace:
3042 // If we see a namespace here, a close brace was missing somewhere.
3043 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
3046 case tok::kw_public:
3047 case tok::kw_protected:
3048 case tok::kw_private: {
3049 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
3050 assert(NewAS != AS_none);
3051 // Current token is a C++ access specifier.
3053 SourceLocation ASLoc = Tok.getLocation();
3054 unsigned TokLength = Tok.getLength();
3056 AccessAttrs.clear();
3057 MaybeParseGNUAttributes(AccessAttrs);
3059 SourceLocation EndLoc;
3060 if (TryConsumeToken(tok::colon, EndLoc)) {
3061 } else if (TryConsumeToken(tok::semi, EndLoc)) {
3062 Diag(EndLoc, diag::err_expected)
3063 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
3065 EndLoc = ASLoc.getLocWithOffset(TokLength);
3066 Diag(EndLoc, diag::err_expected)
3067 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
3070 // The Microsoft extension __interface does not permit non-public
3071 // access specifiers.
3072 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
3073 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
3076 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
3077 AccessAttrs.getList())) {
3078 // found another attribute than only annotations
3079 AccessAttrs.clear();
3085 case tok::annot_pragma_openmp:
3086 return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
3090 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
3094 /// ParseCXXMemberSpecification - Parse the class definition.
3096 /// member-specification:
3097 /// member-declaration member-specification[opt]
3098 /// access-specifier ':' member-specification[opt]
3100 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
3101 SourceLocation AttrFixitLoc,
3102 ParsedAttributesWithRange &Attrs,
3103 unsigned TagType, Decl *TagDecl) {
3104 assert((TagType == DeclSpec::TST_struct ||
3105 TagType == DeclSpec::TST_interface ||
3106 TagType == DeclSpec::TST_union ||
3107 TagType == DeclSpec::TST_class) && "Invalid TagType!");
3109 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
3110 "parsing struct/union/class body");
3112 // Determine whether this is a non-nested class. Note that local
3113 // classes are *not* considered to be nested classes.
3114 bool NonNestedClass = true;
3115 if (!ClassStack.empty()) {
3116 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
3117 if (S->isClassScope()) {
3118 // We're inside a class scope, so this is a nested class.
3119 NonNestedClass = false;
3121 // The Microsoft extension __interface does not permit nested classes.
3122 if (getCurrentClass().IsInterface) {
3123 Diag(RecordLoc, diag::err_invalid_member_in_interface)
3125 << (isa<NamedDecl>(TagDecl)
3126 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
3132 if ((S->getFlags() & Scope::FnScope))
3133 // If we're in a function or function template then this is a local
3134 // class rather than a nested class.
3139 // Enter a scope for the class.
3140 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
3142 // Note that we are parsing a new (potentially-nested) class definition.
3143 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
3144 TagType == DeclSpec::TST_interface);
3147 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
3149 SourceLocation FinalLoc;
3150 bool IsFinalSpelledSealed = false;
3152 // Parse the optional 'final' keyword.
3153 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
3154 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
3155 assert((Specifier == VirtSpecifiers::VS_Final ||
3156 Specifier == VirtSpecifiers::VS_GNU_Final ||
3157 Specifier == VirtSpecifiers::VS_Sealed) &&
3158 "not a class definition");
3159 FinalLoc = ConsumeToken();
3160 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
3162 if (TagType == DeclSpec::TST_interface)
3163 Diag(FinalLoc, diag::err_override_control_interface)
3164 << VirtSpecifiers::getSpecifierName(Specifier);
3165 else if (Specifier == VirtSpecifiers::VS_Final)
3166 Diag(FinalLoc, getLangOpts().CPlusPlus11
3167 ? diag::warn_cxx98_compat_override_control_keyword
3168 : diag::ext_override_control_keyword)
3169 << VirtSpecifiers::getSpecifierName(Specifier);
3170 else if (Specifier == VirtSpecifiers::VS_Sealed)
3171 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
3172 else if (Specifier == VirtSpecifiers::VS_GNU_Final)
3173 Diag(FinalLoc, diag::ext_warn_gnu_final);
3175 // Parse any C++11 attributes after 'final' keyword.
3176 // These attributes are not allowed to appear here,
3177 // and the only possible place for them to appertain
3178 // to the class would be between class-key and class-name.
3179 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3181 // ParseClassSpecifier() does only a superficial check for attributes before
3182 // deciding to call this method. For example, for
3183 // `class C final alignas ([l) {` it will decide that this looks like a
3184 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3185 // attribute parsing code will try to parse the '[' as a constexpr lambda
3186 // and consume enough tokens that the alignas parsing code will eat the
3187 // opening '{'. So bail out if the next token isn't one we expect.
3188 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3190 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3195 if (Tok.is(tok::colon)) {
3196 ParseBaseClause(TagDecl);
3197 if (!Tok.is(tok::l_brace)) {
3198 bool SuggestFixIt = false;
3199 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3200 if (Tok.isAtStartOfLine()) {
3201 switch (Tok.getKind()) {
3202 case tok::kw_private:
3203 case tok::kw_protected:
3204 case tok::kw_public:
3205 SuggestFixIt = NextToken().getKind() == tok::colon;
3207 case tok::kw_static_assert:
3210 // base-clause can have simple-template-id; 'template' can't be there
3211 case tok::kw_template:
3212 SuggestFixIt = true;
3214 case tok::identifier:
3215 SuggestFixIt = isConstructorDeclarator(true);
3218 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3222 DiagnosticBuilder LBraceDiag =
3223 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3225 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3226 // Try recovering from missing { after base-clause.
3228 Tok.setKind(tok::l_brace);
3231 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3237 assert(Tok.is(tok::l_brace));
3238 BalancedDelimiterTracker T(*this, tok::l_brace);
3242 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3243 IsFinalSpelledSealed,
3244 T.getOpenLocation());
3246 // C++ 11p3: Members of a class defined with the keyword class are private
3247 // by default. Members of a class defined with the keywords struct or union
3248 // are public by default.
3249 AccessSpecifier CurAS;
3250 if (TagType == DeclSpec::TST_class)
3254 ParsedAttributesWithRange AccessAttrs(AttrFactory);
3257 // While we still have something to read, read the member-declarations.
3258 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3259 Tok.isNot(tok::eof)) {
3260 // Each iteration of this loop reads one member-declaration.
3261 ParseCXXClassMemberDeclarationWithPragmas(
3262 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3266 SkipUntil(tok::r_brace);
3269 // If attributes exist after class contents, parse them.
3270 ParsedAttributes attrs(AttrFactory);
3271 MaybeParseGNUAttributes(attrs);
3274 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3275 T.getOpenLocation(),
3276 T.getCloseLocation(),
3279 // C++11 [class.mem]p2:
3280 // Within the class member-specification, the class is regarded as complete
3281 // within function bodies, default arguments, exception-specifications, and
3282 // brace-or-equal-initializers for non-static data members (including such
3283 // things in nested classes).
3284 if (TagDecl && NonNestedClass) {
3285 // We are not inside a nested class. This class and its nested classes
3286 // are complete and we can parse the delayed portions of method
3287 // declarations and the lexed inline method definitions, along with any
3288 // delayed attributes.
3289 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3290 ParseLexedAttributes(getCurrentClass());
3291 ParseLexedMethodDeclarations(getCurrentClass());
3293 // We've finished with all pending member declarations.
3294 Actions.ActOnFinishCXXMemberDecls();
3296 ParseLexedMemberInitializers(getCurrentClass());
3297 ParseLexedMethodDefs(getCurrentClass());
3298 PrevTokLocation = SavedPrevTokLocation;
3300 // We've finished parsing everything, including default argument
3302 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3306 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
3308 // Leave the class scope.
3313 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3314 assert(Tok.is(tok::kw_namespace));
3316 // FIXME: Suggest where the close brace should have gone by looking
3317 // at indentation changes within the definition body.
3318 Diag(D->getLocation(),
3319 diag::err_missing_end_of_definition) << D;
3320 Diag(Tok.getLocation(),
3321 diag::note_missing_end_of_definition_before) << D;
3323 // Push '};' onto the token stream to recover.
3327 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3328 Tok.setKind(tok::semi);
3331 Tok.setKind(tok::r_brace);
3334 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3335 /// which explicitly initializes the members or base classes of a
3336 /// class (C++ [class.base.init]). For example, the three initializers
3337 /// after the ':' in the Derived constructor below:
3341 /// class Derived : Base {
3345 /// Derived(float f) : Base(), x(17), f(f) { }
3349 /// [C++] ctor-initializer:
3350 /// ':' mem-initializer-list
3352 /// [C++] mem-initializer-list:
3353 /// mem-initializer ...[opt]
3354 /// mem-initializer ...[opt] , mem-initializer-list
3355 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3356 assert(Tok.is(tok::colon) &&
3357 "Constructor initializer always starts with ':'");
3359 // Poison the SEH identifiers so they are flagged as illegal in constructor
3361 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3362 SourceLocation ColonLoc = ConsumeToken();
3364 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3365 bool AnyErrors = false;
3368 if (Tok.is(tok::code_completion)) {
3369 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3371 return cutOffParsing();
3374 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3375 if (!MemInit.isInvalid())
3376 MemInitializers.push_back(MemInit.get());
3380 if (Tok.is(tok::comma))
3382 else if (Tok.is(tok::l_brace))
3384 // If the previous initializer was valid and the next token looks like a
3385 // base or member initializer, assume that we're just missing a comma.
3386 else if (!MemInit.isInvalid() &&
3387 Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3388 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3389 Diag(Loc, diag::err_ctor_init_missing_comma)
3390 << FixItHint::CreateInsertion(Loc, ", ");
3392 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3393 if (!MemInit.isInvalid())
3394 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3396 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3401 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3405 /// ParseMemInitializer - Parse a C++ member initializer, which is
3406 /// part of a constructor initializer that explicitly initializes one
3407 /// member or base class (C++ [class.base.init]). See
3408 /// ParseConstructorInitializer for an example.
3410 /// [C++] mem-initializer:
3411 /// mem-initializer-id '(' expression-list[opt] ')'
3412 /// [C++0x] mem-initializer-id braced-init-list
3414 /// [C++] mem-initializer-id:
3415 /// '::'[opt] nested-name-specifier[opt] class-name
3417 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3418 // parse '::'[opt] nested-name-specifier[opt]
3420 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
3423 IdentifierInfo *II = nullptr;
3424 SourceLocation IdLoc = Tok.getLocation();
3426 DeclSpec DS(AttrFactory);
3427 // : template_name<...>
3428 ParsedType TemplateTypeTy;
3430 if (Tok.is(tok::identifier)) {
3431 // Get the identifier. This may be a member name or a class name,
3432 // but we'll let the semantic analysis determine which it is.
3433 II = Tok.getIdentifierInfo();
3435 } else if (Tok.is(tok::annot_decltype)) {
3436 // Get the decltype expression, if there is one.
3437 // Uses of decltype will already have been converted to annot_decltype by
3438 // ParseOptionalCXXScopeSpecifier at this point.
3439 // FIXME: Can we get here with a scope specifier?
3440 ParseDecltypeSpecifier(DS);
3442 TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
3443 ? takeTemplateIdAnnotation(Tok)
3445 if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
3446 TemplateId->Kind == TNK_Dependent_template_name)) {
3447 AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
3448 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3449 TemplateTypeTy = getTypeAnnotation(Tok);
3450 ConsumeAnnotationToken();
3452 Diag(Tok, diag::err_expected_member_or_base_name);
3458 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3459 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3461 ExprResult InitList = ParseBraceInitializer();
3462 if (InitList.isInvalid())
3465 SourceLocation EllipsisLoc;
3466 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3468 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3469 TemplateTypeTy, DS, IdLoc,
3470 InitList.get(), EllipsisLoc);
3471 } else if(Tok.is(tok::l_paren)) {
3472 BalancedDelimiterTracker T(*this, tok::l_paren);
3475 // Parse the optional expression-list.
3476 ExprVector ArgExprs;
3477 CommaLocsTy CommaLocs;
3478 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
3479 SkipUntil(tok::r_paren, StopAtSemi);
3485 SourceLocation EllipsisLoc;
3486 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3488 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3489 TemplateTypeTy, DS, IdLoc,
3490 T.getOpenLocation(), ArgExprs,
3491 T.getCloseLocation(), EllipsisLoc);
3494 if (getLangOpts().CPlusPlus11)
3495 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3497 return Diag(Tok, diag::err_expected) << tok::l_paren;
3500 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
3502 /// exception-specification:
3503 /// dynamic-exception-specification
3504 /// noexcept-specification
3506 /// noexcept-specification:
3508 /// 'noexcept' '(' constant-expression ')'
3509 ExceptionSpecificationType
3510 Parser::tryParseExceptionSpecification(bool Delayed,
3511 SourceRange &SpecificationRange,
3512 SmallVectorImpl<ParsedType> &DynamicExceptions,
3513 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3514 ExprResult &NoexceptExpr,
3515 CachedTokens *&ExceptionSpecTokens) {
3516 ExceptionSpecificationType Result = EST_None;
3517 ExceptionSpecTokens = nullptr;
3519 // Handle delayed parsing of exception-specifications.
3521 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3524 // Consume and cache the starting token.
3525 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3526 Token StartTok = Tok;
3527 SpecificationRange = SourceRange(ConsumeToken());
3530 if (!Tok.is(tok::l_paren)) {
3531 // If this is a bare 'noexcept', we're done.
3533 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3534 NoexceptExpr = nullptr;
3535 return EST_BasicNoexcept;
3538 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3539 return EST_DynamicNone;
3542 // Cache the tokens for the exception-specification.
3543 ExceptionSpecTokens = new CachedTokens;
3544 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3545 ExceptionSpecTokens->push_back(Tok); // '('
3546 SpecificationRange.setEnd(ConsumeParen()); // '('
3548 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3549 /*StopAtSemi=*/true,
3550 /*ConsumeFinalToken=*/true);
3551 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3553 return EST_Unparsed;
3556 // See if there's a dynamic specification.
3557 if (Tok.is(tok::kw_throw)) {
3558 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3560 DynamicExceptionRanges);
3561 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3562 "Produced different number of exception types and ranges.");
3565 // If there's no noexcept specification, we're done.
3566 if (Tok.isNot(tok::kw_noexcept))
3569 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3571 // If we already had a dynamic specification, parse the noexcept for,
3572 // recovery, but emit a diagnostic and don't store the results.
3573 SourceRange NoexceptRange;
3574 ExceptionSpecificationType NoexceptType = EST_None;
3576 SourceLocation KeywordLoc = ConsumeToken();
3577 if (Tok.is(tok::l_paren)) {
3578 // There is an argument.
3579 BalancedDelimiterTracker T(*this, tok::l_paren);
3581 NoexceptType = EST_ComputedNoexcept;
3582 NoexceptExpr = ParseConstantExpression();
3584 // The argument must be contextually convertible to bool. We use
3585 // CheckBooleanCondition for this purpose.
3586 // FIXME: Add a proper Sema entry point for this.
3587 if (!NoexceptExpr.isInvalid()) {
3589 Actions.CheckBooleanCondition(KeywordLoc, NoexceptExpr.get());
3590 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3592 NoexceptType = EST_BasicNoexcept;
3595 // There is no argument.
3596 NoexceptType = EST_BasicNoexcept;
3597 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3600 if (Result == EST_None) {
3601 SpecificationRange = NoexceptRange;
3602 Result = NoexceptType;
3604 // If there's a dynamic specification after a noexcept specification,
3605 // parse that and ignore the results.
3606 if (Tok.is(tok::kw_throw)) {
3607 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3608 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3609 DynamicExceptionRanges);
3612 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3618 static void diagnoseDynamicExceptionSpecification(
3619 Parser &P, SourceRange Range, bool IsNoexcept) {
3620 if (P.getLangOpts().CPlusPlus11) {
3621 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3622 P.Diag(Range.getBegin(),
3623 P.getLangOpts().CPlusPlus1z && !IsNoexcept
3624 ? diag::ext_dynamic_exception_spec
3625 : diag::warn_exception_spec_deprecated)
3627 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3628 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3632 /// ParseDynamicExceptionSpecification - Parse a C++
3633 /// dynamic-exception-specification (C++ [except.spec]).
3635 /// dynamic-exception-specification:
3636 /// 'throw' '(' type-id-list [opt] ')'
3637 /// [MS] 'throw' '(' '...' ')'
3640 /// type-id ... [opt]
3641 /// type-id-list ',' type-id ... [opt]
3643 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3644 SourceRange &SpecificationRange,
3645 SmallVectorImpl<ParsedType> &Exceptions,
3646 SmallVectorImpl<SourceRange> &Ranges) {
3647 assert(Tok.is(tok::kw_throw) && "expected throw");
3649 SpecificationRange.setBegin(ConsumeToken());
3650 BalancedDelimiterTracker T(*this, tok::l_paren);
3651 if (T.consumeOpen()) {
3652 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3653 SpecificationRange.setEnd(SpecificationRange.getBegin());
3654 return EST_DynamicNone;
3657 // Parse throw(...), a Microsoft extension that means "this function
3658 // can throw anything".
3659 if (Tok.is(tok::ellipsis)) {
3660 SourceLocation EllipsisLoc = ConsumeToken();
3661 if (!getLangOpts().MicrosoftExt)
3662 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3664 SpecificationRange.setEnd(T.getCloseLocation());
3665 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3669 // Parse the sequence of type-ids.
3671 while (Tok.isNot(tok::r_paren)) {
3672 TypeResult Res(ParseTypeName(&Range));
3674 if (Tok.is(tok::ellipsis)) {
3675 // C++0x [temp.variadic]p5:
3676 // - In a dynamic-exception-specification (15.4); the pattern is a
3678 SourceLocation Ellipsis = ConsumeToken();
3679 Range.setEnd(Ellipsis);
3680 if (!Res.isInvalid())
3681 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3684 if (!Res.isInvalid()) {
3685 Exceptions.push_back(Res.get());
3686 Ranges.push_back(Range);
3689 if (!TryConsumeToken(tok::comma))
3694 SpecificationRange.setEnd(T.getCloseLocation());
3695 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3696 Exceptions.empty());
3697 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3700 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3701 /// function declaration.
3702 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3703 assert(Tok.is(tok::arrow) && "expected arrow");
3707 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3710 /// \brief We have just started parsing the definition of a new class,
3711 /// so push that class onto our stack of classes that is currently
3713 Sema::ParsingClassState
3714 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3716 assert((NonNestedClass || !ClassStack.empty()) &&
3717 "Nested class without outer class");
3718 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3719 return Actions.PushParsingClass();
3722 /// \brief Deallocate the given parsed class and all of its nested
3724 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3725 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3726 delete Class->LateParsedDeclarations[I];
3730 /// \brief Pop the top class of the stack of classes that are
3731 /// currently being parsed.
3733 /// This routine should be called when we have finished parsing the
3734 /// definition of a class, but have not yet popped the Scope
3735 /// associated with the class's definition.
3736 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3737 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3739 Actions.PopParsingClass(state);
3741 ParsingClass *Victim = ClassStack.top();
3743 if (Victim->TopLevelClass) {
3744 // Deallocate all of the nested classes of this class,
3745 // recursively: we don't need to keep any of this information.
3746 DeallocateParsedClasses(Victim);
3749 assert(!ClassStack.empty() && "Missing top-level class?");
3751 if (Victim->LateParsedDeclarations.empty()) {
3752 // The victim is a nested class, but we will not need to perform
3753 // any processing after the definition of this class since it has
3754 // no members whose handling was delayed. Therefore, we can just
3755 // remove this nested class.
3756 DeallocateParsedClasses(Victim);
3760 // This nested class has some members that will need to be processed
3761 // after the top-level class is completely defined. Therefore, add
3762 // it to the list of nested classes within its parent.
3763 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3764 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3765 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3768 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3770 /// \return the parsed identifier on success, and 0 if the next token is not an
3771 /// attribute-token.
3773 /// C++11 [dcl.attr.grammar]p3:
3774 /// If a keyword or an alternative token that satisfies the syntactic
3775 /// requirements of an identifier is contained in an attribute-token,
3776 /// it is considered an identifier.
3777 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3778 switch (Tok.getKind()) {
3780 // Identifiers and keywords have identifier info attached.
3781 if (!Tok.isAnnotation()) {
3782 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3783 Loc = ConsumeToken();
3789 case tok::ampamp: // 'and'
3790 case tok::pipe: // 'bitor'
3791 case tok::pipepipe: // 'or'
3792 case tok::caret: // 'xor'
3793 case tok::tilde: // 'compl'
3794 case tok::amp: // 'bitand'
3795 case tok::ampequal: // 'and_eq'
3796 case tok::pipeequal: // 'or_eq'
3797 case tok::caretequal: // 'xor_eq'
3798 case tok::exclaim: // 'not'
3799 case tok::exclaimequal: // 'not_eq'
3800 // Alternative tokens do not have identifier info, but their spelling
3801 // starts with an alphabetical character.
3802 SmallString<8> SpellingBuf;
3803 SourceLocation SpellingLoc =
3804 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3805 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3806 if (isLetter(Spelling[0])) {
3807 Loc = ConsumeToken();
3808 return &PP.getIdentifierTable().get(Spelling);
3814 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3815 IdentifierInfo *ScopeName) {
3816 switch (AttributeList::getKind(AttrName, ScopeName,
3817 AttributeList::AS_CXX11)) {
3818 case AttributeList::AT_CarriesDependency:
3819 case AttributeList::AT_Deprecated:
3820 case AttributeList::AT_FallThrough:
3821 case AttributeList::AT_CXX11NoReturn:
3823 case AttributeList::AT_WarnUnusedResult:
3824 return !ScopeName && AttrName->getName().equals("nodiscard");
3825 case AttributeList::AT_Unused:
3826 return !ScopeName && AttrName->getName().equals("maybe_unused");
3832 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3834 /// [C++11] attribute-argument-clause:
3835 /// '(' balanced-token-seq ')'
3837 /// [C++11] balanced-token-seq:
3839 /// balanced-token-seq balanced-token
3841 /// [C++11] balanced-token:
3842 /// '(' balanced-token-seq ')'
3843 /// '[' balanced-token-seq ']'
3844 /// '{' balanced-token-seq '}'
3845 /// any token but '(', ')', '[', ']', '{', or '}'
3846 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3847 SourceLocation AttrNameLoc,
3848 ParsedAttributes &Attrs,
3849 SourceLocation *EndLoc,
3850 IdentifierInfo *ScopeName,
3851 SourceLocation ScopeLoc) {
3852 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3853 SourceLocation LParenLoc = Tok.getLocation();
3855 // If the attribute isn't known, we will not attempt to parse any
3857 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
3858 getTargetInfo(), getLangOpts())) {
3859 // Eat the left paren, then skip to the ending right paren.
3861 SkipUntil(tok::r_paren);
3865 if (ScopeName && ScopeName->getName() == "gnu") {
3866 // GNU-scoped attributes have some special cases to handle GNU-specific
3868 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3869 ScopeLoc, AttributeList::AS_CXX11, nullptr);
3874 // Some Clang-scoped attributes have some special parsing behavior.
3875 if (ScopeName && ScopeName->getName() == "clang")
3877 ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3878 ScopeLoc, AttributeList::AS_CXX11);
3881 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3882 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3884 const AttributeList *Attr = Attrs.getList();
3885 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3886 // If the attribute is a standard or built-in attribute and we are
3887 // parsing an argument list, we need to determine whether this attribute
3888 // was allowed to have an argument list (such as [[deprecated]]), and how
3889 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3890 if (Attr->getMaxArgs() && !NumArgs) {
3891 // The attribute was allowed to have arguments, but none were provided
3892 // even though the attribute parsed successfully. This is an error.
3893 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3894 Attr->setInvalid(true);
3895 } else if (!Attr->getMaxArgs()) {
3896 // The attribute parsed successfully, but was not allowed to have any
3897 // arguments. It doesn't matter whether any were provided -- the
3898 // presence of the argument list (even if empty) is diagnosed.
3899 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3901 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3902 Attr->setInvalid(true);
3908 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
3910 /// [C++11] attribute-specifier:
3911 /// '[' '[' attribute-list ']' ']'
3912 /// alignment-specifier
3914 /// [C++11] attribute-list:
3916 /// attribute-list ',' attribute[opt]
3918 /// attribute-list ',' attribute '...'
3920 /// [C++11] attribute:
3921 /// attribute-token attribute-argument-clause[opt]
3923 /// [C++11] attribute-token:
3925 /// attribute-scoped-token
3927 /// [C++11] attribute-scoped-token:
3928 /// attribute-namespace '::' identifier
3930 /// [C++11] attribute-namespace:
3932 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3933 SourceLocation *endLoc) {
3934 if (Tok.is(tok::kw_alignas)) {
3935 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3936 ParseAlignmentSpecifier(attrs, endLoc);
3940 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3941 && "Not a C++11 attribute list");
3943 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3948 SourceLocation CommonScopeLoc;
3949 IdentifierInfo *CommonScopeName = nullptr;
3950 if (Tok.is(tok::kw_using)) {
3951 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
3952 ? diag::warn_cxx14_compat_using_attribute_ns
3953 : diag::ext_using_attribute_ns);
3956 CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
3957 if (!CommonScopeName) {
3958 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3959 SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
3961 if (!TryConsumeToken(tok::colon) && CommonScopeName)
3962 Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
3965 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3967 while (Tok.isNot(tok::r_square)) {
3968 // attribute not present
3969 if (TryConsumeToken(tok::comma))
3972 SourceLocation ScopeLoc, AttrLoc;
3973 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3975 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3977 // Break out to the "expected ']'" diagnostic.
3981 if (TryConsumeToken(tok::coloncolon)) {
3982 ScopeName = AttrName;
3985 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3987 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3988 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3993 if (CommonScopeName) {
3995 Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
3996 << SourceRange(CommonScopeLoc);
3998 ScopeName = CommonScopeName;
3999 ScopeLoc = CommonScopeLoc;
4003 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
4004 bool AttrParsed = false;
4007 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
4008 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
4009 << AttrName << SourceRange(SeenAttrs[AttrName]);
4011 // Parse attribute arguments
4012 if (Tok.is(tok::l_paren))
4013 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
4014 ScopeName, ScopeLoc);
4017 attrs.addNew(AttrName,
4018 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
4020 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
4022 if (TryConsumeToken(tok::ellipsis))
4023 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
4024 << AttrName->getName();
4027 if (ExpectAndConsume(tok::r_square))
4028 SkipUntil(tok::r_square);
4030 *endLoc = Tok.getLocation();
4031 if (ExpectAndConsume(tok::r_square))
4032 SkipUntil(tok::r_square);
4035 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
4037 /// attribute-specifier-seq:
4038 /// attribute-specifier-seq[opt] attribute-specifier
4039 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
4040 SourceLocation *endLoc) {
4041 assert(getLangOpts().CPlusPlus11);
4043 SourceLocation StartLoc = Tok.getLocation(), Loc;
4048 ParseCXX11AttributeSpecifier(attrs, endLoc);
4049 } while (isCXX11AttributeSpecifier());
4051 attrs.Range = SourceRange(StartLoc, *endLoc);
4054 void Parser::DiagnoseAndSkipCXX11Attributes() {
4055 // Start and end location of an attribute or an attribute list.
4056 SourceLocation StartLoc = Tok.getLocation();
4057 SourceLocation EndLoc = SkipCXX11Attributes();
4059 if (EndLoc.isValid()) {
4060 SourceRange Range(StartLoc, EndLoc);
4061 Diag(StartLoc, diag::err_attributes_not_allowed)
4066 SourceLocation Parser::SkipCXX11Attributes() {
4067 SourceLocation EndLoc;
4069 if (!isCXX11AttributeSpecifier())
4073 if (Tok.is(tok::l_square)) {
4074 BalancedDelimiterTracker T(*this, tok::l_square);
4077 EndLoc = T.getCloseLocation();
4079 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
4081 BalancedDelimiterTracker T(*this, tok::l_paren);
4082 if (!T.consumeOpen())
4084 EndLoc = T.getCloseLocation();
4086 } while (isCXX11AttributeSpecifier());
4091 /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
4092 void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
4093 assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
4094 IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
4095 assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
4097 SourceLocation UuidLoc = Tok.getLocation();
4100 // Ignore the left paren location for now.
4101 BalancedDelimiterTracker T(*this, tok::l_paren);
4102 if (T.consumeOpen()) {
4103 Diag(Tok, diag::err_expected) << tok::l_paren;
4107 ArgsVector ArgExprs;
4108 if (Tok.is(tok::string_literal)) {
4109 // Easy case: uuid("...") -- quoted string.
4110 ExprResult StringResult = ParseStringLiteralExpression();
4111 if (StringResult.isInvalid())
4113 ArgExprs.push_back(StringResult.get());
4115 // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
4116 // quotes in the parens. Just append the spelling of all tokens encountered
4117 // until the closing paren.
4119 SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
4122 // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
4123 // tok::r_brace, tok::minus, tok::identifier (think C000) and
4124 // tok::numeric_constant (0000) should be enough. But the spelling of the
4125 // uuid argument is checked later anyways, so there's no harm in accepting
4126 // almost anything here.
4127 // cl is very strict about whitespace in this form and errors out if any
4128 // is present, so check the space flags on the tokens.
4129 SourceLocation StartLoc = Tok.getLocation();
4130 while (Tok.isNot(tok::r_paren)) {
4131 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4132 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4133 SkipUntil(tok::r_paren, StopAtSemi);
4136 SmallString<16> SpellingBuffer;
4137 SpellingBuffer.resize(Tok.getLength() + 1);
4138 bool Invalid = false;
4139 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
4141 SkipUntil(tok::r_paren, StopAtSemi);
4144 StrBuffer += TokSpelling;
4149 if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
4150 Diag(Tok, diag::err_attribute_uuid_malformed_guid);
4155 // Pretend the user wrote the appropriate string literal here.
4156 // ActOnStringLiteral() copies the string data into the literal, so it's
4157 // ok that the Token points to StrBuffer.
4159 Toks[0].startToken();
4160 Toks[0].setKind(tok::string_literal);
4161 Toks[0].setLocation(StartLoc);
4162 Toks[0].setLiteralData(StrBuffer.data());
4163 Toks[0].setLength(StrBuffer.size());
4164 StringLiteral *UuidString =
4165 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
4166 ArgExprs.push_back(UuidString);
4169 if (!T.consumeClose()) {
4170 Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
4171 SourceLocation(), ArgExprs.data(), ArgExprs.size(),
4172 AttributeList::AS_Microsoft);
4176 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
4178 /// [MS] ms-attribute:
4179 /// '[' token-seq ']'
4181 /// [MS] ms-attribute-seq:
4182 /// ms-attribute[opt]
4183 /// ms-attribute ms-attribute-seq
4184 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
4185 SourceLocation *endLoc) {
4186 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
4189 // FIXME: If this is actually a C++11 attribute, parse it as one.
4190 BalancedDelimiterTracker T(*this, tok::l_square);
4193 // Skip most ms attributes except for a whitelist.
4195 SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
4196 if (Tok.isNot(tok::identifier)) // ']', but also eof
4198 if (Tok.getIdentifierInfo()->getName() == "uuid")
4199 ParseMicrosoftUuidAttributeArgs(attrs);
4206 *endLoc = T.getCloseLocation();
4207 } while (Tok.is(tok::l_square));
4210 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
4211 AccessSpecifier& CurAS) {
4212 IfExistsCondition Result;
4213 if (ParseMicrosoftIfExistsCondition(Result))
4216 BalancedDelimiterTracker Braces(*this, tok::l_brace);
4217 if (Braces.consumeOpen()) {
4218 Diag(Tok, diag::err_expected) << tok::l_brace;
4222 switch (Result.Behavior) {
4224 // Parse the declarations below.
4228 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
4229 << Result.IsIfExists;
4230 // Fall through to skip.
4238 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
4239 // __if_exists, __if_not_exists can nest.
4240 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
4241 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
4245 // Check for extraneous top-level semicolon.
4246 if (Tok.is(tok::semi)) {
4247 ConsumeExtraSemi(InsideStruct, TagType);
4251 AccessSpecifier AS = getAccessSpecifierIfPresent();
4252 if (AS != AS_none) {
4253 // Current token is a C++ access specifier.
4255 SourceLocation ASLoc = Tok.getLocation();
4257 if (Tok.is(tok::colon))
4258 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
4260 Diag(Tok, diag::err_expected) << tok::colon;
4265 // Parse all the comma separated declarators.
4266 ParseCXXClassMemberDeclaration(CurAS, nullptr);
4269 Braces.consumeClose();