1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++ Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Basic/Attributes.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/OperatorKinds.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/SmallString.h"
29 using namespace clang;
31 /// ParseNamespace - We know that the current token is a namespace keyword. This
32 /// may either be a top level namespace or a block-level namespace alias. If
33 /// there was an inline keyword, it has already been parsed.
35 /// namespace-definition: [C++ 7.3: basic.namespace]
36 /// named-namespace-definition
37 /// unnamed-namespace-definition
39 /// unnamed-namespace-definition:
40 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
42 /// named-namespace-definition:
43 /// original-namespace-definition
44 /// extension-namespace-definition
46 /// original-namespace-definition:
47 /// 'inline'[opt] 'namespace' identifier attributes[opt]
48 /// '{' namespace-body '}'
50 /// extension-namespace-definition:
51 /// 'inline'[opt] 'namespace' original-namespace-name
52 /// '{' namespace-body '}'
54 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
55 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
57 Decl *Parser::ParseNamespace(unsigned Context,
58 SourceLocation &DeclEnd,
59 SourceLocation InlineLoc) {
60 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
61 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
62 ObjCDeclContextSwitch ObjCDC(*this);
64 if (Tok.is(tok::code_completion)) {
65 Actions.CodeCompleteNamespaceDecl(getCurScope());
70 SourceLocation IdentLoc;
71 IdentifierInfo *Ident = nullptr;
72 std::vector<SourceLocation> ExtraIdentLoc;
73 std::vector<IdentifierInfo*> ExtraIdent;
74 std::vector<SourceLocation> ExtraNamespaceLoc;
76 ParsedAttributesWithRange attrs(AttrFactory);
77 SourceLocation attrLoc;
78 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
79 if (!getLangOpts().CPlusPlus1z)
80 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
82 attrLoc = Tok.getLocation();
83 ParseCXX11Attributes(attrs);
86 if (Tok.is(tok::identifier)) {
87 Ident = Tok.getIdentifierInfo();
88 IdentLoc = ConsumeToken(); // eat the identifier.
89 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
90 ExtraNamespaceLoc.push_back(ConsumeToken());
91 ExtraIdent.push_back(Tok.getIdentifierInfo());
92 ExtraIdentLoc.push_back(ConsumeToken());
96 // A nested namespace definition cannot have attributes.
97 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
98 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
100 // Read label attributes, if present.
101 if (Tok.is(tok::kw___attribute)) {
102 attrLoc = Tok.getLocation();
103 ParseGNUAttributes(attrs);
106 if (Tok.is(tok::equal)) {
108 Diag(Tok, diag::err_expected) << tok::identifier;
109 // Skip to end of the definition and eat the ';'.
110 SkipUntil(tok::semi);
113 if (attrLoc.isValid())
114 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
115 if (InlineLoc.isValid())
116 Diag(InlineLoc, diag::err_inline_namespace_alias)
117 << FixItHint::CreateRemoval(InlineLoc);
118 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
122 BalancedDelimiterTracker T(*this, tok::l_brace);
123 if (T.consumeOpen()) {
125 Diag(Tok, diag::err_expected) << tok::l_brace;
127 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
131 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
132 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
133 getCurScope()->getFnParent()) {
134 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
135 SkipUntil(tok::r_brace);
139 if (ExtraIdent.empty()) {
140 // Normal namespace definition, not a nested-namespace-definition.
141 } else if (InlineLoc.isValid()) {
142 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
143 } else if (getLangOpts().CPlusPlus1z) {
144 Diag(ExtraNamespaceLoc[0],
145 diag::warn_cxx14_compat_nested_namespace_definition);
147 TentativeParsingAction TPA(*this);
148 SkipUntil(tok::r_brace, StopBeforeMatch);
149 Token rBraceToken = Tok;
152 if (!rBraceToken.is(tok::r_brace)) {
153 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
154 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
156 std::string NamespaceFix;
157 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
158 E = ExtraIdent.end(); I != E; ++I) {
159 NamespaceFix += " { namespace ";
160 NamespaceFix += (*I)->getName();
164 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
167 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
168 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
169 ExtraIdentLoc.back()),
171 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
175 // If we're still good, complain about inline namespaces in non-C++0x now.
176 if (InlineLoc.isValid())
177 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
178 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
180 // Enter a scope for the namespace.
181 ParseScope NamespaceScope(this, Scope::DeclScope);
184 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
185 IdentLoc, Ident, T.getOpenLocation(),
188 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
189 "parsing namespace");
191 // Parse the contents of the namespace. This includes parsing recovery on
192 // any improperly nested namespaces.
193 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
194 InlineLoc, attrs, T);
196 // Leave the namespace scope.
197 NamespaceScope.Exit();
199 DeclEnd = T.getCloseLocation();
200 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
205 /// ParseInnerNamespace - Parse the contents of a namespace.
206 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
207 std::vector<IdentifierInfo *> &Ident,
208 std::vector<SourceLocation> &NamespaceLoc,
209 unsigned int index, SourceLocation &InlineLoc,
210 ParsedAttributes &attrs,
211 BalancedDelimiterTracker &Tracker) {
212 if (index == Ident.size()) {
213 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
214 ParsedAttributesWithRange attrs(AttrFactory);
215 MaybeParseCXX11Attributes(attrs);
216 MaybeParseMicrosoftAttributes(attrs);
217 ParseExternalDeclaration(attrs);
220 // The caller is what called check -- we are simply calling
222 Tracker.consumeClose();
227 // Handle a nested namespace definition.
228 // FIXME: Preserve the source information through to the AST rather than
229 // desugaring it here.
230 ParseScope NamespaceScope(this, Scope::DeclScope);
232 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
233 NamespaceLoc[index], IdentLoc[index],
234 Ident[index], Tracker.getOpenLocation(),
237 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
240 NamespaceScope.Exit();
242 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
245 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
246 /// alias definition.
248 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
249 SourceLocation AliasLoc,
250 IdentifierInfo *Alias,
251 SourceLocation &DeclEnd) {
252 assert(Tok.is(tok::equal) && "Not equal token");
254 ConsumeToken(); // eat the '='.
256 if (Tok.is(tok::code_completion)) {
257 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
263 // Parse (optional) nested-name-specifier.
264 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
266 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
267 Diag(Tok, diag::err_expected_namespace_name);
268 // Skip to end of the definition and eat the ';'.
269 SkipUntil(tok::semi);
274 IdentifierInfo *Ident = Tok.getIdentifierInfo();
275 SourceLocation IdentLoc = ConsumeToken();
278 DeclEnd = Tok.getLocation();
279 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
280 SkipUntil(tok::semi);
282 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
283 SS, IdentLoc, Ident);
286 /// ParseLinkage - We know that the current token is a string_literal
287 /// and just before that, that extern was seen.
289 /// linkage-specification: [C++ 7.5p2: dcl.link]
290 /// 'extern' string-literal '{' declaration-seq[opt] '}'
291 /// 'extern' string-literal declaration
293 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
294 assert(isTokenStringLiteral() && "Not a string literal!");
295 ExprResult Lang = ParseStringLiteralExpression(false);
297 ParseScope LinkageScope(this, Scope::DeclScope);
301 : Actions.ActOnStartLinkageSpecification(
302 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
303 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
305 ParsedAttributesWithRange attrs(AttrFactory);
306 MaybeParseCXX11Attributes(attrs);
307 MaybeParseMicrosoftAttributes(attrs);
309 if (Tok.isNot(tok::l_brace)) {
310 // Reset the source range in DS, as the leading "extern"
311 // does not really belong to the inner declaration ...
312 DS.SetRangeStart(SourceLocation());
313 DS.SetRangeEnd(SourceLocation());
314 // ... but anyway remember that such an "extern" was seen.
315 DS.setExternInLinkageSpec(true);
316 ParseExternalDeclaration(attrs, &DS);
317 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
318 getCurScope(), LinkageSpec, SourceLocation())
324 ProhibitAttributes(attrs);
326 BalancedDelimiterTracker T(*this, tok::l_brace);
329 unsigned NestedModules = 0;
331 switch (Tok.getKind()) {
332 case tok::annot_module_begin:
337 case tok::annot_module_end:
344 case tok::annot_module_include:
356 ParsedAttributesWithRange attrs(AttrFactory);
357 MaybeParseCXX11Attributes(attrs);
358 MaybeParseMicrosoftAttributes(attrs);
359 ParseExternalDeclaration(attrs);
367 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
368 getCurScope(), LinkageSpec, T.getCloseLocation())
372 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
373 /// using-directive. Assumes that current token is 'using'.
374 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
375 const ParsedTemplateInfo &TemplateInfo,
376 SourceLocation &DeclEnd,
377 ParsedAttributesWithRange &attrs,
379 assert(Tok.is(tok::kw_using) && "Not using token");
380 ObjCDeclContextSwitch ObjCDC(*this);
383 SourceLocation UsingLoc = ConsumeToken();
385 if (Tok.is(tok::code_completion)) {
386 Actions.CodeCompleteUsing(getCurScope());
391 // 'using namespace' means this is a using-directive.
392 if (Tok.is(tok::kw_namespace)) {
393 // Template parameters are always an error here.
394 if (TemplateInfo.Kind) {
395 SourceRange R = TemplateInfo.getSourceRange();
396 Diag(UsingLoc, diag::err_templated_using_directive)
397 << R << FixItHint::CreateRemoval(R);
400 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
403 // Otherwise, it must be a using-declaration or an alias-declaration.
405 // Using declarations can't have attributes.
406 ProhibitAttributes(attrs);
408 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
412 /// ParseUsingDirective - Parse C++ using-directive, assumes
413 /// that current token is 'namespace' and 'using' was already parsed.
415 /// using-directive: [C++ 7.3.p4: namespace.udir]
416 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
418 /// [GNU] using-directive:
419 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
420 /// namespace-name attributes[opt] ;
422 Decl *Parser::ParseUsingDirective(unsigned Context,
423 SourceLocation UsingLoc,
424 SourceLocation &DeclEnd,
425 ParsedAttributes &attrs) {
426 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
429 SourceLocation NamespcLoc = ConsumeToken();
431 if (Tok.is(tok::code_completion)) {
432 Actions.CodeCompleteUsingDirective(getCurScope());
438 // Parse (optional) nested-name-specifier.
439 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
441 IdentifierInfo *NamespcName = nullptr;
442 SourceLocation IdentLoc = SourceLocation();
444 // Parse namespace-name.
445 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
446 Diag(Tok, diag::err_expected_namespace_name);
447 // If there was invalid namespace name, skip to end of decl, and eat ';'.
448 SkipUntil(tok::semi);
449 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
454 NamespcName = Tok.getIdentifierInfo();
455 IdentLoc = ConsumeToken();
457 // Parse (optional) attributes (most likely GNU strong-using extension).
458 bool GNUAttr = false;
459 if (Tok.is(tok::kw___attribute)) {
461 ParseGNUAttributes(attrs);
465 DeclEnd = Tok.getLocation();
466 if (ExpectAndConsume(tok::semi,
467 GNUAttr ? diag::err_expected_semi_after_attribute_list
468 : diag::err_expected_semi_after_namespace_name))
469 SkipUntil(tok::semi);
471 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
472 IdentLoc, NamespcName, attrs.getList());
475 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
476 /// Assumes that 'using' was already seen.
478 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
479 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
481 /// 'using' :: unqualified-id
483 /// alias-declaration: C++11 [dcl.dcl]p1
484 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
486 Decl *Parser::ParseUsingDeclaration(unsigned Context,
487 const ParsedTemplateInfo &TemplateInfo,
488 SourceLocation UsingLoc,
489 SourceLocation &DeclEnd,
493 SourceLocation TypenameLoc;
494 bool HasTypenameKeyword = false;
496 // Check for misplaced attributes before the identifier in an
497 // alias-declaration.
498 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
499 MaybeParseCXX11Attributes(MisplacedAttrs);
501 // Ignore optional 'typename'.
502 // FIXME: This is wrong; we should parse this as a typename-specifier.
503 if (TryConsumeToken(tok::kw_typename, TypenameLoc))
504 HasTypenameKeyword = true;
506 if (Tok.is(tok::kw___super)) {
507 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
508 SkipUntil(tok::semi);
512 // Parse nested-name-specifier.
513 IdentifierInfo *LastII = nullptr;
514 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false,
515 /*MayBePseudoDtor=*/nullptr,
516 /*IsTypename=*/false,
519 // Check nested-name specifier.
520 if (SS.isInvalid()) {
521 SkipUntil(tok::semi);
525 SourceLocation TemplateKWLoc;
528 // Parse the unqualified-id. We allow parsing of both constructor and
529 // destructor names and allow the action module to diagnose any semantic
532 // C++11 [class.qual]p2:
533 // [...] in a using-declaration that is a member-declaration, if the name
534 // specified after the nested-name-specifier is the same as the identifier
535 // or the simple-template-id's template-name in the last component of the
536 // nested-name-specifier, the name is [...] considered to name the
538 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
539 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
540 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
541 !SS.getScopeRep()->getAsNamespace() &&
542 !SS.getScopeRep()->getAsNamespaceAlias()) {
543 SourceLocation IdLoc = ConsumeToken();
544 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
545 Name.setConstructorName(Type, IdLoc, IdLoc);
546 } else if (ParseUnqualifiedId(SS, /*EnteringContext=*/ false,
547 /*AllowDestructorName=*/ true,
548 /*AllowConstructorName=*/ true, ParsedType(),
549 TemplateKWLoc, Name)) {
550 SkipUntil(tok::semi);
554 ParsedAttributesWithRange Attrs(AttrFactory);
555 MaybeParseGNUAttributes(Attrs);
556 MaybeParseCXX11Attributes(Attrs);
558 // Maybe this is an alias-declaration.
559 TypeResult TypeAlias;
560 bool IsAliasDecl = Tok.is(tok::equal);
561 Decl *DeclFromDeclSpec = nullptr;
563 // If we had any misplaced attributes from earlier, this is where they
564 // should have been written.
565 if (MisplacedAttrs.Range.isValid()) {
566 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
567 << FixItHint::CreateInsertionFromRange(
569 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
570 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
571 Attrs.takeAllFrom(MisplacedAttrs);
576 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
577 diag::warn_cxx98_compat_alias_declaration :
578 diag::ext_alias_declaration);
580 // Type alias templates cannot be specialized.
582 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
583 Name.getKind() == UnqualifiedId::IK_TemplateId)
585 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
587 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
589 if (SpecKind != -1) {
592 Range = SourceRange(Name.TemplateId->LAngleLoc,
593 Name.TemplateId->RAngleLoc);
595 Range = TemplateInfo.getSourceRange();
596 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
597 << SpecKind << Range;
598 SkipUntil(tok::semi);
602 // Name must be an identifier.
603 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
604 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
605 // No removal fixit: can't recover from this.
606 SkipUntil(tok::semi);
608 } else if (HasTypenameKeyword)
609 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
610 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
611 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
612 else if (SS.isNotEmpty())
613 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
614 << FixItHint::CreateRemoval(SS.getRange());
616 TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind
617 ? Declarator::AliasTemplateContext
618 : Declarator::AliasDeclContext,
619 AS, &DeclFromDeclSpec, &Attrs);
621 *OwnedType = DeclFromDeclSpec;
623 // C++11 attributes are not allowed on a using-declaration, but GNU ones
625 ProhibitAttributes(MisplacedAttrs);
626 ProhibitAttributes(Attrs);
628 // Parse (optional) attributes (most likely GNU strong-using extension).
629 MaybeParseGNUAttributes(Attrs);
633 DeclEnd = Tok.getLocation();
634 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
635 !Attrs.empty() ? "attributes list"
636 : IsAliasDecl ? "alias declaration"
637 : "using declaration"))
638 SkipUntil(tok::semi);
640 // Diagnose an attempt to declare a templated using-declaration.
641 // In C++11, alias-declarations can be templates:
642 // template <...> using id = type;
643 if (TemplateInfo.Kind && !IsAliasDecl) {
644 SourceRange R = TemplateInfo.getSourceRange();
645 Diag(UsingLoc, diag::err_templated_using_declaration)
646 << R << FixItHint::CreateRemoval(R);
648 // Unfortunately, we have to bail out instead of recovering by
649 // ignoring the parameters, just in case the nested name specifier
650 // depends on the parameters.
654 // "typename" keyword is allowed for identifiers only,
655 // because it may be a type definition.
656 if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
657 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
658 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
659 // Proceed parsing, but reset the HasTypenameKeyword flag.
660 HasTypenameKeyword = false;
664 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
665 MultiTemplateParamsArg TemplateParamsArg(
666 TemplateParams ? TemplateParams->data() : nullptr,
667 TemplateParams ? TemplateParams->size() : 0);
668 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
669 UsingLoc, Name, Attrs.getList(),
670 TypeAlias, DeclFromDeclSpec);
673 return Actions.ActOnUsingDeclaration(getCurScope(), AS,
674 /* HasUsingKeyword */ true, UsingLoc,
675 SS, Name, Attrs.getList(),
676 HasTypenameKeyword, TypenameLoc);
679 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
681 /// [C++0x] static_assert-declaration:
682 /// static_assert ( constant-expression , string-literal ) ;
684 /// [C11] static_assert-declaration:
685 /// _Static_assert ( constant-expression , string-literal ) ;
687 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
688 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
689 "Not a static_assert declaration");
691 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
692 Diag(Tok, diag::ext_c11_static_assert);
693 if (Tok.is(tok::kw_static_assert))
694 Diag(Tok, diag::warn_cxx98_compat_static_assert);
696 SourceLocation StaticAssertLoc = ConsumeToken();
698 BalancedDelimiterTracker T(*this, tok::l_paren);
699 if (T.consumeOpen()) {
700 Diag(Tok, diag::err_expected) << tok::l_paren;
705 ExprResult AssertExpr(ParseConstantExpression());
706 if (AssertExpr.isInvalid()) {
711 ExprResult AssertMessage;
712 if (Tok.is(tok::r_paren)) {
713 Diag(Tok, getLangOpts().CPlusPlus1z
714 ? diag::warn_cxx14_compat_static_assert_no_message
715 : diag::ext_static_assert_no_message)
716 << (getLangOpts().CPlusPlus1z
718 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
720 if (ExpectAndConsume(tok::comma)) {
721 SkipUntil(tok::semi);
725 if (!isTokenStringLiteral()) {
726 Diag(Tok, diag::err_expected_string_literal)
727 << /*Source='static_assert'*/1;
732 AssertMessage = ParseStringLiteralExpression();
733 if (AssertMessage.isInvalid()) {
741 DeclEnd = Tok.getLocation();
742 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
744 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
747 T.getCloseLocation());
750 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
752 /// 'decltype' ( expression )
753 /// 'decltype' ( 'auto' ) [C++1y]
755 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
756 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
757 && "Not a decltype specifier");
760 SourceLocation StartLoc = Tok.getLocation();
761 SourceLocation EndLoc;
763 if (Tok.is(tok::annot_decltype)) {
764 Result = getExprAnnotation(Tok);
765 EndLoc = Tok.getAnnotationEndLoc();
767 if (Result.isInvalid()) {
768 DS.SetTypeSpecError();
772 if (Tok.getIdentifierInfo()->isStr("decltype"))
773 Diag(Tok, diag::warn_cxx98_compat_decltype);
777 BalancedDelimiterTracker T(*this, tok::l_paren);
778 if (T.expectAndConsume(diag::err_expected_lparen_after,
779 "decltype", tok::r_paren)) {
780 DS.SetTypeSpecError();
781 return T.getOpenLocation() == Tok.getLocation() ?
782 StartLoc : T.getOpenLocation();
785 // Check for C++1y 'decltype(auto)'.
786 if (Tok.is(tok::kw_auto)) {
787 // No need to disambiguate here: an expression can't start with 'auto',
788 // because the typename-specifier in a function-style cast operation can't
790 Diag(Tok.getLocation(),
791 getLangOpts().CPlusPlus14
792 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
793 : diag::ext_decltype_auto_type_specifier);
796 // Parse the expression
798 // C++11 [dcl.type.simple]p4:
799 // The operand of the decltype specifier is an unevaluated operand.
800 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
801 nullptr,/*IsDecltype=*/true);
803 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
804 return E->hasPlaceholderType() ? ExprError() : E;
806 if (Result.isInvalid()) {
807 DS.SetTypeSpecError();
808 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
809 EndLoc = ConsumeParen();
811 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
812 // Backtrack to get the location of the last token before the semi.
813 PP.RevertCachedTokens(2);
814 ConsumeToken(); // the semi.
815 EndLoc = ConsumeAnyToken();
816 assert(Tok.is(tok::semi));
818 EndLoc = Tok.getLocation();
824 Result = Actions.ActOnDecltypeExpression(Result.get());
829 if (T.getCloseLocation().isInvalid()) {
830 DS.SetTypeSpecError();
831 // FIXME: this should return the location of the last token
832 // that was consumed (by "consumeClose()")
833 return T.getCloseLocation();
836 if (Result.isInvalid()) {
837 DS.SetTypeSpecError();
838 return T.getCloseLocation();
841 EndLoc = T.getCloseLocation();
843 assert(!Result.isInvalid());
845 const char *PrevSpec = nullptr;
847 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
848 // Check for duplicate type specifiers (e.g. "int decltype(a)").
850 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
851 DiagID, Result.get(), Policy)
852 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
854 Diag(StartLoc, DiagID) << PrevSpec;
855 DS.SetTypeSpecError();
860 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
861 SourceLocation StartLoc,
862 SourceLocation EndLoc) {
863 // make sure we have a token we can turn into an annotation token
864 if (PP.isBacktrackEnabled())
865 PP.RevertCachedTokens(1);
869 Tok.setKind(tok::annot_decltype);
870 setExprAnnotation(Tok,
871 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
872 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
874 Tok.setAnnotationEndLoc(EndLoc);
875 Tok.setLocation(StartLoc);
876 PP.AnnotateCachedTokens(Tok);
879 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
880 assert(Tok.is(tok::kw___underlying_type) &&
881 "Not an underlying type specifier");
883 SourceLocation StartLoc = ConsumeToken();
884 BalancedDelimiterTracker T(*this, tok::l_paren);
885 if (T.expectAndConsume(diag::err_expected_lparen_after,
886 "__underlying_type", tok::r_paren)) {
890 TypeResult Result = ParseTypeName();
891 if (Result.isInvalid()) {
892 SkipUntil(tok::r_paren, StopAtSemi);
898 if (T.getCloseLocation().isInvalid())
901 const char *PrevSpec = nullptr;
903 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
904 DiagID, Result.get(),
905 Actions.getASTContext().getPrintingPolicy()))
906 Diag(StartLoc, DiagID) << PrevSpec;
907 DS.setTypeofParensRange(T.getRange());
910 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
911 /// class name or decltype-specifier. Note that we only check that the result
912 /// names a type; semantic analysis will need to verify that the type names a
913 /// class. The result is either a type or null, depending on whether a type
916 /// base-type-specifier: [C++11 class.derived]
917 /// class-or-decltype
918 /// class-or-decltype: [C++11 class.derived]
919 /// nested-name-specifier[opt] class-name
920 /// decltype-specifier
921 /// class-name: [C++ class.name]
923 /// simple-template-id
925 /// In C++98, instead of base-type-specifier, we have:
927 /// ::[opt] nested-name-specifier[opt] class-name
928 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
929 SourceLocation &EndLocation) {
930 // Ignore attempts to use typename
931 if (Tok.is(tok::kw_typename)) {
932 Diag(Tok, diag::err_expected_class_name_not_template)
933 << FixItHint::CreateRemoval(Tok.getLocation());
937 // Parse optional nested-name-specifier
939 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
941 BaseLoc = Tok.getLocation();
943 // Parse decltype-specifier
944 // tok == kw_decltype is just error recovery, it can only happen when SS
946 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
948 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
949 << FixItHint::CreateRemoval(SS.getRange());
950 // Fake up a Declarator to use with ActOnTypeName.
951 DeclSpec DS(AttrFactory);
953 EndLocation = ParseDecltypeSpecifier(DS);
955 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
956 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
959 // Check whether we have a template-id that names a type.
960 if (Tok.is(tok::annot_template_id)) {
961 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
962 if (TemplateId->Kind == TNK_Type_template ||
963 TemplateId->Kind == TNK_Dependent_template_name) {
964 AnnotateTemplateIdTokenAsType();
966 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
967 ParsedType Type = getTypeAnnotation(Tok);
968 EndLocation = Tok.getAnnotationEndLoc();
976 // Fall through to produce an error below.
979 if (Tok.isNot(tok::identifier)) {
980 Diag(Tok, diag::err_expected_class_name);
984 IdentifierInfo *Id = Tok.getIdentifierInfo();
985 SourceLocation IdLoc = ConsumeToken();
987 if (Tok.is(tok::less)) {
988 // It looks the user intended to write a template-id here, but the
989 // template-name was wrong. Try to fix that.
990 TemplateNameKind TNK = TNK_Type_template;
992 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
993 &SS, Template, TNK)) {
994 Diag(IdLoc, diag::err_unknown_template_name)
999 TemplateArgList TemplateArgs;
1000 SourceLocation LAngleLoc, RAngleLoc;
1001 ParseTemplateIdAfterTemplateName(TemplateTy(), IdLoc, SS,
1002 true, LAngleLoc, TemplateArgs, RAngleLoc);
1006 // Form the template name
1007 UnqualifiedId TemplateName;
1008 TemplateName.setIdentifier(Id, IdLoc);
1010 // Parse the full template-id, then turn it into a type.
1011 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1012 TemplateName, true))
1014 if (TNK == TNK_Dependent_template_name)
1015 AnnotateTemplateIdTokenAsType();
1017 // If we didn't end up with a typename token, there's nothing more we
1019 if (Tok.isNot(tok::annot_typename))
1022 // Retrieve the type from the annotation token, consume that token, and
1024 EndLocation = Tok.getAnnotationEndLoc();
1025 ParsedType Type = getTypeAnnotation(Tok);
1030 // We have an identifier; check whether it is actually a type.
1031 IdentifierInfo *CorrectedII = nullptr;
1032 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
1033 false, ParsedType(),
1034 /*IsCtorOrDtorName=*/false,
1035 /*NonTrivialTypeSourceInfo=*/true,
1038 Diag(IdLoc, diag::err_expected_class_name);
1042 // Consume the identifier.
1043 EndLocation = IdLoc;
1045 // Fake up a Declarator to use with ActOnTypeName.
1046 DeclSpec DS(AttrFactory);
1047 DS.SetRangeStart(IdLoc);
1048 DS.SetRangeEnd(EndLocation);
1049 DS.getTypeSpecScope() = SS;
1051 const char *PrevSpec = nullptr;
1053 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1054 Actions.getASTContext().getPrintingPolicy());
1056 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1057 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1060 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1061 while (Tok.isOneOf(tok::kw___single_inheritance,
1062 tok::kw___multiple_inheritance,
1063 tok::kw___virtual_inheritance)) {
1064 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1065 SourceLocation AttrNameLoc = ConsumeToken();
1066 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1067 AttributeList::AS_Keyword);
1071 /// Determine whether the following tokens are valid after a type-specifier
1072 /// which could be a standalone declaration. This will conservatively return
1073 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1074 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1075 // This switch enumerates the valid "follow" set for type-specifiers.
1076 switch (Tok.getKind()) {
1078 case tok::semi: // struct foo {...} ;
1079 case tok::star: // struct foo {...} * P;
1080 case tok::amp: // struct foo {...} & R = ...
1081 case tok::ampamp: // struct foo {...} && R = ...
1082 case tok::identifier: // struct foo {...} V ;
1083 case tok::r_paren: //(struct foo {...} ) {4}
1084 case tok::annot_cxxscope: // struct foo {...} a:: b;
1085 case tok::annot_typename: // struct foo {...} a ::b;
1086 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1087 case tok::l_paren: // struct foo {...} ( x);
1088 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1089 case tok::kw_operator: // struct foo operator ++() {...}
1090 case tok::kw___declspec: // struct foo {...} __declspec(...)
1091 case tok::l_square: // void f(struct f [ 3])
1092 case tok::ellipsis: // void f(struct f ... [Ns])
1093 // FIXME: we should emit semantic diagnostic when declaration
1094 // attribute is in type attribute position.
1095 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1098 return CouldBeBitfield; // enum E { ... } : 2;
1100 case tok::kw_const: // struct foo {...} const x;
1101 case tok::kw_volatile: // struct foo {...} volatile x;
1102 case tok::kw_restrict: // struct foo {...} restrict x;
1103 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1104 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1105 // Function specifiers
1106 // Note, no 'explicit'. An explicit function must be either a conversion
1107 // operator or a constructor. Either way, it can't have a return type.
1108 case tok::kw_inline: // struct foo inline f();
1109 case tok::kw_virtual: // struct foo virtual f();
1110 case tok::kw_friend: // struct foo friend f();
1111 // Storage-class specifiers
1112 case tok::kw_static: // struct foo {...} static x;
1113 case tok::kw_extern: // struct foo {...} extern x;
1114 case tok::kw_typedef: // struct foo {...} typedef x;
1115 case tok::kw_register: // struct foo {...} register x;
1116 case tok::kw_auto: // struct foo {...} auto x;
1117 case tok::kw_mutable: // struct foo {...} mutable x;
1118 case tok::kw_thread_local: // struct foo {...} thread_local x;
1119 case tok::kw_constexpr: // struct foo {...} constexpr x;
1120 // As shown above, type qualifiers and storage class specifiers absolutely
1121 // can occur after class specifiers according to the grammar. However,
1122 // almost no one actually writes code like this. If we see one of these,
1123 // it is much more likely that someone missed a semi colon and the
1124 // type/storage class specifier we're seeing is part of the *next*
1125 // intended declaration, as in:
1127 // struct foo { ... }
1130 // We'd really like to emit a missing semicolon error instead of emitting
1131 // an error on the 'int' saying that you can't have two type specifiers in
1132 // the same declaration of X. Because of this, we look ahead past this
1133 // token to see if it's a type specifier. If so, we know the code is
1134 // otherwise invalid, so we can produce the expected semi error.
1135 if (!isKnownToBeTypeSpecifier(NextToken()))
1138 case tok::r_brace: // struct bar { struct foo {...} }
1139 // Missing ';' at end of struct is accepted as an extension in C mode.
1140 if (!getLangOpts().CPlusPlus)
1144 // template<class T = class X>
1145 return getLangOpts().CPlusPlus;
1150 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1151 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1152 /// until we reach the start of a definition or see a token that
1153 /// cannot start a definition.
1155 /// class-specifier: [C++ class]
1156 /// class-head '{' member-specification[opt] '}'
1157 /// class-head '{' member-specification[opt] '}' attributes[opt]
1159 /// class-key identifier[opt] base-clause[opt]
1160 /// class-key nested-name-specifier identifier base-clause[opt]
1161 /// class-key nested-name-specifier[opt] simple-template-id
1162 /// base-clause[opt]
1163 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1164 /// [GNU] class-key attributes[opt] nested-name-specifier
1165 /// identifier base-clause[opt]
1166 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1167 /// simple-template-id base-clause[opt]
1173 /// elaborated-type-specifier: [C++ dcl.type.elab]
1174 /// class-key ::[opt] nested-name-specifier[opt] identifier
1175 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1176 /// simple-template-id
1178 /// Note that the C++ class-specifier and elaborated-type-specifier,
1179 /// together, subsume the C99 struct-or-union-specifier:
1181 /// struct-or-union-specifier: [C99 6.7.2.1]
1182 /// struct-or-union identifier[opt] '{' struct-contents '}'
1183 /// struct-or-union identifier
1184 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1185 /// '}' attributes[opt]
1186 /// [GNU] struct-or-union attributes[opt] identifier
1187 /// struct-or-union:
1190 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1191 SourceLocation StartLoc, DeclSpec &DS,
1192 const ParsedTemplateInfo &TemplateInfo,
1194 bool EnteringContext, DeclSpecContext DSC,
1195 ParsedAttributesWithRange &Attributes) {
1196 DeclSpec::TST TagType;
1197 if (TagTokKind == tok::kw_struct)
1198 TagType = DeclSpec::TST_struct;
1199 else if (TagTokKind == tok::kw___interface)
1200 TagType = DeclSpec::TST_interface;
1201 else if (TagTokKind == tok::kw_class)
1202 TagType = DeclSpec::TST_class;
1204 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1205 TagType = DeclSpec::TST_union;
1208 if (Tok.is(tok::code_completion)) {
1209 // Code completion for a struct, class, or union name.
1210 Actions.CodeCompleteTag(getCurScope(), TagType);
1211 return cutOffParsing();
1214 // C++03 [temp.explicit] 14.7.2/8:
1215 // The usual access checking rules do not apply to names used to specify
1216 // explicit instantiations.
1218 // As an extension we do not perform access checking on the names used to
1219 // specify explicit specializations either. This is important to allow
1220 // specializing traits classes for private types.
1222 // Note that we don't suppress if this turns out to be an elaborated
1224 bool shouldDelayDiagsInTag =
1225 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1226 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1227 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1229 ParsedAttributesWithRange attrs(AttrFactory);
1230 // If attributes exist after tag, parse them.
1231 MaybeParseGNUAttributes(attrs);
1232 MaybeParseMicrosoftDeclSpecs(attrs);
1234 // Parse inheritance specifiers.
1235 if (Tok.isOneOf(tok::kw___single_inheritance,
1236 tok::kw___multiple_inheritance,
1237 tok::kw___virtual_inheritance))
1238 ParseMicrosoftInheritanceClassAttributes(attrs);
1240 // If C++0x attributes exist here, parse them.
1241 // FIXME: Are we consistent with the ordering of parsing of different
1242 // styles of attributes?
1243 MaybeParseCXX11Attributes(attrs);
1245 // Source location used by FIXIT to insert misplaced
1247 SourceLocation AttrFixitLoc = Tok.getLocation();
1249 if (TagType == DeclSpec::TST_struct &&
1250 Tok.isNot(tok::identifier) &&
1251 !Tok.isAnnotation() &&
1252 Tok.getIdentifierInfo() &&
1253 Tok.isOneOf(tok::kw___is_abstract,
1254 tok::kw___is_arithmetic,
1256 tok::kw___is_base_of,
1258 tok::kw___is_complete_type,
1259 tok::kw___is_compound,
1261 tok::kw___is_constructible,
1262 tok::kw___is_convertible,
1263 tok::kw___is_convertible_to,
1264 tok::kw___is_destructible,
1267 tok::kw___is_floating_point,
1269 tok::kw___is_function,
1270 tok::kw___is_fundamental,
1271 tok::kw___is_integral,
1272 tok::kw___is_interface_class,
1273 tok::kw___is_literal,
1274 tok::kw___is_lvalue_expr,
1275 tok::kw___is_lvalue_reference,
1276 tok::kw___is_member_function_pointer,
1277 tok::kw___is_member_object_pointer,
1278 tok::kw___is_member_pointer,
1279 tok::kw___is_nothrow_assignable,
1280 tok::kw___is_nothrow_constructible,
1281 tok::kw___is_nothrow_destructible,
1282 tok::kw___is_object,
1284 tok::kw___is_pointer,
1285 tok::kw___is_polymorphic,
1286 tok::kw___is_reference,
1287 tok::kw___is_rvalue_expr,
1288 tok::kw___is_rvalue_reference,
1290 tok::kw___is_scalar,
1291 tok::kw___is_sealed,
1292 tok::kw___is_signed,
1293 tok::kw___is_standard_layout,
1294 tok::kw___is_trivial,
1295 tok::kw___is_trivially_assignable,
1296 tok::kw___is_trivially_constructible,
1297 tok::kw___is_trivially_copyable,
1299 tok::kw___is_unsigned,
1301 tok::kw___is_volatile))
1302 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1303 // name of struct templates, but some are keywords in GCC >= 4.3
1304 // and Clang. Therefore, when we see the token sequence "struct
1305 // X", make X into a normal identifier rather than a keyword, to
1306 // allow libstdc++ 4.2 and libc++ to work properly.
1307 TryKeywordIdentFallback(true);
1309 // Parse the (optional) nested-name-specifier.
1310 CXXScopeSpec &SS = DS.getTypeSpecScope();
1311 if (getLangOpts().CPlusPlus) {
1312 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1313 // is a base-specifier-list.
1314 ColonProtectionRAIIObject X(*this);
1317 bool HasValidSpec = true;
1318 if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(), EnteringContext)) {
1319 DS.SetTypeSpecError();
1320 HasValidSpec = false;
1323 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1324 Diag(Tok, diag::err_expected) << tok::identifier;
1325 HasValidSpec = false;
1331 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1333 // Parse the (optional) class name or simple-template-id.
1334 IdentifierInfo *Name = nullptr;
1335 SourceLocation NameLoc;
1336 TemplateIdAnnotation *TemplateId = nullptr;
1337 if (Tok.is(tok::identifier)) {
1338 Name = Tok.getIdentifierInfo();
1339 NameLoc = ConsumeToken();
1341 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1342 // The name was supposed to refer to a template, but didn't.
1343 // Eat the template argument list and try to continue parsing this as
1344 // a class (or template thereof).
1345 TemplateArgList TemplateArgs;
1346 SourceLocation LAngleLoc, RAngleLoc;
1347 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1349 TemplateArgs, RAngleLoc)) {
1350 // We couldn't parse the template argument list at all, so don't
1351 // try to give any location information for the list.
1352 LAngleLoc = RAngleLoc = SourceLocation();
1355 Diag(NameLoc, diag::err_explicit_spec_non_template)
1356 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1357 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1359 // Strip off the last template parameter list if it was empty, since
1360 // we've removed its template argument list.
1361 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1362 if (TemplateParams && TemplateParams->size() > 1) {
1363 TemplateParams->pop_back();
1365 TemplateParams = nullptr;
1366 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1367 = ParsedTemplateInfo::NonTemplate;
1369 } else if (TemplateInfo.Kind
1370 == ParsedTemplateInfo::ExplicitInstantiation) {
1371 // Pretend this is just a forward declaration.
1372 TemplateParams = nullptr;
1373 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1374 = ParsedTemplateInfo::NonTemplate;
1375 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1377 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1381 } else if (Tok.is(tok::annot_template_id)) {
1382 TemplateId = takeTemplateIdAnnotation(Tok);
1383 NameLoc = ConsumeToken();
1385 if (TemplateId->Kind != TNK_Type_template &&
1386 TemplateId->Kind != TNK_Dependent_template_name) {
1387 // The template-name in the simple-template-id refers to
1388 // something other than a class template. Give an appropriate
1389 // error message and skip to the ';'.
1390 SourceRange Range(NameLoc);
1391 if (SS.isNotEmpty())
1392 Range.setBegin(SS.getBeginLoc());
1394 // FIXME: Name may be null here.
1395 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1396 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1398 DS.SetTypeSpecError();
1399 SkipUntil(tok::semi, StopBeforeMatch);
1404 // There are four options here.
1405 // - If we are in a trailing return type, this is always just a reference,
1406 // and we must not try to parse a definition. For instance,
1407 // [] () -> struct S { };
1408 // does not define a type.
1409 // - If we have 'struct foo {...', 'struct foo :...',
1410 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1411 // - If we have 'struct foo;', then this is either a forward declaration
1412 // or a friend declaration, which have to be treated differently.
1413 // - Otherwise we have something like 'struct foo xyz', a reference.
1415 // We also detect these erroneous cases to provide better diagnostic for
1416 // C++11 attributes parsing.
1417 // - attributes follow class name:
1418 // struct foo [[]] {};
1419 // - attributes appear before or after 'final':
1420 // struct foo [[]] final [[]] {};
1422 // However, in type-specifier-seq's, things look like declarations but are
1423 // just references, e.g.
1426 // &T::operator struct s;
1427 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
1429 // If there are attributes after class name, parse them.
1430 MaybeParseCXX11Attributes(Attributes);
1432 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1433 Sema::TagUseKind TUK;
1434 if (DSC == DSC_trailing)
1435 TUK = Sema::TUK_Reference;
1436 else if (Tok.is(tok::l_brace) ||
1437 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1438 (isCXX11FinalKeyword() &&
1439 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1440 if (DS.isFriendSpecified()) {
1441 // C++ [class.friend]p2:
1442 // A class shall not be defined in a friend declaration.
1443 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1444 << SourceRange(DS.getFriendSpecLoc());
1446 // Skip everything up to the semicolon, so that this looks like a proper
1447 // friend class (or template thereof) declaration.
1448 SkipUntil(tok::semi, StopBeforeMatch);
1449 TUK = Sema::TUK_Friend;
1451 // Okay, this is a class definition.
1452 TUK = Sema::TUK_Definition;
1454 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1455 NextToken().is(tok::kw_alignas))) {
1456 // We can't tell if this is a definition or reference
1457 // until we skipped the 'final' and C++11 attribute specifiers.
1458 TentativeParsingAction PA(*this);
1460 // Skip the 'final' keyword.
1463 // Skip C++11 attribute specifiers.
1465 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1467 if (!SkipUntil(tok::r_square, StopAtSemi))
1469 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1472 if (!SkipUntil(tok::r_paren, StopAtSemi))
1479 if (Tok.isOneOf(tok::l_brace, tok::colon))
1480 TUK = Sema::TUK_Definition;
1482 TUK = Sema::TUK_Reference;
1485 } else if (!isTypeSpecifier(DSC) &&
1486 (Tok.is(tok::semi) ||
1487 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1488 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1489 if (Tok.isNot(tok::semi)) {
1490 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1491 // A semicolon was missing after this declaration. Diagnose and recover.
1492 ExpectAndConsume(tok::semi, diag::err_expected_after,
1493 DeclSpec::getSpecifierName(TagType, PPol));
1495 Tok.setKind(tok::semi);
1498 TUK = Sema::TUK_Reference;
1500 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1501 // to caller to handle.
1502 if (TUK != Sema::TUK_Reference) {
1503 // If this is not a reference, then the only possible
1504 // valid place for C++11 attributes to appear here
1505 // is between class-key and class-name. If there are
1506 // any attributes after class-name, we try a fixit to move
1507 // them to the right place.
1508 SourceRange AttrRange = Attributes.Range;
1509 if (AttrRange.isValid()) {
1510 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1512 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1513 CharSourceRange(AttrRange, true))
1514 << FixItHint::CreateRemoval(AttrRange);
1516 // Recover by adding misplaced attributes to the attribute list
1517 // of the class so they can be applied on the class later.
1518 attrs.takeAllFrom(Attributes);
1522 // If this is an elaborated type specifier, and we delayed
1523 // diagnostics before, just merge them into the current pool.
1524 if (shouldDelayDiagsInTag) {
1525 diagsFromTag.done();
1526 if (TUK == Sema::TUK_Reference)
1527 diagsFromTag.redelay();
1530 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1531 TUK != Sema::TUK_Definition)) {
1532 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1533 // We have a declaration or reference to an anonymous class.
1534 Diag(StartLoc, diag::err_anon_type_definition)
1535 << DeclSpec::getSpecifierName(TagType, Policy);
1538 // If we are parsing a definition and stop at a base-clause, continue on
1539 // until the semicolon. Continuing from the comma will just trick us into
1540 // thinking we are seeing a variable declaration.
1541 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1542 SkipUntil(tok::semi, StopBeforeMatch);
1544 SkipUntil(tok::comma, StopAtSemi);
1548 // Create the tag portion of the class or class template.
1549 DeclResult TagOrTempResult = true; // invalid
1550 TypeResult TypeResult = true; // invalid
1553 Sema::SkipBodyInfo SkipBody;
1555 // Explicit specialization, class template partial specialization,
1556 // or explicit instantiation.
1557 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1558 TemplateId->NumArgs);
1559 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1560 TUK == Sema::TUK_Declaration) {
1561 // This is an explicit instantiation of a class template.
1562 ProhibitAttributes(attrs);
1565 = Actions.ActOnExplicitInstantiation(getCurScope(),
1566 TemplateInfo.ExternLoc,
1567 TemplateInfo.TemplateLoc,
1571 TemplateId->Template,
1572 TemplateId->TemplateNameLoc,
1573 TemplateId->LAngleLoc,
1575 TemplateId->RAngleLoc,
1578 // Friend template-ids are treated as references unless
1579 // they have template headers, in which case they're ill-formed
1580 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1581 // We diagnose this error in ActOnClassTemplateSpecialization.
1582 } else if (TUK == Sema::TUK_Reference ||
1583 (TUK == Sema::TUK_Friend &&
1584 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1585 ProhibitAttributes(attrs);
1586 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1588 TemplateId->TemplateKWLoc,
1589 TemplateId->Template,
1590 TemplateId->TemplateNameLoc,
1591 TemplateId->LAngleLoc,
1593 TemplateId->RAngleLoc);
1595 // This is an explicit specialization or a class template
1596 // partial specialization.
1597 TemplateParameterLists FakedParamLists;
1598 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1599 // This looks like an explicit instantiation, because we have
1602 // template class Foo<X>
1604 // but it actually has a definition. Most likely, this was
1605 // meant to be an explicit specialization, but the user forgot
1606 // the '<>' after 'template'.
1607 // It this is friend declaration however, since it cannot have a
1608 // template header, it is most likely that the user meant to
1609 // remove the 'template' keyword.
1610 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1611 "Expected a definition here");
1613 if (TUK == Sema::TUK_Friend) {
1614 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1615 TemplateParams = nullptr;
1617 SourceLocation LAngleLoc =
1618 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1619 Diag(TemplateId->TemplateNameLoc,
1620 diag::err_explicit_instantiation_with_definition)
1621 << SourceRange(TemplateInfo.TemplateLoc)
1622 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1624 // Create a fake template parameter list that contains only
1625 // "template<>", so that we treat this construct as a class
1626 // template specialization.
1627 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1628 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
1630 TemplateParams = &FakedParamLists;
1634 // Build the class template specialization.
1635 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1636 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1637 *TemplateId, attrs.getList(),
1638 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1640 TemplateParams ? TemplateParams->size() : 0),
1643 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1644 TUK == Sema::TUK_Declaration) {
1645 // Explicit instantiation of a member of a class template
1646 // specialization, e.g.,
1648 // template struct Outer<int>::Inner;
1650 ProhibitAttributes(attrs);
1653 = Actions.ActOnExplicitInstantiation(getCurScope(),
1654 TemplateInfo.ExternLoc,
1655 TemplateInfo.TemplateLoc,
1656 TagType, StartLoc, SS, Name,
1657 NameLoc, attrs.getList());
1658 } else if (TUK == Sema::TUK_Friend &&
1659 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1660 ProhibitAttributes(attrs);
1663 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1664 TagType, StartLoc, SS,
1665 Name, NameLoc, attrs.getList(),
1666 MultiTemplateParamsArg(
1667 TemplateParams? &(*TemplateParams)[0]
1669 TemplateParams? TemplateParams->size() : 0));
1671 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1672 ProhibitAttributes(attrs);
1674 if (TUK == Sema::TUK_Definition &&
1675 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1676 // If the declarator-id is not a template-id, issue a diagnostic and
1677 // recover by ignoring the 'template' keyword.
1678 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1679 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1680 TemplateParams = nullptr;
1683 bool IsDependent = false;
1685 // Don't pass down template parameter lists if this is just a tag
1686 // reference. For example, we don't need the template parameters here:
1687 // template <class T> class A *makeA(T t);
1688 MultiTemplateParamsArg TParams;
1689 if (TUK != Sema::TUK_Reference && TemplateParams)
1691 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1693 handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
1695 // Declaration or definition of a class type
1696 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1697 SS, Name, NameLoc, attrs.getList(), AS,
1698 DS.getModulePrivateSpecLoc(),
1699 TParams, Owned, IsDependent,
1700 SourceLocation(), false,
1701 clang::TypeResult(),
1702 DSC == DSC_type_specifier,
1705 // If ActOnTag said the type was dependent, try again with the
1706 // less common call.
1708 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1709 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1710 SS, Name, StartLoc, NameLoc);
1714 // If there is a body, parse it and inform the actions module.
1715 if (TUK == Sema::TUK_Definition) {
1716 assert(Tok.is(tok::l_brace) ||
1717 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1718 isCXX11FinalKeyword());
1719 if (SkipBody.ShouldSkip)
1720 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1721 TagOrTempResult.get());
1722 else if (getLangOpts().CPlusPlus)
1723 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1724 TagOrTempResult.get());
1726 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1729 const char *PrevSpec = nullptr;
1732 if (!TypeResult.isInvalid()) {
1733 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1734 NameLoc.isValid() ? NameLoc : StartLoc,
1735 PrevSpec, DiagID, TypeResult.get(), Policy);
1736 } else if (!TagOrTempResult.isInvalid()) {
1737 Result = DS.SetTypeSpecType(TagType, StartLoc,
1738 NameLoc.isValid() ? NameLoc : StartLoc,
1739 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1742 DS.SetTypeSpecError();
1747 Diag(StartLoc, DiagID) << PrevSpec;
1749 // At this point, we've successfully parsed a class-specifier in 'definition'
1750 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1751 // going to look at what comes after it to improve error recovery. If an
1752 // impossible token occurs next, we assume that the programmer forgot a ; at
1753 // the end of the declaration and recover that way.
1755 // Also enforce C++ [temp]p3:
1756 // In a template-declaration which defines a class, no declarator
1759 // After a type-specifier, we don't expect a semicolon. This only happens in
1760 // C, since definitions are not permitted in this context in C++.
1761 if (TUK == Sema::TUK_Definition &&
1762 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1763 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1764 if (Tok.isNot(tok::semi)) {
1765 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1766 ExpectAndConsume(tok::semi, diag::err_expected_after,
1767 DeclSpec::getSpecifierName(TagType, PPol));
1768 // Push this token back into the preprocessor and change our current token
1769 // to ';' so that the rest of the code recovers as though there were an
1770 // ';' after the definition.
1772 Tok.setKind(tok::semi);
1777 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1779 /// base-clause : [C++ class.derived]
1780 /// ':' base-specifier-list
1781 /// base-specifier-list:
1782 /// base-specifier '...'[opt]
1783 /// base-specifier-list ',' base-specifier '...'[opt]
1784 void Parser::ParseBaseClause(Decl *ClassDecl) {
1785 assert(Tok.is(tok::colon) && "Not a base clause");
1788 // Build up an array of parsed base specifiers.
1789 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1792 // Parse a base-specifier.
1793 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1794 if (Result.isInvalid()) {
1795 // Skip the rest of this base specifier, up until the comma or
1797 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
1799 // Add this to our array of base specifiers.
1800 BaseInfo.push_back(Result.get());
1803 // If the next token is a comma, consume it and keep reading
1805 if (!TryConsumeToken(tok::comma))
1809 // Attach the base specifiers
1810 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1813 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1814 /// one entry in the base class list of a class specifier, for example:
1815 /// class foo : public bar, virtual private baz {
1816 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1818 /// base-specifier: [C++ class.derived]
1819 /// attribute-specifier-seq[opt] base-type-specifier
1820 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
1821 /// base-type-specifier
1822 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
1823 /// base-type-specifier
1824 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1825 bool IsVirtual = false;
1826 SourceLocation StartLoc = Tok.getLocation();
1828 ParsedAttributesWithRange Attributes(AttrFactory);
1829 MaybeParseCXX11Attributes(Attributes);
1831 // Parse the 'virtual' keyword.
1832 if (TryConsumeToken(tok::kw_virtual))
1835 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1837 // Parse an (optional) access specifier.
1838 AccessSpecifier Access = getAccessSpecifierIfPresent();
1839 if (Access != AS_none)
1842 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1844 // Parse the 'virtual' keyword (again!), in case it came after the
1845 // access specifier.
1846 if (Tok.is(tok::kw_virtual)) {
1847 SourceLocation VirtualLoc = ConsumeToken();
1849 // Complain about duplicate 'virtual'
1850 Diag(VirtualLoc, diag::err_dup_virtual)
1851 << FixItHint::CreateRemoval(VirtualLoc);
1857 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1859 // Parse the class-name.
1860 SourceLocation EndLocation;
1861 SourceLocation BaseLoc;
1862 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1863 if (BaseType.isInvalid())
1866 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1867 // actually part of the base-specifier-list grammar productions, but we
1868 // parse it here for convenience.
1869 SourceLocation EllipsisLoc;
1870 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1872 // Find the complete source range for the base-specifier.
1873 SourceRange Range(StartLoc, EndLocation);
1875 // Notify semantic analysis that we have parsed a complete
1877 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
1878 Access, BaseType.get(), BaseLoc,
1882 /// getAccessSpecifierIfPresent - Determine whether the next token is
1883 /// a C++ access-specifier.
1885 /// access-specifier: [C++ class.derived]
1889 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1890 switch (Tok.getKind()) {
1891 default: return AS_none;
1892 case tok::kw_private: return AS_private;
1893 case tok::kw_protected: return AS_protected;
1894 case tok::kw_public: return AS_public;
1898 /// \brief If the given declarator has any parts for which parsing has to be
1899 /// delayed, e.g., default arguments or an exception-specification, create a
1900 /// late-parsed method declaration record to handle the parsing at the end of
1901 /// the class definition.
1902 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1904 DeclaratorChunk::FunctionTypeInfo &FTI
1905 = DeclaratorInfo.getFunctionTypeInfo();
1906 // If there was a late-parsed exception-specification, we'll need a
1908 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
1910 if (!NeedLateParse) {
1911 // Look ahead to see if there are any default args
1912 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
1913 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
1914 if (Param->hasUnparsedDefaultArg()) {
1915 NeedLateParse = true;
1921 if (NeedLateParse) {
1922 // Push this method onto the stack of late-parsed method
1924 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1925 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1926 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1928 // Stash the exception-specification tokens in the late-pased method.
1929 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
1930 FTI.ExceptionSpecTokens = 0;
1932 // Push tokens for each parameter. Those that do not have
1933 // defaults will be NULL.
1934 LateMethod->DefaultArgs.reserve(FTI.NumParams);
1935 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
1936 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
1937 FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
1941 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
1947 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
1948 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
1949 return VirtSpecifiers::VS_None;
1951 IdentifierInfo *II = Tok.getIdentifierInfo();
1953 // Initialize the contextual keywords.
1955 Ident_final = &PP.getIdentifierTable().get("final");
1956 if (getLangOpts().MicrosoftExt)
1957 Ident_sealed = &PP.getIdentifierTable().get("sealed");
1958 Ident_override = &PP.getIdentifierTable().get("override");
1961 if (II == Ident_override)
1962 return VirtSpecifiers::VS_Override;
1964 if (II == Ident_sealed)
1965 return VirtSpecifiers::VS_Sealed;
1967 if (II == Ident_final)
1968 return VirtSpecifiers::VS_Final;
1970 return VirtSpecifiers::VS_None;
1973 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
1975 /// virt-specifier-seq:
1977 /// virt-specifier-seq virt-specifier
1978 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
1980 SourceLocation FriendLoc) {
1982 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
1983 if (Specifier == VirtSpecifiers::VS_None)
1986 if (FriendLoc.isValid()) {
1987 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
1988 << VirtSpecifiers::getSpecifierName(Specifier)
1989 << FixItHint::CreateRemoval(Tok.getLocation())
1990 << SourceRange(FriendLoc, FriendLoc);
1995 // C++ [class.mem]p8:
1996 // A virt-specifier-seq shall contain at most one of each virt-specifier.
1997 const char *PrevSpec = nullptr;
1998 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
1999 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2001 << FixItHint::CreateRemoval(Tok.getLocation());
2003 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2004 Specifier == VirtSpecifiers::VS_Sealed)) {
2005 Diag(Tok.getLocation(), diag::err_override_control_interface)
2006 << VirtSpecifiers::getSpecifierName(Specifier);
2007 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2008 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2010 Diag(Tok.getLocation(),
2011 getLangOpts().CPlusPlus11
2012 ? diag::warn_cxx98_compat_override_control_keyword
2013 : diag::ext_override_control_keyword)
2014 << VirtSpecifiers::getSpecifierName(Specifier);
2020 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2021 /// 'final' or Microsoft 'sealed' contextual keyword.
2022 bool Parser::isCXX11FinalKeyword() const {
2023 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2024 return Specifier == VirtSpecifiers::VS_Final ||
2025 Specifier == VirtSpecifiers::VS_Sealed;
2028 /// \brief Parse a C++ member-declarator up to, but not including, the optional
2029 /// brace-or-equal-initializer or pure-specifier.
2030 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2031 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2032 LateParsedAttrList &LateParsedAttrs) {
2033 // member-declarator:
2034 // declarator pure-specifier[opt]
2035 // declarator brace-or-equal-initializer[opt]
2036 // identifier[opt] ':' constant-expression
2037 if (Tok.isNot(tok::colon))
2038 ParseDeclarator(DeclaratorInfo);
2040 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2042 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2043 assert(DeclaratorInfo.isPastIdentifier() &&
2044 "don't know where identifier would go yet?");
2045 BitfieldSize = ParseConstantExpression();
2046 if (BitfieldSize.isInvalid())
2047 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2049 ParseOptionalCXX11VirtSpecifierSeq(
2050 VS, getCurrentClass().IsInterface,
2051 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2053 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2056 // If a simple-asm-expr is present, parse it.
2057 if (Tok.is(tok::kw_asm)) {
2059 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2060 if (AsmLabel.isInvalid())
2061 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2063 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2064 DeclaratorInfo.SetRangeEnd(Loc);
2067 // If attributes exist after the declarator, but before an '{', parse them.
2068 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2070 // For compatibility with code written to older Clang, also accept a
2071 // virt-specifier *after* the GNU attributes.
2072 if (BitfieldSize.isUnset() && VS.isUnset()) {
2073 ParseOptionalCXX11VirtSpecifierSeq(
2074 VS, getCurrentClass().IsInterface,
2075 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2076 if (!VS.isUnset()) {
2077 // If we saw any GNU-style attributes that are known to GCC followed by a
2078 // virt-specifier, issue a GCC-compat warning.
2079 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2081 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2082 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2083 Attr = Attr->getNext();
2085 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2089 // If this has neither a name nor a bit width, something has gone seriously
2090 // wrong. Skip until the semi-colon or }.
2091 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2092 // If so, skip until the semi-colon or a }.
2093 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2099 /// \brief Look for declaration specifiers possibly occurring after C++11
2100 /// virt-specifier-seq and diagnose them.
2101 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2103 VirtSpecifiers &VS) {
2104 DeclSpec DS(AttrFactory);
2106 // GNU-style and C++11 attributes are not allowed here, but they will be
2107 // handled by the caller. Diagnose everything else.
2108 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, false);
2109 D.ExtendWithDeclSpec(DS);
2111 if (D.isFunctionDeclarator()) {
2112 auto &Function = D.getFunctionTypeInfo();
2113 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2114 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2115 const char *FixItName,
2116 SourceLocation SpecLoc,
2117 unsigned* QualifierLoc) {
2118 FixItHint Insertion;
2119 if (DS.getTypeQualifiers() & TypeQual) {
2120 if (!(Function.TypeQuals & TypeQual)) {
2121 std::string Name(FixItName);
2123 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name.c_str());
2124 Function.TypeQuals |= TypeQual;
2125 *QualifierLoc = SpecLoc.getRawEncoding();
2127 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2129 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2130 << FixItHint::CreateRemoval(SpecLoc)
2134 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2135 &Function.ConstQualifierLoc);
2136 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2137 &Function.VolatileQualifierLoc);
2138 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2139 &Function.RestrictQualifierLoc);
2142 // Parse ref-qualifiers.
2143 bool RefQualifierIsLValueRef = true;
2144 SourceLocation RefQualifierLoc;
2145 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2146 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2147 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2148 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2149 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2151 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2152 << (RefQualifierIsLValueRef ? "&" : "&&")
2153 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2154 << FixItHint::CreateRemoval(RefQualifierLoc)
2156 D.SetRangeEnd(RefQualifierLoc);
2161 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2163 /// member-declaration:
2164 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2165 /// function-definition ';'[opt]
2166 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2167 /// using-declaration [TODO]
2168 /// [C++0x] static_assert-declaration
2169 /// template-declaration
2170 /// [GNU] '__extension__' member-declaration
2172 /// member-declarator-list:
2173 /// member-declarator
2174 /// member-declarator-list ',' member-declarator
2176 /// member-declarator:
2177 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2178 /// declarator constant-initializer[opt]
2179 /// [C++11] declarator brace-or-equal-initializer[opt]
2180 /// identifier[opt] ':' constant-expression
2182 /// virt-specifier-seq:
2184 /// virt-specifier-seq virt-specifier
2194 /// constant-initializer:
2195 /// '=' constant-expression
2197 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2198 AttributeList *AccessAttrs,
2199 const ParsedTemplateInfo &TemplateInfo,
2200 ParsingDeclRAIIObject *TemplateDiags) {
2201 if (Tok.is(tok::at)) {
2202 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2203 Diag(Tok, diag::err_at_defs_cxx);
2205 Diag(Tok, diag::err_at_in_class);
2208 SkipUntil(tok::r_brace, StopAtSemi);
2212 // Turn on colon protection early, while parsing declspec, although there is
2213 // nothing to protect there. It prevents from false errors if error recovery
2214 // incorrectly determines where the declspec ends, as in the example:
2215 // struct A { enum class B { C }; };
2217 // struct D { A::B : C; };
2218 ColonProtectionRAIIObject X(*this);
2220 // Access declarations.
2221 bool MalformedTypeSpec = false;
2222 if (!TemplateInfo.Kind &&
2223 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2224 if (TryAnnotateCXXScopeToken())
2225 MalformedTypeSpec = true;
2228 if (Tok.isNot(tok::annot_cxxscope))
2229 isAccessDecl = false;
2230 else if (NextToken().is(tok::identifier))
2231 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2233 isAccessDecl = NextToken().is(tok::kw_operator);
2236 // Collect the scope specifier token we annotated earlier.
2238 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
2239 /*EnteringContext=*/false);
2241 if (SS.isInvalid()) {
2242 SkipUntil(tok::semi);
2246 // Try to parse an unqualified-id.
2247 SourceLocation TemplateKWLoc;
2249 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
2250 TemplateKWLoc, Name)) {
2251 SkipUntil(tok::semi);
2255 // TODO: recover from mistakenly-qualified operator declarations.
2256 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2257 "access declaration")) {
2258 SkipUntil(tok::semi);
2262 Actions.ActOnUsingDeclaration(getCurScope(), AS,
2263 /* HasUsingKeyword */ false,
2266 /* AttrList */ nullptr,
2267 /* HasTypenameKeyword */ false,
2273 // static_assert-declaration. A templated static_assert declaration is
2274 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2275 if (!TemplateInfo.Kind &&
2276 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2277 SourceLocation DeclEnd;
2278 ParseStaticAssertDeclaration(DeclEnd);
2282 if (Tok.is(tok::kw_template)) {
2283 assert(!TemplateInfo.TemplateParams &&
2284 "Nested template improperly parsed?");
2285 SourceLocation DeclEnd;
2286 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
2291 // Handle: member-declaration ::= '__extension__' member-declaration
2292 if (Tok.is(tok::kw___extension__)) {
2293 // __extension__ silences extension warnings in the subexpression.
2294 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2296 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2297 TemplateInfo, TemplateDiags);
2300 ParsedAttributesWithRange attrs(AttrFactory);
2301 ParsedAttributesWithRange FnAttrs(AttrFactory);
2302 // Optional C++11 attribute-specifier
2303 MaybeParseCXX11Attributes(attrs);
2304 // We need to keep these attributes for future diagnostic
2305 // before they are taken over by declaration specifier.
2306 FnAttrs.addAll(attrs.getList());
2307 FnAttrs.Range = attrs.Range;
2309 MaybeParseMicrosoftAttributes(attrs);
2311 if (Tok.is(tok::kw_using)) {
2312 ProhibitAttributes(attrs);
2315 SourceLocation UsingLoc = ConsumeToken();
2317 if (Tok.is(tok::kw_namespace)) {
2318 Diag(UsingLoc, diag::err_using_namespace_in_class);
2319 SkipUntil(tok::semi, StopBeforeMatch);
2321 SourceLocation DeclEnd;
2322 // Otherwise, it must be a using-declaration or an alias-declaration.
2323 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2324 UsingLoc, DeclEnd, AS);
2329 // Hold late-parsed attributes so we can attach a Decl to them later.
2330 LateParsedAttrList CommonLateParsedAttrs;
2332 // decl-specifier-seq:
2333 // Parse the common declaration-specifiers piece.
2334 ParsingDeclSpec DS(*this, TemplateDiags);
2335 DS.takeAttributesFrom(attrs);
2336 if (MalformedTypeSpec)
2337 DS.SetTypeSpecError();
2339 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2340 &CommonLateParsedAttrs);
2342 // Turn off colon protection that was set for declspec.
2345 // If we had a free-standing type definition with a missing semicolon, we
2346 // may get this far before the problem becomes obvious.
2347 if (DS.hasTagDefinition() &&
2348 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2349 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2350 &CommonLateParsedAttrs))
2353 MultiTemplateParamsArg TemplateParams(
2354 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2356 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2358 if (TryConsumeToken(tok::semi)) {
2359 if (DS.isFriendSpecified())
2360 ProhibitAttributes(FnAttrs);
2363 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
2364 DS.complete(TheDecl);
2368 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2371 // Hold late-parsed attributes so we can attach a Decl to them later.
2372 LateParsedAttrList LateParsedAttrs;
2374 SourceLocation EqualLoc;
2375 bool HasInitializer = false;
2378 SmallVector<Decl *, 8> DeclsInGroup;
2379 ExprResult BitfieldSize;
2380 bool ExpectSemi = true;
2382 // Parse the first declarator.
2383 if (ParseCXXMemberDeclaratorBeforeInitializer(
2384 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2385 TryConsumeToken(tok::semi);
2389 // Check for a member function definition.
2390 if (BitfieldSize.isUnset()) {
2391 // MSVC permits pure specifier on inline functions defined at class scope.
2392 // Hence check for =0 before checking for function definition.
2393 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
2394 DeclaratorInfo.isFunctionDeclarator() &&
2395 NextToken().is(tok::numeric_constant)) {
2396 EqualLoc = ConsumeToken();
2397 Init = ParseInitializer();
2398 if (Init.isInvalid())
2399 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2401 HasInitializer = true;
2404 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2405 // function-definition:
2407 // In C++11, a non-function declarator followed by an open brace is a
2408 // braced-init-list for an in-class member initialization, not an
2409 // erroneous function definition.
2410 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2411 DefinitionKind = FDK_Definition;
2412 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2413 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2414 DefinitionKind = FDK_Definition;
2415 } else if (Tok.is(tok::equal)) {
2416 const Token &KW = NextToken();
2417 if (KW.is(tok::kw_default))
2418 DefinitionKind = FDK_Defaulted;
2419 else if (KW.is(tok::kw_delete))
2420 DefinitionKind = FDK_Deleted;
2423 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2425 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2426 // to a friend declaration, that declaration shall be a definition.
2427 if (DeclaratorInfo.isFunctionDeclarator() &&
2428 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2429 // Diagnose attributes that appear before decl specifier:
2430 // [[]] friend int foo();
2431 ProhibitAttributes(FnAttrs);
2434 if (DefinitionKind != FDK_Declaration) {
2435 if (!DeclaratorInfo.isFunctionDeclarator()) {
2436 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2438 SkipUntil(tok::r_brace);
2440 // Consume the optional ';'
2441 TryConsumeToken(tok::semi);
2446 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2447 Diag(DeclaratorInfo.getIdentifierLoc(),
2448 diag::err_function_declared_typedef);
2450 // Recover by treating the 'typedef' as spurious.
2451 DS.ClearStorageClassSpecs();
2455 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2459 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2460 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2462 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2463 LateParsedAttrs[i]->addDecl(FunDecl);
2466 LateParsedAttrs.clear();
2468 // Consume the ';' - it's optional unless we have a delete or default
2469 if (Tok.is(tok::semi))
2470 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2476 // member-declarator-list:
2477 // member-declarator
2478 // member-declarator-list ',' member-declarator
2481 InClassInitStyle HasInClassInit = ICIS_NoInit;
2482 if (Tok.isOneOf(tok::equal, tok::l_brace) && !HasInitializer) {
2483 if (BitfieldSize.get()) {
2484 Diag(Tok, diag::err_bitfield_member_init);
2485 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2487 HasInitializer = true;
2488 if (!DeclaratorInfo.isDeclarationOfFunction() &&
2489 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2490 != DeclSpec::SCS_typedef)
2491 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2495 // NOTE: If Sema is the Action module and declarator is an instance field,
2496 // this call will *not* return the created decl; It will return null.
2497 // See Sema::ActOnCXXMemberDeclarator for details.
2499 NamedDecl *ThisDecl = nullptr;
2500 if (DS.isFriendSpecified()) {
2501 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2502 // to a friend declaration, that declaration shall be a definition.
2504 // Diagnose attributes that appear in a friend member function declarator:
2505 // friend int foo [[]] ();
2506 SmallVector<SourceRange, 4> Ranges;
2507 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2508 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2509 E = Ranges.end(); I != E; ++I)
2510 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2512 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2515 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2519 VS, HasInClassInit);
2521 if (VarTemplateDecl *VT =
2522 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2523 // Re-direct this decl to refer to the templated decl so that we can
2525 ThisDecl = VT->getTemplatedDecl();
2527 if (ThisDecl && AccessAttrs)
2528 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2531 // Handle the initializer.
2532 if (HasInClassInit != ICIS_NoInit &&
2533 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2534 DeclSpec::SCS_static) {
2535 // The initializer was deferred; parse it and cache the tokens.
2536 Diag(Tok, getLangOpts().CPlusPlus11
2537 ? diag::warn_cxx98_compat_nonstatic_member_init
2538 : diag::ext_nonstatic_member_init);
2540 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2541 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2542 // declarator is followed by an initializer.
2544 // A brace-or-equal-initializer for a member-declarator is not an
2545 // initializer in the grammar, so this is ill-formed.
2546 Diag(Tok, diag::err_incomplete_array_member_init);
2547 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2549 // Avoid later warnings about a class member of incomplete type.
2551 ThisDecl->setInvalidDecl();
2553 ParseCXXNonStaticMemberInitializer(ThisDecl);
2554 } else if (HasInitializer) {
2555 // Normal initializer.
2556 if (!Init.isUsable())
2557 Init = ParseCXXMemberInitializer(
2558 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2560 if (Init.isInvalid())
2561 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2563 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2564 DS.containsPlaceholderType());
2565 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2567 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
2570 if (!ThisDecl->isInvalidDecl()) {
2571 // Set the Decl for any late parsed attributes
2572 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2573 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2575 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2576 LateParsedAttrs[i]->addDecl(ThisDecl);
2578 Actions.FinalizeDeclaration(ThisDecl);
2579 DeclsInGroup.push_back(ThisDecl);
2581 if (DeclaratorInfo.isFunctionDeclarator() &&
2582 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2583 DeclSpec::SCS_typedef)
2584 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2586 LateParsedAttrs.clear();
2588 DeclaratorInfo.complete(ThisDecl);
2590 // If we don't have a comma, it is either the end of the list (a ';')
2591 // or an error, bail out.
2592 SourceLocation CommaLoc;
2593 if (!TryConsumeToken(tok::comma, CommaLoc))
2596 if (Tok.isAtStartOfLine() &&
2597 !MightBeDeclarator(Declarator::MemberContext)) {
2598 // This comma was followed by a line-break and something which can't be
2599 // the start of a declarator. The comma was probably a typo for a
2601 Diag(CommaLoc, diag::err_expected_semi_declaration)
2602 << FixItHint::CreateReplacement(CommaLoc, ";");
2607 // Parse the next declarator.
2608 DeclaratorInfo.clear();
2610 BitfieldSize = ExprResult(/*Invalid=*/false);
2611 Init = ExprResult(/*Invalid=*/false);
2612 HasInitializer = false;
2613 DeclaratorInfo.setCommaLoc(CommaLoc);
2615 // GNU attributes are allowed before the second and subsequent declarator.
2616 MaybeParseGNUAttributes(DeclaratorInfo);
2618 if (ParseCXXMemberDeclaratorBeforeInitializer(
2619 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2624 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2625 // Skip to end of block or statement.
2626 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2627 // If we stopped at a ';', eat it.
2628 TryConsumeToken(tok::semi);
2632 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2635 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
2636 /// pure-specifier. Also detect and reject any attempted defaulted/deleted
2637 /// function definition. The location of the '=', if any, will be placed in
2643 /// brace-or-equal-initializer:
2644 /// '=' initializer-expression
2645 /// braced-init-list
2647 /// initializer-clause:
2648 /// assignment-expression
2649 /// braced-init-list
2651 /// defaulted/deleted function-definition:
2655 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2656 /// be a constant-expression.
2657 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2658 SourceLocation &EqualLoc) {
2659 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2660 && "Data member initializer not starting with '=' or '{'");
2662 EnterExpressionEvaluationContext Context(Actions,
2663 Sema::PotentiallyEvaluated,
2665 if (TryConsumeToken(tok::equal, EqualLoc)) {
2666 if (Tok.is(tok::kw_delete)) {
2667 // In principle, an initializer of '= delete p;' is legal, but it will
2668 // never type-check. It's better to diagnose it as an ill-formed expression
2669 // than as an ill-formed deleted non-function member.
2670 // An initializer of '= delete p, foo' will never be parsed, because
2671 // a top-level comma always ends the initializer expression.
2672 const Token &Next = NextToken();
2673 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2675 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2678 Diag(ConsumeToken(), diag::err_deleted_non_function);
2681 } else if (Tok.is(tok::kw_default)) {
2683 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2686 Diag(ConsumeToken(), diag::err_default_special_members);
2690 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2691 Diag(Tok, diag::err_ms_property_initializer) << PD;
2694 return ParseInitializer();
2697 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2698 SourceLocation AttrFixitLoc,
2699 unsigned TagType, Decl *TagDecl) {
2700 // Skip the optional 'final' keyword.
2701 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2702 assert(isCXX11FinalKeyword() && "not a class definition");
2705 // Diagnose any C++11 attributes after 'final' keyword.
2706 // We deliberately discard these attributes.
2707 ParsedAttributesWithRange Attrs(AttrFactory);
2708 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2710 // This can only happen if we had malformed misplaced attributes;
2711 // we only get called if there is a colon or left-brace after the
2713 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2717 // Skip the base clauses. This requires actually parsing them, because
2718 // otherwise we can't be sure where they end (a left brace may appear
2719 // within a template argument).
2720 if (Tok.is(tok::colon)) {
2721 // Enter the scope of the class so that we can correctly parse its bases.
2722 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2723 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2724 TagType == DeclSpec::TST_interface);
2726 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2728 // Parse the bases but don't attach them to the class.
2729 ParseBaseClause(nullptr);
2731 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2733 if (!Tok.is(tok::l_brace)) {
2734 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2735 diag::err_expected_lbrace_after_base_specifiers);
2741 assert(Tok.is(tok::l_brace));
2742 BalancedDelimiterTracker T(*this, tok::l_brace);
2747 /// ParseCXXMemberSpecification - Parse the class definition.
2749 /// member-specification:
2750 /// member-declaration member-specification[opt]
2751 /// access-specifier ':' member-specification[opt]
2753 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2754 SourceLocation AttrFixitLoc,
2755 ParsedAttributesWithRange &Attrs,
2756 unsigned TagType, Decl *TagDecl) {
2757 assert((TagType == DeclSpec::TST_struct ||
2758 TagType == DeclSpec::TST_interface ||
2759 TagType == DeclSpec::TST_union ||
2760 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2762 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2763 "parsing struct/union/class body");
2765 // Determine whether this is a non-nested class. Note that local
2766 // classes are *not* considered to be nested classes.
2767 bool NonNestedClass = true;
2768 if (!ClassStack.empty()) {
2769 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2770 if (S->isClassScope()) {
2771 // We're inside a class scope, so this is a nested class.
2772 NonNestedClass = false;
2774 // The Microsoft extension __interface does not permit nested classes.
2775 if (getCurrentClass().IsInterface) {
2776 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2778 << (isa<NamedDecl>(TagDecl)
2779 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2785 if ((S->getFlags() & Scope::FnScope)) {
2786 // If we're in a function or function template declared in the
2787 // body of a class, then this is a local class rather than a
2789 const Scope *Parent = S->getParent();
2790 if (Parent->isTemplateParamScope())
2791 Parent = Parent->getParent();
2792 if (Parent->isClassScope())
2798 // Enter a scope for the class.
2799 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2801 // Note that we are parsing a new (potentially-nested) class definition.
2802 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2803 TagType == DeclSpec::TST_interface);
2806 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2808 SourceLocation FinalLoc;
2809 bool IsFinalSpelledSealed = false;
2811 // Parse the optional 'final' keyword.
2812 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2813 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2814 assert((Specifier == VirtSpecifiers::VS_Final ||
2815 Specifier == VirtSpecifiers::VS_Sealed) &&
2816 "not a class definition");
2817 FinalLoc = ConsumeToken();
2818 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
2820 if (TagType == DeclSpec::TST_interface)
2821 Diag(FinalLoc, diag::err_override_control_interface)
2822 << VirtSpecifiers::getSpecifierName(Specifier);
2823 else if (Specifier == VirtSpecifiers::VS_Final)
2824 Diag(FinalLoc, getLangOpts().CPlusPlus11
2825 ? diag::warn_cxx98_compat_override_control_keyword
2826 : diag::ext_override_control_keyword)
2827 << VirtSpecifiers::getSpecifierName(Specifier);
2828 else if (Specifier == VirtSpecifiers::VS_Sealed)
2829 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
2831 // Parse any C++11 attributes after 'final' keyword.
2832 // These attributes are not allowed to appear here,
2833 // and the only possible place for them to appertain
2834 // to the class would be between class-key and class-name.
2835 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2837 // ParseClassSpecifier() does only a superficial check for attributes before
2838 // deciding to call this method. For example, for
2839 // `class C final alignas ([l) {` it will decide that this looks like a
2840 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
2841 // attribute parsing code will try to parse the '[' as a constexpr lambda
2842 // and consume enough tokens that the alignas parsing code will eat the
2843 // opening '{'. So bail out if the next token isn't one we expect.
2844 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
2846 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2851 if (Tok.is(tok::colon)) {
2852 ParseBaseClause(TagDecl);
2853 if (!Tok.is(tok::l_brace)) {
2854 bool SuggestFixIt = false;
2855 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
2856 if (Tok.isAtStartOfLine()) {
2857 switch (Tok.getKind()) {
2858 case tok::kw_private:
2859 case tok::kw_protected:
2860 case tok::kw_public:
2861 SuggestFixIt = NextToken().getKind() == tok::colon;
2863 case tok::kw_static_assert:
2866 // base-clause can have simple-template-id; 'template' can't be there
2867 case tok::kw_template:
2868 SuggestFixIt = true;
2870 case tok::identifier:
2871 SuggestFixIt = isConstructorDeclarator(true);
2874 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
2878 DiagnosticBuilder LBraceDiag =
2879 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
2881 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
2882 // Try recovering from missing { after base-clause.
2884 Tok.setKind(tok::l_brace);
2887 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2893 assert(Tok.is(tok::l_brace));
2894 BalancedDelimiterTracker T(*this, tok::l_brace);
2898 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2899 IsFinalSpelledSealed,
2900 T.getOpenLocation());
2902 // C++ 11p3: Members of a class defined with the keyword class are private
2903 // by default. Members of a class defined with the keywords struct or union
2904 // are public by default.
2905 AccessSpecifier CurAS;
2906 if (TagType == DeclSpec::TST_class)
2910 ParsedAttributes AccessAttrs(AttrFactory);
2913 // While we still have something to read, read the member-declarations.
2914 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2915 // Each iteration of this loop reads one member-declaration.
2917 if (getLangOpts().MicrosoftExt && Tok.isOneOf(tok::kw___if_exists,
2918 tok::kw___if_not_exists)) {
2919 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2923 // Check for extraneous top-level semicolon.
2924 if (Tok.is(tok::semi)) {
2925 ConsumeExtraSemi(InsideStruct, TagType);
2929 if (Tok.is(tok::annot_pragma_vis)) {
2930 HandlePragmaVisibility();
2934 if (Tok.is(tok::annot_pragma_pack)) {
2939 if (Tok.is(tok::annot_pragma_align)) {
2940 HandlePragmaAlign();
2944 if (Tok.is(tok::annot_pragma_openmp)) {
2945 ParseOpenMPDeclarativeDirective();
2949 if (Tok.is(tok::annot_pragma_ms_pointers_to_members)) {
2950 HandlePragmaMSPointersToMembers();
2954 if (Tok.is(tok::annot_pragma_ms_pragma)) {
2955 HandlePragmaMSPragma();
2959 // If we see a namespace here, a close brace was missing somewhere.
2960 if (Tok.is(tok::kw_namespace)) {
2961 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
2965 AccessSpecifier AS = getAccessSpecifierIfPresent();
2966 if (AS != AS_none) {
2967 // Current token is a C++ access specifier.
2969 SourceLocation ASLoc = Tok.getLocation();
2970 unsigned TokLength = Tok.getLength();
2972 AccessAttrs.clear();
2973 MaybeParseGNUAttributes(AccessAttrs);
2975 SourceLocation EndLoc;
2976 if (TryConsumeToken(tok::colon, EndLoc)) {
2977 } else if (TryConsumeToken(tok::semi, EndLoc)) {
2978 Diag(EndLoc, diag::err_expected)
2979 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
2981 EndLoc = ASLoc.getLocWithOffset(TokLength);
2982 Diag(EndLoc, diag::err_expected)
2983 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
2986 // The Microsoft extension __interface does not permit non-public
2987 // access specifiers.
2988 if (TagType == DeclSpec::TST_interface && CurAS != AS_public) {
2989 Diag(ASLoc, diag::err_access_specifier_interface)
2990 << (CurAS == AS_protected);
2993 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
2994 AccessAttrs.getList())) {
2995 // found another attribute than only annotations
2996 AccessAttrs.clear();
3002 // Parse all the comma separated declarators.
3003 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
3008 SkipUntil(tok::r_brace);
3011 // If attributes exist after class contents, parse them.
3012 ParsedAttributes attrs(AttrFactory);
3013 MaybeParseGNUAttributes(attrs);
3016 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3017 T.getOpenLocation(),
3018 T.getCloseLocation(),
3021 // C++11 [class.mem]p2:
3022 // Within the class member-specification, the class is regarded as complete
3023 // within function bodies, default arguments, exception-specifications, and
3024 // brace-or-equal-initializers for non-static data members (including such
3025 // things in nested classes).
3026 if (TagDecl && NonNestedClass) {
3027 // We are not inside a nested class. This class and its nested classes
3028 // are complete and we can parse the delayed portions of method
3029 // declarations and the lexed inline method definitions, along with any
3030 // delayed attributes.
3031 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3032 ParseLexedAttributes(getCurrentClass());
3033 ParseLexedMethodDeclarations(getCurrentClass());
3035 // We've finished with all pending member declarations.
3036 Actions.ActOnFinishCXXMemberDecls();
3038 ParseLexedMemberInitializers(getCurrentClass());
3039 ParseLexedMethodDefs(getCurrentClass());
3040 PrevTokLocation = SavedPrevTokLocation;
3042 // We've finished parsing everything, including default argument
3044 Actions.ActOnFinishCXXMemberDefaultArgs(TagDecl);
3048 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3049 T.getCloseLocation());
3051 // Leave the class scope.
3056 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3057 assert(Tok.is(tok::kw_namespace));
3059 // FIXME: Suggest where the close brace should have gone by looking
3060 // at indentation changes within the definition body.
3061 Diag(D->getLocation(),
3062 diag::err_missing_end_of_definition) << D;
3063 Diag(Tok.getLocation(),
3064 diag::note_missing_end_of_definition_before) << D;
3066 // Push '};' onto the token stream to recover.
3070 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3071 Tok.setKind(tok::semi);
3074 Tok.setKind(tok::r_brace);
3077 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3078 /// which explicitly initializes the members or base classes of a
3079 /// class (C++ [class.base.init]). For example, the three initializers
3080 /// after the ':' in the Derived constructor below:
3084 /// class Derived : Base {
3088 /// Derived(float f) : Base(), x(17), f(f) { }
3092 /// [C++] ctor-initializer:
3093 /// ':' mem-initializer-list
3095 /// [C++] mem-initializer-list:
3096 /// mem-initializer ...[opt]
3097 /// mem-initializer ...[opt] , mem-initializer-list
3098 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3099 assert(Tok.is(tok::colon) &&
3100 "Constructor initializer always starts with ':'");
3102 // Poison the SEH identifiers so they are flagged as illegal in constructor
3104 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3105 SourceLocation ColonLoc = ConsumeToken();
3107 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3108 bool AnyErrors = false;
3111 if (Tok.is(tok::code_completion)) {
3112 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3114 return cutOffParsing();
3116 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3117 if (!MemInit.isInvalid())
3118 MemInitializers.push_back(MemInit.get());
3123 if (Tok.is(tok::comma))
3125 else if (Tok.is(tok::l_brace))
3127 // If the next token looks like a base or member initializer, assume that
3128 // we're just missing a comma.
3129 else if (Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3130 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3131 Diag(Loc, diag::err_ctor_init_missing_comma)
3132 << FixItHint::CreateInsertion(Loc, ", ");
3134 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3135 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3137 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3142 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3146 /// ParseMemInitializer - Parse a C++ member initializer, which is
3147 /// part of a constructor initializer that explicitly initializes one
3148 /// member or base class (C++ [class.base.init]). See
3149 /// ParseConstructorInitializer for an example.
3151 /// [C++] mem-initializer:
3152 /// mem-initializer-id '(' expression-list[opt] ')'
3153 /// [C++0x] mem-initializer-id braced-init-list
3155 /// [C++] mem-initializer-id:
3156 /// '::'[opt] nested-name-specifier[opt] class-name
3158 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3159 // parse '::'[opt] nested-name-specifier[opt]
3161 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
3162 ParsedType TemplateTypeTy;
3163 if (Tok.is(tok::annot_template_id)) {
3164 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3165 if (TemplateId->Kind == TNK_Type_template ||
3166 TemplateId->Kind == TNK_Dependent_template_name) {
3167 AnnotateTemplateIdTokenAsType();
3168 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3169 TemplateTypeTy = getTypeAnnotation(Tok);
3172 // Uses of decltype will already have been converted to annot_decltype by
3173 // ParseOptionalCXXScopeSpecifier at this point.
3174 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
3175 && Tok.isNot(tok::annot_decltype)) {
3176 Diag(Tok, diag::err_expected_member_or_base_name);
3180 IdentifierInfo *II = nullptr;
3181 DeclSpec DS(AttrFactory);
3182 SourceLocation IdLoc = Tok.getLocation();
3183 if (Tok.is(tok::annot_decltype)) {
3184 // Get the decltype expression, if there is one.
3185 ParseDecltypeSpecifier(DS);
3187 if (Tok.is(tok::identifier))
3188 // Get the identifier. This may be a member name or a class name,
3189 // but we'll let the semantic analysis determine which it is.
3190 II = Tok.getIdentifierInfo();
3196 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3197 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3199 ExprResult InitList = ParseBraceInitializer();
3200 if (InitList.isInvalid())
3203 SourceLocation EllipsisLoc;
3204 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3206 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3207 TemplateTypeTy, DS, IdLoc,
3208 InitList.get(), EllipsisLoc);
3209 } else if(Tok.is(tok::l_paren)) {
3210 BalancedDelimiterTracker T(*this, tok::l_paren);
3213 // Parse the optional expression-list.
3214 ExprVector ArgExprs;
3215 CommaLocsTy CommaLocs;
3216 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
3217 SkipUntil(tok::r_paren, StopAtSemi);
3223 SourceLocation EllipsisLoc;
3224 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3226 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3227 TemplateTypeTy, DS, IdLoc,
3228 T.getOpenLocation(), ArgExprs,
3229 T.getCloseLocation(), EllipsisLoc);
3232 if (getLangOpts().CPlusPlus11)
3233 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3235 return Diag(Tok, diag::err_expected) << tok::l_paren;
3238 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
3240 /// exception-specification:
3241 /// dynamic-exception-specification
3242 /// noexcept-specification
3244 /// noexcept-specification:
3246 /// 'noexcept' '(' constant-expression ')'
3247 ExceptionSpecificationType
3248 Parser::tryParseExceptionSpecification(bool Delayed,
3249 SourceRange &SpecificationRange,
3250 SmallVectorImpl<ParsedType> &DynamicExceptions,
3251 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3252 ExprResult &NoexceptExpr,
3253 CachedTokens *&ExceptionSpecTokens) {
3254 ExceptionSpecificationType Result = EST_None;
3255 ExceptionSpecTokens = 0;
3257 // Handle delayed parsing of exception-specifications.
3259 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3262 // Consume and cache the starting token.
3263 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3264 Token StartTok = Tok;
3265 SpecificationRange = SourceRange(ConsumeToken());
3268 if (!Tok.is(tok::l_paren)) {
3269 // If this is a bare 'noexcept', we're done.
3271 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3273 return EST_BasicNoexcept;
3276 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3277 return EST_DynamicNone;
3280 // Cache the tokens for the exception-specification.
3281 ExceptionSpecTokens = new CachedTokens;
3282 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3283 ExceptionSpecTokens->push_back(Tok); // '('
3284 SpecificationRange.setEnd(ConsumeParen()); // '('
3286 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3287 /*StopAtSemi=*/true,
3288 /*ConsumeFinalToken=*/true);
3289 SpecificationRange.setEnd(Tok.getLocation());
3290 return EST_Unparsed;
3293 // See if there's a dynamic specification.
3294 if (Tok.is(tok::kw_throw)) {
3295 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3297 DynamicExceptionRanges);
3298 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3299 "Produced different number of exception types and ranges.");
3302 // If there's no noexcept specification, we're done.
3303 if (Tok.isNot(tok::kw_noexcept))
3306 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3308 // If we already had a dynamic specification, parse the noexcept for,
3309 // recovery, but emit a diagnostic and don't store the results.
3310 SourceRange NoexceptRange;
3311 ExceptionSpecificationType NoexceptType = EST_None;
3313 SourceLocation KeywordLoc = ConsumeToken();
3314 if (Tok.is(tok::l_paren)) {
3315 // There is an argument.
3316 BalancedDelimiterTracker T(*this, tok::l_paren);
3318 NoexceptType = EST_ComputedNoexcept;
3319 NoexceptExpr = ParseConstantExpression();
3320 // The argument must be contextually convertible to bool. We use
3321 // ActOnBooleanCondition for this purpose.
3322 if (!NoexceptExpr.isInvalid())
3323 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
3324 NoexceptExpr.get());
3326 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3328 // There is no argument.
3329 NoexceptType = EST_BasicNoexcept;
3330 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3333 if (Result == EST_None) {
3334 SpecificationRange = NoexceptRange;
3335 Result = NoexceptType;
3337 // If there's a dynamic specification after a noexcept specification,
3338 // parse that and ignore the results.
3339 if (Tok.is(tok::kw_throw)) {
3340 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3341 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3342 DynamicExceptionRanges);
3345 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3351 static void diagnoseDynamicExceptionSpecification(
3352 Parser &P, const SourceRange &Range, bool IsNoexcept) {
3353 if (P.getLangOpts().CPlusPlus11) {
3354 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3355 P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
3356 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3357 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3361 /// ParseDynamicExceptionSpecification - Parse a C++
3362 /// dynamic-exception-specification (C++ [except.spec]).
3364 /// dynamic-exception-specification:
3365 /// 'throw' '(' type-id-list [opt] ')'
3366 /// [MS] 'throw' '(' '...' ')'
3369 /// type-id ... [opt]
3370 /// type-id-list ',' type-id ... [opt]
3372 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3373 SourceRange &SpecificationRange,
3374 SmallVectorImpl<ParsedType> &Exceptions,
3375 SmallVectorImpl<SourceRange> &Ranges) {
3376 assert(Tok.is(tok::kw_throw) && "expected throw");
3378 SpecificationRange.setBegin(ConsumeToken());
3379 BalancedDelimiterTracker T(*this, tok::l_paren);
3380 if (T.consumeOpen()) {
3381 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3382 SpecificationRange.setEnd(SpecificationRange.getBegin());
3383 return EST_DynamicNone;
3386 // Parse throw(...), a Microsoft extension that means "this function
3387 // can throw anything".
3388 if (Tok.is(tok::ellipsis)) {
3389 SourceLocation EllipsisLoc = ConsumeToken();
3390 if (!getLangOpts().MicrosoftExt)
3391 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3393 SpecificationRange.setEnd(T.getCloseLocation());
3394 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3398 // Parse the sequence of type-ids.
3400 while (Tok.isNot(tok::r_paren)) {
3401 TypeResult Res(ParseTypeName(&Range));
3403 if (Tok.is(tok::ellipsis)) {
3404 // C++0x [temp.variadic]p5:
3405 // - In a dynamic-exception-specification (15.4); the pattern is a
3407 SourceLocation Ellipsis = ConsumeToken();
3408 Range.setEnd(Ellipsis);
3409 if (!Res.isInvalid())
3410 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3413 if (!Res.isInvalid()) {
3414 Exceptions.push_back(Res.get());
3415 Ranges.push_back(Range);
3418 if (!TryConsumeToken(tok::comma))
3423 SpecificationRange.setEnd(T.getCloseLocation());
3424 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3425 Exceptions.empty());
3426 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3429 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3430 /// function declaration.
3431 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3432 assert(Tok.is(tok::arrow) && "expected arrow");
3436 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3439 /// \brief We have just started parsing the definition of a new class,
3440 /// so push that class onto our stack of classes that is currently
3442 Sema::ParsingClassState
3443 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3445 assert((NonNestedClass || !ClassStack.empty()) &&
3446 "Nested class without outer class");
3447 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3448 return Actions.PushParsingClass();
3451 /// \brief Deallocate the given parsed class and all of its nested
3453 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3454 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3455 delete Class->LateParsedDeclarations[I];
3459 /// \brief Pop the top class of the stack of classes that are
3460 /// currently being parsed.
3462 /// This routine should be called when we have finished parsing the
3463 /// definition of a class, but have not yet popped the Scope
3464 /// associated with the class's definition.
3465 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3466 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3468 Actions.PopParsingClass(state);
3470 ParsingClass *Victim = ClassStack.top();
3472 if (Victim->TopLevelClass) {
3473 // Deallocate all of the nested classes of this class,
3474 // recursively: we don't need to keep any of this information.
3475 DeallocateParsedClasses(Victim);
3478 assert(!ClassStack.empty() && "Missing top-level class?");
3480 if (Victim->LateParsedDeclarations.empty()) {
3481 // The victim is a nested class, but we will not need to perform
3482 // any processing after the definition of this class since it has
3483 // no members whose handling was delayed. Therefore, we can just
3484 // remove this nested class.
3485 DeallocateParsedClasses(Victim);
3489 // This nested class has some members that will need to be processed
3490 // after the top-level class is completely defined. Therefore, add
3491 // it to the list of nested classes within its parent.
3492 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3493 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3494 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3497 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3499 /// \return the parsed identifier on success, and 0 if the next token is not an
3500 /// attribute-token.
3502 /// C++11 [dcl.attr.grammar]p3:
3503 /// If a keyword or an alternative token that satisfies the syntactic
3504 /// requirements of an identifier is contained in an attribute-token,
3505 /// it is considered an identifier.
3506 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3507 switch (Tok.getKind()) {
3509 // Identifiers and keywords have identifier info attached.
3510 if (!Tok.isAnnotation()) {
3511 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3512 Loc = ConsumeToken();
3518 case tok::ampamp: // 'and'
3519 case tok::pipe: // 'bitor'
3520 case tok::pipepipe: // 'or'
3521 case tok::caret: // 'xor'
3522 case tok::tilde: // 'compl'
3523 case tok::amp: // 'bitand'
3524 case tok::ampequal: // 'and_eq'
3525 case tok::pipeequal: // 'or_eq'
3526 case tok::caretequal: // 'xor_eq'
3527 case tok::exclaim: // 'not'
3528 case tok::exclaimequal: // 'not_eq'
3529 // Alternative tokens do not have identifier info, but their spelling
3530 // starts with an alphabetical character.
3531 SmallString<8> SpellingBuf;
3532 SourceLocation SpellingLoc =
3533 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3534 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3535 if (isLetter(Spelling[0])) {
3536 Loc = ConsumeToken();
3537 return &PP.getIdentifierTable().get(Spelling);
3543 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3544 IdentifierInfo *ScopeName) {
3545 switch (AttributeList::getKind(AttrName, ScopeName,
3546 AttributeList::AS_CXX11)) {
3547 case AttributeList::AT_CarriesDependency:
3548 case AttributeList::AT_Deprecated:
3549 case AttributeList::AT_FallThrough:
3550 case AttributeList::AT_CXX11NoReturn: {
3559 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3561 /// [C++11] attribute-argument-clause:
3562 /// '(' balanced-token-seq ')'
3564 /// [C++11] balanced-token-seq:
3566 /// balanced-token-seq balanced-token
3568 /// [C++11] balanced-token:
3569 /// '(' balanced-token-seq ')'
3570 /// '[' balanced-token-seq ']'
3571 /// '{' balanced-token-seq '}'
3572 /// any token but '(', ')', '[', ']', '{', or '}'
3573 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3574 SourceLocation AttrNameLoc,
3575 ParsedAttributes &Attrs,
3576 SourceLocation *EndLoc,
3577 IdentifierInfo *ScopeName,
3578 SourceLocation ScopeLoc) {
3579 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3580 SourceLocation LParenLoc = Tok.getLocation();
3582 // If the attribute isn't known, we will not attempt to parse any
3584 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
3585 getTargetInfo().getTriple(), getLangOpts())) {
3586 // Eat the left paren, then skip to the ending right paren.
3588 SkipUntil(tok::r_paren);
3592 if (ScopeName && ScopeName->getName() == "gnu")
3593 // GNU-scoped attributes have some special cases to handle GNU-specific
3595 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3596 ScopeLoc, AttributeList::AS_CXX11, nullptr);
3599 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3600 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3602 const AttributeList *Attr = Attrs.getList();
3603 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3604 // If the attribute is a standard or built-in attribute and we are
3605 // parsing an argument list, we need to determine whether this attribute
3606 // was allowed to have an argument list (such as [[deprecated]]), and how
3607 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3608 if (Attr->getMaxArgs() && !NumArgs) {
3609 // The attribute was allowed to have arguments, but none were provided
3610 // even though the attribute parsed successfully. This is an error.
3611 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3612 } else if (!Attr->getMaxArgs()) {
3613 // The attribute parsed successfully, but was not allowed to have any
3614 // arguments. It doesn't matter whether any were provided -- the
3615 // presence of the argument list (even if empty) is diagnosed.
3616 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3618 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3625 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
3627 /// [C++11] attribute-specifier:
3628 /// '[' '[' attribute-list ']' ']'
3629 /// alignment-specifier
3631 /// [C++11] attribute-list:
3633 /// attribute-list ',' attribute[opt]
3635 /// attribute-list ',' attribute '...'
3637 /// [C++11] attribute:
3638 /// attribute-token attribute-argument-clause[opt]
3640 /// [C++11] attribute-token:
3642 /// attribute-scoped-token
3644 /// [C++11] attribute-scoped-token:
3645 /// attribute-namespace '::' identifier
3647 /// [C++11] attribute-namespace:
3649 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3650 SourceLocation *endLoc) {
3651 if (Tok.is(tok::kw_alignas)) {
3652 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3653 ParseAlignmentSpecifier(attrs, endLoc);
3657 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3658 && "Not a C++11 attribute list");
3660 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3665 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3667 while (Tok.isNot(tok::r_square)) {
3668 // attribute not present
3669 if (TryConsumeToken(tok::comma))
3672 SourceLocation ScopeLoc, AttrLoc;
3673 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3675 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3677 // Break out to the "expected ']'" diagnostic.
3681 if (TryConsumeToken(tok::coloncolon)) {
3682 ScopeName = AttrName;
3685 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3687 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3688 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3693 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
3694 bool AttrParsed = false;
3697 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3698 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
3699 << AttrName << SourceRange(SeenAttrs[AttrName]);
3701 // Parse attribute arguments
3702 if (Tok.is(tok::l_paren))
3703 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3704 ScopeName, ScopeLoc);
3707 attrs.addNew(AttrName,
3708 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3710 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
3712 if (TryConsumeToken(tok::ellipsis))
3713 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3714 << AttrName->getName();
3717 if (ExpectAndConsume(tok::r_square))
3718 SkipUntil(tok::r_square);
3720 *endLoc = Tok.getLocation();
3721 if (ExpectAndConsume(tok::r_square))
3722 SkipUntil(tok::r_square);
3725 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3727 /// attribute-specifier-seq:
3728 /// attribute-specifier-seq[opt] attribute-specifier
3729 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3730 SourceLocation *endLoc) {
3731 assert(getLangOpts().CPlusPlus11);
3733 SourceLocation StartLoc = Tok.getLocation(), Loc;
3738 ParseCXX11AttributeSpecifier(attrs, endLoc);
3739 } while (isCXX11AttributeSpecifier());
3741 attrs.Range = SourceRange(StartLoc, *endLoc);
3744 void Parser::DiagnoseAndSkipCXX11Attributes() {
3745 // Start and end location of an attribute or an attribute list.
3746 SourceLocation StartLoc = Tok.getLocation();
3747 SourceLocation EndLoc = SkipCXX11Attributes();
3749 if (EndLoc.isValid()) {
3750 SourceRange Range(StartLoc, EndLoc);
3751 Diag(StartLoc, diag::err_attributes_not_allowed)
3756 SourceLocation Parser::SkipCXX11Attributes() {
3757 SourceLocation EndLoc;
3759 if (!isCXX11AttributeSpecifier())
3763 if (Tok.is(tok::l_square)) {
3764 BalancedDelimiterTracker T(*this, tok::l_square);
3767 EndLoc = T.getCloseLocation();
3769 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
3771 BalancedDelimiterTracker T(*this, tok::l_paren);
3772 if (!T.consumeOpen())
3774 EndLoc = T.getCloseLocation();
3776 } while (isCXX11AttributeSpecifier());
3781 /// Parse one or more Microsoft-style attributes [Attr]
3783 /// [MS] ms-attribute:
3784 /// '[' token-seq ']'
3786 /// [MS] ms-attribute-seq:
3787 /// ms-attribute[opt]
3788 /// ms-attribute ms-attribute-seq
3789 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3790 SourceLocation *endLoc) {
3791 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3794 // FIXME: If this is actually a C++11 attribute, parse it as one.
3795 BalancedDelimiterTracker T(*this, tok::l_square);
3797 if (Tok.is(tok::r_square))
3798 Diag(T.getOpenLocation(), diag::err_empty_attribute_block);
3799 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
3802 *endLoc = T.getCloseLocation();
3803 } while (Tok.is(tok::l_square));
3806 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3807 AccessSpecifier& CurAS) {
3808 IfExistsCondition Result;
3809 if (ParseMicrosoftIfExistsCondition(Result))
3812 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3813 if (Braces.consumeOpen()) {
3814 Diag(Tok, diag::err_expected) << tok::l_brace;
3818 switch (Result.Behavior) {
3820 // Parse the declarations below.
3824 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3825 << Result.IsIfExists;
3826 // Fall through to skip.
3833 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
3834 // __if_exists, __if_not_exists can nest.
3835 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
3836 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3840 // Check for extraneous top-level semicolon.
3841 if (Tok.is(tok::semi)) {
3842 ConsumeExtraSemi(InsideStruct, TagType);
3846 AccessSpecifier AS = getAccessSpecifierIfPresent();
3847 if (AS != AS_none) {
3848 // Current token is a C++ access specifier.
3850 SourceLocation ASLoc = Tok.getLocation();
3852 if (Tok.is(tok::colon))
3853 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3855 Diag(Tok, diag::err_expected) << tok::colon;
3860 // Parse all the comma separated declarators.
3861 ParseCXXClassMemberDeclaration(CurAS, nullptr);
3864 Braces.consumeClose();