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/TargetInfo.h"
21 #include "clang/Basic/OperatorKinds.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;
78 if (Tok.is(tok::identifier)) {
79 Ident = Tok.getIdentifierInfo();
80 IdentLoc = ConsumeToken(); // eat the identifier.
81 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
82 ExtraNamespaceLoc.push_back(ConsumeToken());
83 ExtraIdent.push_back(Tok.getIdentifierInfo());
84 ExtraIdentLoc.push_back(ConsumeToken());
88 // Read label attributes, if present.
89 ParsedAttributes attrs(AttrFactory);
90 if (Tok.is(tok::kw___attribute)) {
92 ParseGNUAttributes(attrs);
95 if (Tok.is(tok::equal)) {
97 Diag(Tok, diag::err_expected) << tok::identifier;
98 // Skip to end of the definition and eat the ';'.
103 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
104 if (InlineLoc.isValid())
105 Diag(InlineLoc, diag::err_inline_namespace_alias)
106 << FixItHint::CreateRemoval(InlineLoc);
107 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
111 BalancedDelimiterTracker T(*this, tok::l_brace);
112 if (T.consumeOpen()) {
113 if (!ExtraIdent.empty()) {
114 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
115 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
119 Diag(Tok, diag::err_expected) << tok::l_brace;
121 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
126 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
127 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
128 getCurScope()->getFnParent()) {
129 if (!ExtraIdent.empty()) {
130 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
131 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
133 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
134 SkipUntil(tok::r_brace);
138 if (!ExtraIdent.empty()) {
139 TentativeParsingAction TPA(*this);
140 SkipUntil(tok::r_brace, StopBeforeMatch);
141 Token rBraceToken = Tok;
144 if (!rBraceToken.is(tok::r_brace)) {
145 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
146 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
148 std::string NamespaceFix;
149 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
150 E = ExtraIdent.end(); I != E; ++I) {
151 NamespaceFix += " { namespace ";
152 NamespaceFix += (*I)->getName();
156 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
159 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
160 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
161 ExtraIdentLoc.back()),
163 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
167 // If we're still good, complain about inline namespaces in non-C++0x now.
168 if (InlineLoc.isValid())
169 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
170 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
172 // Enter a scope for the namespace.
173 ParseScope NamespaceScope(this, Scope::DeclScope);
176 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
177 IdentLoc, Ident, T.getOpenLocation(),
180 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
181 "parsing namespace");
183 // Parse the contents of the namespace. This includes parsing recovery on
184 // any improperly nested namespaces.
185 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
186 InlineLoc, attrs, T);
188 // Leave the namespace scope.
189 NamespaceScope.Exit();
191 DeclEnd = T.getCloseLocation();
192 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
197 /// ParseInnerNamespace - Parse the contents of a namespace.
198 void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
199 std::vector<IdentifierInfo*>& Ident,
200 std::vector<SourceLocation>& NamespaceLoc,
201 unsigned int index, SourceLocation& InlineLoc,
202 ParsedAttributes& attrs,
203 BalancedDelimiterTracker &Tracker) {
204 if (index == Ident.size()) {
205 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
206 ParsedAttributesWithRange attrs(AttrFactory);
207 MaybeParseCXX11Attributes(attrs);
208 MaybeParseMicrosoftAttributes(attrs);
209 ParseExternalDeclaration(attrs);
212 // The caller is what called check -- we are simply calling
214 Tracker.consumeClose();
219 // Parse improperly nested namespaces.
220 ParseScope NamespaceScope(this, Scope::DeclScope);
222 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
223 NamespaceLoc[index], IdentLoc[index],
224 Ident[index], Tracker.getOpenLocation(),
227 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
230 NamespaceScope.Exit();
232 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
235 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
236 /// alias definition.
238 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
239 SourceLocation AliasLoc,
240 IdentifierInfo *Alias,
241 SourceLocation &DeclEnd) {
242 assert(Tok.is(tok::equal) && "Not equal token");
244 ConsumeToken(); // eat the '='.
246 if (Tok.is(tok::code_completion)) {
247 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
253 // Parse (optional) nested-name-specifier.
254 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
256 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
257 Diag(Tok, diag::err_expected_namespace_name);
258 // Skip to end of the definition and eat the ';'.
259 SkipUntil(tok::semi);
264 IdentifierInfo *Ident = Tok.getIdentifierInfo();
265 SourceLocation IdentLoc = ConsumeToken();
268 DeclEnd = Tok.getLocation();
269 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
270 SkipUntil(tok::semi);
272 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
273 SS, IdentLoc, Ident);
276 /// ParseLinkage - We know that the current token is a string_literal
277 /// and just before that, that extern was seen.
279 /// linkage-specification: [C++ 7.5p2: dcl.link]
280 /// 'extern' string-literal '{' declaration-seq[opt] '}'
281 /// 'extern' string-literal declaration
283 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
284 assert(isTokenStringLiteral() && "Not a string literal!");
285 ExprResult Lang = ParseStringLiteralExpression(false);
287 ParseScope LinkageScope(this, Scope::DeclScope);
291 : Actions.ActOnStartLinkageSpecification(
292 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
293 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
295 ParsedAttributesWithRange attrs(AttrFactory);
296 MaybeParseCXX11Attributes(attrs);
297 MaybeParseMicrosoftAttributes(attrs);
299 if (Tok.isNot(tok::l_brace)) {
300 // Reset the source range in DS, as the leading "extern"
301 // does not really belong to the inner declaration ...
302 DS.SetRangeStart(SourceLocation());
303 DS.SetRangeEnd(SourceLocation());
304 // ... but anyway remember that such an "extern" was seen.
305 DS.setExternInLinkageSpec(true);
306 ParseExternalDeclaration(attrs, &DS);
307 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
308 getCurScope(), LinkageSpec, SourceLocation())
314 ProhibitAttributes(attrs);
316 BalancedDelimiterTracker T(*this, tok::l_brace);
319 unsigned NestedModules = 0;
321 switch (Tok.getKind()) {
322 case tok::annot_module_begin:
327 case tok::annot_module_end:
334 case tok::annot_module_include:
346 ParsedAttributesWithRange attrs(AttrFactory);
347 MaybeParseCXX11Attributes(attrs);
348 MaybeParseMicrosoftAttributes(attrs);
349 ParseExternalDeclaration(attrs);
357 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
358 getCurScope(), LinkageSpec, T.getCloseLocation())
362 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
363 /// using-directive. Assumes that current token is 'using'.
364 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
365 const ParsedTemplateInfo &TemplateInfo,
366 SourceLocation &DeclEnd,
367 ParsedAttributesWithRange &attrs,
369 assert(Tok.is(tok::kw_using) && "Not using token");
370 ObjCDeclContextSwitch ObjCDC(*this);
373 SourceLocation UsingLoc = ConsumeToken();
375 if (Tok.is(tok::code_completion)) {
376 Actions.CodeCompleteUsing(getCurScope());
381 // 'using namespace' means this is a using-directive.
382 if (Tok.is(tok::kw_namespace)) {
383 // Template parameters are always an error here.
384 if (TemplateInfo.Kind) {
385 SourceRange R = TemplateInfo.getSourceRange();
386 Diag(UsingLoc, diag::err_templated_using_directive)
387 << R << FixItHint::CreateRemoval(R);
390 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
393 // Otherwise, it must be a using-declaration or an alias-declaration.
395 // Using declarations can't have attributes.
396 ProhibitAttributes(attrs);
398 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
402 /// ParseUsingDirective - Parse C++ using-directive, assumes
403 /// that current token is 'namespace' and 'using' was already parsed.
405 /// using-directive: [C++ 7.3.p4: namespace.udir]
406 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
408 /// [GNU] using-directive:
409 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
410 /// namespace-name attributes[opt] ;
412 Decl *Parser::ParseUsingDirective(unsigned Context,
413 SourceLocation UsingLoc,
414 SourceLocation &DeclEnd,
415 ParsedAttributes &attrs) {
416 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
419 SourceLocation NamespcLoc = ConsumeToken();
421 if (Tok.is(tok::code_completion)) {
422 Actions.CodeCompleteUsingDirective(getCurScope());
428 // Parse (optional) nested-name-specifier.
429 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
431 IdentifierInfo *NamespcName = nullptr;
432 SourceLocation IdentLoc = SourceLocation();
434 // Parse namespace-name.
435 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
436 Diag(Tok, diag::err_expected_namespace_name);
437 // If there was invalid namespace name, skip to end of decl, and eat ';'.
438 SkipUntil(tok::semi);
439 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
444 NamespcName = Tok.getIdentifierInfo();
445 IdentLoc = ConsumeToken();
447 // Parse (optional) attributes (most likely GNU strong-using extension).
448 bool GNUAttr = false;
449 if (Tok.is(tok::kw___attribute)) {
451 ParseGNUAttributes(attrs);
455 DeclEnd = Tok.getLocation();
456 if (ExpectAndConsume(tok::semi,
457 GNUAttr ? diag::err_expected_semi_after_attribute_list
458 : diag::err_expected_semi_after_namespace_name))
459 SkipUntil(tok::semi);
461 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
462 IdentLoc, NamespcName, attrs.getList());
465 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
466 /// Assumes that 'using' was already seen.
468 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
469 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
471 /// 'using' :: unqualified-id
473 /// alias-declaration: C++11 [dcl.dcl]p1
474 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
476 Decl *Parser::ParseUsingDeclaration(unsigned Context,
477 const ParsedTemplateInfo &TemplateInfo,
478 SourceLocation UsingLoc,
479 SourceLocation &DeclEnd,
483 SourceLocation TypenameLoc;
484 bool HasTypenameKeyword = false;
486 // Check for misplaced attributes before the identifier in an
487 // alias-declaration.
488 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
489 MaybeParseCXX11Attributes(MisplacedAttrs);
491 // Ignore optional 'typename'.
492 // FIXME: This is wrong; we should parse this as a typename-specifier.
493 if (TryConsumeToken(tok::kw_typename, TypenameLoc))
494 HasTypenameKeyword = true;
496 // Parse nested-name-specifier.
497 IdentifierInfo *LastII = nullptr;
498 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false,
499 /*MayBePseudoDtor=*/nullptr,
500 /*IsTypename=*/false,
503 // Check nested-name specifier.
504 if (SS.isInvalid()) {
505 SkipUntil(tok::semi);
509 SourceLocation TemplateKWLoc;
512 // Parse the unqualified-id. We allow parsing of both constructor and
513 // destructor names and allow the action module to diagnose any semantic
516 // C++11 [class.qual]p2:
517 // [...] in a using-declaration that is a member-declaration, if the name
518 // specified after the nested-name-specifier is the same as the identifier
519 // or the simple-template-id's template-name in the last component of the
520 // nested-name-specifier, the name is [...] considered to name the
522 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
523 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
524 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
525 !SS.getScopeRep()->getAsNamespace() &&
526 !SS.getScopeRep()->getAsNamespaceAlias()) {
527 SourceLocation IdLoc = ConsumeToken();
528 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
529 Name.setConstructorName(Type, IdLoc, IdLoc);
530 } else if (ParseUnqualifiedId(SS, /*EnteringContext=*/ false,
531 /*AllowDestructorName=*/ true,
532 /*AllowConstructorName=*/ true, ParsedType(),
533 TemplateKWLoc, Name)) {
534 SkipUntil(tok::semi);
538 ParsedAttributesWithRange Attrs(AttrFactory);
539 MaybeParseGNUAttributes(Attrs);
540 MaybeParseCXX11Attributes(Attrs);
542 // Maybe this is an alias-declaration.
543 TypeResult TypeAlias;
544 bool IsAliasDecl = Tok.is(tok::equal);
546 // If we had any misplaced attributes from earlier, this is where they
547 // should have been written.
548 if (MisplacedAttrs.Range.isValid()) {
549 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
550 << FixItHint::CreateInsertionFromRange(
552 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
553 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
554 Attrs.takeAllFrom(MisplacedAttrs);
559 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
560 diag::warn_cxx98_compat_alias_declaration :
561 diag::ext_alias_declaration);
563 // Type alias templates cannot be specialized.
565 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
566 Name.getKind() == UnqualifiedId::IK_TemplateId)
568 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
570 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
572 if (SpecKind != -1) {
575 Range = SourceRange(Name.TemplateId->LAngleLoc,
576 Name.TemplateId->RAngleLoc);
578 Range = TemplateInfo.getSourceRange();
579 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
580 << SpecKind << Range;
581 SkipUntil(tok::semi);
585 // Name must be an identifier.
586 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
587 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
588 // No removal fixit: can't recover from this.
589 SkipUntil(tok::semi);
591 } else if (HasTypenameKeyword)
592 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
593 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
594 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
595 else if (SS.isNotEmpty())
596 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
597 << FixItHint::CreateRemoval(SS.getRange());
599 TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind ?
600 Declarator::AliasTemplateContext :
601 Declarator::AliasDeclContext, AS, OwnedType,
604 // C++11 attributes are not allowed on a using-declaration, but GNU ones
606 ProhibitAttributes(MisplacedAttrs);
607 ProhibitAttributes(Attrs);
609 // Parse (optional) attributes (most likely GNU strong-using extension).
610 MaybeParseGNUAttributes(Attrs);
614 DeclEnd = Tok.getLocation();
615 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
616 !Attrs.empty() ? "attributes list"
617 : IsAliasDecl ? "alias declaration"
618 : "using declaration"))
619 SkipUntil(tok::semi);
621 // Diagnose an attempt to declare a templated using-declaration.
622 // In C++11, alias-declarations can be templates:
623 // template <...> using id = type;
624 if (TemplateInfo.Kind && !IsAliasDecl) {
625 SourceRange R = TemplateInfo.getSourceRange();
626 Diag(UsingLoc, diag::err_templated_using_declaration)
627 << R << FixItHint::CreateRemoval(R);
629 // Unfortunately, we have to bail out instead of recovering by
630 // ignoring the parameters, just in case the nested name specifier
631 // depends on the parameters.
635 // "typename" keyword is allowed for identifiers only,
636 // because it may be a type definition.
637 if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
638 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
639 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
640 // Proceed parsing, but reset the HasTypenameKeyword flag.
641 HasTypenameKeyword = false;
645 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
646 MultiTemplateParamsArg TemplateParamsArg(
647 TemplateParams ? TemplateParams->data() : nullptr,
648 TemplateParams ? TemplateParams->size() : 0);
649 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
650 UsingLoc, Name, Attrs.getList(),
654 return Actions.ActOnUsingDeclaration(getCurScope(), AS,
655 /* HasUsingKeyword */ true, UsingLoc,
656 SS, Name, Attrs.getList(),
657 HasTypenameKeyword, TypenameLoc);
660 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
662 /// [C++0x] static_assert-declaration:
663 /// static_assert ( constant-expression , string-literal ) ;
665 /// [C11] static_assert-declaration:
666 /// _Static_assert ( constant-expression , string-literal ) ;
668 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
669 assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) &&
670 "Not a static_assert declaration");
672 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
673 Diag(Tok, diag::ext_c11_static_assert);
674 if (Tok.is(tok::kw_static_assert))
675 Diag(Tok, diag::warn_cxx98_compat_static_assert);
677 SourceLocation StaticAssertLoc = ConsumeToken();
679 BalancedDelimiterTracker T(*this, tok::l_paren);
680 if (T.consumeOpen()) {
681 Diag(Tok, diag::err_expected) << tok::l_paren;
686 ExprResult AssertExpr(ParseConstantExpression());
687 if (AssertExpr.isInvalid()) {
692 ExprResult AssertMessage;
693 if (Tok.is(tok::r_paren)) {
694 Diag(Tok, getLangOpts().CPlusPlus1z
695 ? diag::warn_cxx1y_compat_static_assert_no_message
696 : diag::ext_static_assert_no_message)
697 << (getLangOpts().CPlusPlus1z
699 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
701 if (ExpectAndConsume(tok::comma)) {
702 SkipUntil(tok::semi);
706 if (!isTokenStringLiteral()) {
707 Diag(Tok, diag::err_expected_string_literal)
708 << /*Source='static_assert'*/1;
713 AssertMessage = ParseStringLiteralExpression();
714 if (AssertMessage.isInvalid()) {
722 DeclEnd = Tok.getLocation();
723 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
725 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
728 T.getCloseLocation());
731 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
733 /// 'decltype' ( expression )
734 /// 'decltype' ( 'auto' ) [C++1y]
736 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
737 assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
738 && "Not a decltype specifier");
741 SourceLocation StartLoc = Tok.getLocation();
742 SourceLocation EndLoc;
744 if (Tok.is(tok::annot_decltype)) {
745 Result = getExprAnnotation(Tok);
746 EndLoc = Tok.getAnnotationEndLoc();
748 if (Result.isInvalid()) {
749 DS.SetTypeSpecError();
753 if (Tok.getIdentifierInfo()->isStr("decltype"))
754 Diag(Tok, diag::warn_cxx98_compat_decltype);
758 BalancedDelimiterTracker T(*this, tok::l_paren);
759 if (T.expectAndConsume(diag::err_expected_lparen_after,
760 "decltype", tok::r_paren)) {
761 DS.SetTypeSpecError();
762 return T.getOpenLocation() == Tok.getLocation() ?
763 StartLoc : T.getOpenLocation();
766 // Check for C++1y 'decltype(auto)'.
767 if (Tok.is(tok::kw_auto)) {
768 // No need to disambiguate here: an expression can't start with 'auto',
769 // because the typename-specifier in a function-style cast operation can't
771 Diag(Tok.getLocation(),
772 getLangOpts().CPlusPlus1y
773 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
774 : diag::ext_decltype_auto_type_specifier);
777 // Parse the expression
779 // C++11 [dcl.type.simple]p4:
780 // The operand of the decltype specifier is an unevaluated operand.
781 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
782 nullptr,/*IsDecltype=*/true);
783 Result = ParseExpression();
784 if (Result.isInvalid()) {
785 DS.SetTypeSpecError();
786 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
787 EndLoc = ConsumeParen();
789 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
790 // Backtrack to get the location of the last token before the semi.
791 PP.RevertCachedTokens(2);
792 ConsumeToken(); // the semi.
793 EndLoc = ConsumeAnyToken();
794 assert(Tok.is(tok::semi));
796 EndLoc = Tok.getLocation();
802 Result = Actions.ActOnDecltypeExpression(Result.get());
807 if (T.getCloseLocation().isInvalid()) {
808 DS.SetTypeSpecError();
809 // FIXME: this should return the location of the last token
810 // that was consumed (by "consumeClose()")
811 return T.getCloseLocation();
814 if (Result.isInvalid()) {
815 DS.SetTypeSpecError();
816 return T.getCloseLocation();
819 EndLoc = T.getCloseLocation();
821 assert(!Result.isInvalid());
823 const char *PrevSpec = nullptr;
825 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
826 // Check for duplicate type specifiers (e.g. "int decltype(a)").
828 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
829 DiagID, Result.get(), Policy)
830 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
832 Diag(StartLoc, DiagID) << PrevSpec;
833 DS.SetTypeSpecError();
838 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
839 SourceLocation StartLoc,
840 SourceLocation EndLoc) {
841 // make sure we have a token we can turn into an annotation token
842 if (PP.isBacktrackEnabled())
843 PP.RevertCachedTokens(1);
847 Tok.setKind(tok::annot_decltype);
848 setExprAnnotation(Tok,
849 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
850 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
852 Tok.setAnnotationEndLoc(EndLoc);
853 Tok.setLocation(StartLoc);
854 PP.AnnotateCachedTokens(Tok);
857 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
858 assert(Tok.is(tok::kw___underlying_type) &&
859 "Not an underlying type specifier");
861 SourceLocation StartLoc = ConsumeToken();
862 BalancedDelimiterTracker T(*this, tok::l_paren);
863 if (T.expectAndConsume(diag::err_expected_lparen_after,
864 "__underlying_type", tok::r_paren)) {
868 TypeResult Result = ParseTypeName();
869 if (Result.isInvalid()) {
870 SkipUntil(tok::r_paren, StopAtSemi);
876 if (T.getCloseLocation().isInvalid())
879 const char *PrevSpec = nullptr;
881 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
882 DiagID, Result.get(),
883 Actions.getASTContext().getPrintingPolicy()))
884 Diag(StartLoc, DiagID) << PrevSpec;
885 DS.setTypeofParensRange(T.getRange());
888 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
889 /// class name or decltype-specifier. Note that we only check that the result
890 /// names a type; semantic analysis will need to verify that the type names a
891 /// class. The result is either a type or null, depending on whether a type
894 /// base-type-specifier: [C++11 class.derived]
895 /// class-or-decltype
896 /// class-or-decltype: [C++11 class.derived]
897 /// nested-name-specifier[opt] class-name
898 /// decltype-specifier
899 /// class-name: [C++ class.name]
901 /// simple-template-id
903 /// In C++98, instead of base-type-specifier, we have:
905 /// ::[opt] nested-name-specifier[opt] class-name
906 Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
907 SourceLocation &EndLocation) {
908 // Ignore attempts to use typename
909 if (Tok.is(tok::kw_typename)) {
910 Diag(Tok, diag::err_expected_class_name_not_template)
911 << FixItHint::CreateRemoval(Tok.getLocation());
915 // Parse optional nested-name-specifier
917 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
919 BaseLoc = Tok.getLocation();
921 // Parse decltype-specifier
922 // tok == kw_decltype is just error recovery, it can only happen when SS
924 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
926 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
927 << FixItHint::CreateRemoval(SS.getRange());
928 // Fake up a Declarator to use with ActOnTypeName.
929 DeclSpec DS(AttrFactory);
931 EndLocation = ParseDecltypeSpecifier(DS);
933 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
934 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
937 // Check whether we have a template-id that names a type.
938 if (Tok.is(tok::annot_template_id)) {
939 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
940 if (TemplateId->Kind == TNK_Type_template ||
941 TemplateId->Kind == TNK_Dependent_template_name) {
942 AnnotateTemplateIdTokenAsType();
944 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
945 ParsedType Type = getTypeAnnotation(Tok);
946 EndLocation = Tok.getAnnotationEndLoc();
954 // Fall through to produce an error below.
957 if (Tok.isNot(tok::identifier)) {
958 Diag(Tok, diag::err_expected_class_name);
962 IdentifierInfo *Id = Tok.getIdentifierInfo();
963 SourceLocation IdLoc = ConsumeToken();
965 if (Tok.is(tok::less)) {
966 // It looks the user intended to write a template-id here, but the
967 // template-name was wrong. Try to fix that.
968 TemplateNameKind TNK = TNK_Type_template;
970 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
971 &SS, Template, TNK)) {
972 Diag(IdLoc, diag::err_unknown_template_name)
977 TemplateArgList TemplateArgs;
978 SourceLocation LAngleLoc, RAngleLoc;
979 ParseTemplateIdAfterTemplateName(TemplateTy(), IdLoc, SS,
980 true, LAngleLoc, TemplateArgs, RAngleLoc);
984 // Form the template name
985 UnqualifiedId TemplateName;
986 TemplateName.setIdentifier(Id, IdLoc);
988 // Parse the full template-id, then turn it into a type.
989 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
992 if (TNK == TNK_Dependent_template_name)
993 AnnotateTemplateIdTokenAsType();
995 // If we didn't end up with a typename token, there's nothing more we
997 if (Tok.isNot(tok::annot_typename))
1000 // Retrieve the type from the annotation token, consume that token, and
1002 EndLocation = Tok.getAnnotationEndLoc();
1003 ParsedType Type = getTypeAnnotation(Tok);
1008 // We have an identifier; check whether it is actually a type.
1009 IdentifierInfo *CorrectedII = nullptr;
1010 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
1011 false, ParsedType(),
1012 /*IsCtorOrDtorName=*/false,
1013 /*NonTrivialTypeSourceInfo=*/true,
1016 Diag(IdLoc, diag::err_expected_class_name);
1020 // Consume the identifier.
1021 EndLocation = IdLoc;
1023 // Fake up a Declarator to use with ActOnTypeName.
1024 DeclSpec DS(AttrFactory);
1025 DS.SetRangeStart(IdLoc);
1026 DS.SetRangeEnd(EndLocation);
1027 DS.getTypeSpecScope() = SS;
1029 const char *PrevSpec = nullptr;
1031 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1032 Actions.getASTContext().getPrintingPolicy());
1034 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1035 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1038 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1039 while (Tok.is(tok::kw___single_inheritance) ||
1040 Tok.is(tok::kw___multiple_inheritance) ||
1041 Tok.is(tok::kw___virtual_inheritance)) {
1042 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1043 SourceLocation AttrNameLoc = ConsumeToken();
1044 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1045 AttributeList::AS_Keyword);
1049 /// Determine whether the following tokens are valid after a type-specifier
1050 /// which could be a standalone declaration. This will conservatively return
1051 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1052 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1053 // This switch enumerates the valid "follow" set for type-specifiers.
1054 switch (Tok.getKind()) {
1056 case tok::semi: // struct foo {...} ;
1057 case tok::star: // struct foo {...} * P;
1058 case tok::amp: // struct foo {...} & R = ...
1059 case tok::ampamp: // struct foo {...} && R = ...
1060 case tok::identifier: // struct foo {...} V ;
1061 case tok::r_paren: //(struct foo {...} ) {4}
1062 case tok::annot_cxxscope: // struct foo {...} a:: b;
1063 case tok::annot_typename: // struct foo {...} a ::b;
1064 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1065 case tok::l_paren: // struct foo {...} ( x);
1066 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1067 case tok::kw_operator: // struct foo operator ++() {...}
1068 case tok::kw___declspec: // struct foo {...} __declspec(...)
1071 return CouldBeBitfield; // enum E { ... } : 2;
1073 case tok::kw_const: // struct foo {...} const x;
1074 case tok::kw_volatile: // struct foo {...} volatile x;
1075 case tok::kw_restrict: // struct foo {...} restrict x;
1076 // Function specifiers
1077 // Note, no 'explicit'. An explicit function must be either a conversion
1078 // operator or a constructor. Either way, it can't have a return type.
1079 case tok::kw_inline: // struct foo inline f();
1080 case tok::kw_virtual: // struct foo virtual f();
1081 case tok::kw_friend: // struct foo friend f();
1082 // Storage-class specifiers
1083 case tok::kw_static: // struct foo {...} static x;
1084 case tok::kw_extern: // struct foo {...} extern x;
1085 case tok::kw_typedef: // struct foo {...} typedef x;
1086 case tok::kw_register: // struct foo {...} register x;
1087 case tok::kw_auto: // struct foo {...} auto x;
1088 case tok::kw_mutable: // struct foo {...} mutable x;
1089 case tok::kw_thread_local: // struct foo {...} thread_local x;
1090 case tok::kw_constexpr: // struct foo {...} constexpr x;
1091 // As shown above, type qualifiers and storage class specifiers absolutely
1092 // can occur after class specifiers according to the grammar. However,
1093 // almost no one actually writes code like this. If we see one of these,
1094 // it is much more likely that someone missed a semi colon and the
1095 // type/storage class specifier we're seeing is part of the *next*
1096 // intended declaration, as in:
1098 // struct foo { ... }
1101 // We'd really like to emit a missing semicolon error instead of emitting
1102 // an error on the 'int' saying that you can't have two type specifiers in
1103 // the same declaration of X. Because of this, we look ahead past this
1104 // token to see if it's a type specifier. If so, we know the code is
1105 // otherwise invalid, so we can produce the expected semi error.
1106 if (!isKnownToBeTypeSpecifier(NextToken()))
1109 case tok::r_brace: // struct bar { struct foo {...} }
1110 // Missing ';' at end of struct is accepted as an extension in C mode.
1111 if (!getLangOpts().CPlusPlus)
1115 case tok::l_square: // enum E [[]] x
1116 // Note, no tok::kw_alignas here; alignas cannot appertain to a type.
1117 return getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1119 // template<class T = class X>
1120 return getLangOpts().CPlusPlus;
1125 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1126 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1127 /// until we reach the start of a definition or see a token that
1128 /// cannot start a definition.
1130 /// class-specifier: [C++ class]
1131 /// class-head '{' member-specification[opt] '}'
1132 /// class-head '{' member-specification[opt] '}' attributes[opt]
1134 /// class-key identifier[opt] base-clause[opt]
1135 /// class-key nested-name-specifier identifier base-clause[opt]
1136 /// class-key nested-name-specifier[opt] simple-template-id
1137 /// base-clause[opt]
1138 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1139 /// [GNU] class-key attributes[opt] nested-name-specifier
1140 /// identifier base-clause[opt]
1141 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1142 /// simple-template-id base-clause[opt]
1148 /// elaborated-type-specifier: [C++ dcl.type.elab]
1149 /// class-key ::[opt] nested-name-specifier[opt] identifier
1150 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1151 /// simple-template-id
1153 /// Note that the C++ class-specifier and elaborated-type-specifier,
1154 /// together, subsume the C99 struct-or-union-specifier:
1156 /// struct-or-union-specifier: [C99 6.7.2.1]
1157 /// struct-or-union identifier[opt] '{' struct-contents '}'
1158 /// struct-or-union identifier
1159 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1160 /// '}' attributes[opt]
1161 /// [GNU] struct-or-union attributes[opt] identifier
1162 /// struct-or-union:
1165 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1166 SourceLocation StartLoc, DeclSpec &DS,
1167 const ParsedTemplateInfo &TemplateInfo,
1169 bool EnteringContext, DeclSpecContext DSC,
1170 ParsedAttributesWithRange &Attributes) {
1171 DeclSpec::TST TagType;
1172 if (TagTokKind == tok::kw_struct)
1173 TagType = DeclSpec::TST_struct;
1174 else if (TagTokKind == tok::kw___interface)
1175 TagType = DeclSpec::TST_interface;
1176 else if (TagTokKind == tok::kw_class)
1177 TagType = DeclSpec::TST_class;
1179 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1180 TagType = DeclSpec::TST_union;
1183 if (Tok.is(tok::code_completion)) {
1184 // Code completion for a struct, class, or union name.
1185 Actions.CodeCompleteTag(getCurScope(), TagType);
1186 return cutOffParsing();
1189 // C++03 [temp.explicit] 14.7.2/8:
1190 // The usual access checking rules do not apply to names used to specify
1191 // explicit instantiations.
1193 // As an extension we do not perform access checking on the names used to
1194 // specify explicit specializations either. This is important to allow
1195 // specializing traits classes for private types.
1197 // Note that we don't suppress if this turns out to be an elaborated
1199 bool shouldDelayDiagsInTag =
1200 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1201 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1202 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1204 ParsedAttributesWithRange attrs(AttrFactory);
1205 // If attributes exist after tag, parse them.
1206 MaybeParseGNUAttributes(attrs);
1208 // If declspecs exist after tag, parse them.
1209 while (Tok.is(tok::kw___declspec))
1210 ParseMicrosoftDeclSpec(attrs);
1212 // Parse inheritance specifiers.
1213 if (Tok.is(tok::kw___single_inheritance) ||
1214 Tok.is(tok::kw___multiple_inheritance) ||
1215 Tok.is(tok::kw___virtual_inheritance))
1216 ParseMicrosoftInheritanceClassAttributes(attrs);
1218 // If C++0x attributes exist here, parse them.
1219 // FIXME: Are we consistent with the ordering of parsing of different
1220 // styles of attributes?
1221 MaybeParseCXX11Attributes(attrs);
1223 // Source location used by FIXIT to insert misplaced
1225 SourceLocation AttrFixitLoc = Tok.getLocation();
1227 // GNU libstdc++ and libc++ use certain intrinsic names as the
1228 // name of struct templates, but some are keywords in GCC >= 4.3
1229 // MSVC and Clang. For compatibility, convert the token to an identifier
1230 // and issue a warning diagnostic.
1231 if (TagType == DeclSpec::TST_struct && !Tok.is(tok::identifier) &&
1232 !Tok.isAnnotation()) {
1233 const IdentifierInfo *II = Tok.getIdentifierInfo();
1234 // We rarely end up here so the following check is efficient.
1235 if (II && II->getName().startswith("__is_"))
1236 TryKeywordIdentFallback(true);
1239 // Parse the (optional) nested-name-specifier.
1240 CXXScopeSpec &SS = DS.getTypeSpecScope();
1241 if (getLangOpts().CPlusPlus) {
1242 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1243 // is a base-specifier-list.
1244 ColonProtectionRAIIObject X(*this);
1246 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1247 DS.SetTypeSpecError();
1249 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
1250 Diag(Tok, diag::err_expected) << tok::identifier;
1253 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1255 // Parse the (optional) class name or simple-template-id.
1256 IdentifierInfo *Name = nullptr;
1257 SourceLocation NameLoc;
1258 TemplateIdAnnotation *TemplateId = nullptr;
1259 if (Tok.is(tok::identifier)) {
1260 Name = Tok.getIdentifierInfo();
1261 NameLoc = ConsumeToken();
1263 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1264 // The name was supposed to refer to a template, but didn't.
1265 // Eat the template argument list and try to continue parsing this as
1266 // a class (or template thereof).
1267 TemplateArgList TemplateArgs;
1268 SourceLocation LAngleLoc, RAngleLoc;
1269 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1271 TemplateArgs, RAngleLoc)) {
1272 // We couldn't parse the template argument list at all, so don't
1273 // try to give any location information for the list.
1274 LAngleLoc = RAngleLoc = SourceLocation();
1277 Diag(NameLoc, diag::err_explicit_spec_non_template)
1278 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1279 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1281 // Strip off the last template parameter list if it was empty, since
1282 // we've removed its template argument list.
1283 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1284 if (TemplateParams && TemplateParams->size() > 1) {
1285 TemplateParams->pop_back();
1287 TemplateParams = nullptr;
1288 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1289 = ParsedTemplateInfo::NonTemplate;
1291 } else if (TemplateInfo.Kind
1292 == ParsedTemplateInfo::ExplicitInstantiation) {
1293 // Pretend this is just a forward declaration.
1294 TemplateParams = nullptr;
1295 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1296 = ParsedTemplateInfo::NonTemplate;
1297 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1299 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1303 } else if (Tok.is(tok::annot_template_id)) {
1304 TemplateId = takeTemplateIdAnnotation(Tok);
1305 NameLoc = ConsumeToken();
1307 if (TemplateId->Kind != TNK_Type_template &&
1308 TemplateId->Kind != TNK_Dependent_template_name) {
1309 // The template-name in the simple-template-id refers to
1310 // something other than a class template. Give an appropriate
1311 // error message and skip to the ';'.
1312 SourceRange Range(NameLoc);
1313 if (SS.isNotEmpty())
1314 Range.setBegin(SS.getBeginLoc());
1316 // FIXME: Name may be null here.
1317 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1318 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1320 DS.SetTypeSpecError();
1321 SkipUntil(tok::semi, StopBeforeMatch);
1326 // There are four options here.
1327 // - If we are in a trailing return type, this is always just a reference,
1328 // and we must not try to parse a definition. For instance,
1329 // [] () -> struct S { };
1330 // does not define a type.
1331 // - If we have 'struct foo {...', 'struct foo :...',
1332 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1333 // - If we have 'struct foo;', then this is either a forward declaration
1334 // or a friend declaration, which have to be treated differently.
1335 // - Otherwise we have something like 'struct foo xyz', a reference.
1337 // We also detect these erroneous cases to provide better diagnostic for
1338 // C++11 attributes parsing.
1339 // - attributes follow class name:
1340 // struct foo [[]] {};
1341 // - attributes appear before or after 'final':
1342 // struct foo [[]] final [[]] {};
1344 // However, in type-specifier-seq's, things look like declarations but are
1345 // just references, e.g.
1348 // &T::operator struct s;
1349 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
1351 // If there are attributes after class name, parse them.
1352 MaybeParseCXX11Attributes(Attributes);
1354 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1355 Sema::TagUseKind TUK;
1356 if (DSC == DSC_trailing)
1357 TUK = Sema::TUK_Reference;
1358 else if (Tok.is(tok::l_brace) ||
1359 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1360 (isCXX11FinalKeyword() &&
1361 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1362 if (DS.isFriendSpecified()) {
1363 // C++ [class.friend]p2:
1364 // A class shall not be defined in a friend declaration.
1365 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1366 << SourceRange(DS.getFriendSpecLoc());
1368 // Skip everything up to the semicolon, so that this looks like a proper
1369 // friend class (or template thereof) declaration.
1370 SkipUntil(tok::semi, StopBeforeMatch);
1371 TUK = Sema::TUK_Friend;
1373 // Okay, this is a class definition.
1374 TUK = Sema::TUK_Definition;
1376 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1377 NextToken().is(tok::kw_alignas))) {
1378 // We can't tell if this is a definition or reference
1379 // until we skipped the 'final' and C++11 attribute specifiers.
1380 TentativeParsingAction PA(*this);
1382 // Skip the 'final' keyword.
1385 // Skip C++11 attribute specifiers.
1387 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1389 if (!SkipUntil(tok::r_square, StopAtSemi))
1391 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1394 if (!SkipUntil(tok::r_paren, StopAtSemi))
1401 if (Tok.is(tok::l_brace) || Tok.is(tok::colon))
1402 TUK = Sema::TUK_Definition;
1404 TUK = Sema::TUK_Reference;
1407 } else if (!isTypeSpecifier(DSC) &&
1408 (Tok.is(tok::semi) ||
1409 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1410 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1411 if (Tok.isNot(tok::semi)) {
1412 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1413 // A semicolon was missing after this declaration. Diagnose and recover.
1414 ExpectAndConsume(tok::semi, diag::err_expected_after,
1415 DeclSpec::getSpecifierName(TagType, PPol));
1417 Tok.setKind(tok::semi);
1420 TUK = Sema::TUK_Reference;
1422 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1423 // to caller to handle.
1424 if (TUK != Sema::TUK_Reference) {
1425 // If this is not a reference, then the only possible
1426 // valid place for C++11 attributes to appear here
1427 // is between class-key and class-name. If there are
1428 // any attributes after class-name, we try a fixit to move
1429 // them to the right place.
1430 SourceRange AttrRange = Attributes.Range;
1431 if (AttrRange.isValid()) {
1432 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1434 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1435 CharSourceRange(AttrRange, true))
1436 << FixItHint::CreateRemoval(AttrRange);
1438 // Recover by adding misplaced attributes to the attribute list
1439 // of the class so they can be applied on the class later.
1440 attrs.takeAllFrom(Attributes);
1444 // If this is an elaborated type specifier, and we delayed
1445 // diagnostics before, just merge them into the current pool.
1446 if (shouldDelayDiagsInTag) {
1447 diagsFromTag.done();
1448 if (TUK == Sema::TUK_Reference)
1449 diagsFromTag.redelay();
1452 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1453 TUK != Sema::TUK_Definition)) {
1454 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1455 // We have a declaration or reference to an anonymous class.
1456 Diag(StartLoc, diag::err_anon_type_definition)
1457 << DeclSpec::getSpecifierName(TagType, Policy);
1460 // If we are parsing a definition and stop at a base-clause, continue on
1461 // until the semicolon. Continuing from the comma will just trick us into
1462 // thinking we are seeing a variable declaration.
1463 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1464 SkipUntil(tok::semi, StopBeforeMatch);
1466 SkipUntil(tok::comma, StopAtSemi);
1470 // Create the tag portion of the class or class template.
1471 DeclResult TagOrTempResult = true; // invalid
1472 TypeResult TypeResult = true; // invalid
1476 // Explicit specialization, class template partial specialization,
1477 // or explicit instantiation.
1478 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1479 TemplateId->NumArgs);
1480 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1481 TUK == Sema::TUK_Declaration) {
1482 // This is an explicit instantiation of a class template.
1483 ProhibitAttributes(attrs);
1486 = Actions.ActOnExplicitInstantiation(getCurScope(),
1487 TemplateInfo.ExternLoc,
1488 TemplateInfo.TemplateLoc,
1492 TemplateId->Template,
1493 TemplateId->TemplateNameLoc,
1494 TemplateId->LAngleLoc,
1496 TemplateId->RAngleLoc,
1499 // Friend template-ids are treated as references unless
1500 // they have template headers, in which case they're ill-formed
1501 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1502 // We diagnose this error in ActOnClassTemplateSpecialization.
1503 } else if (TUK == Sema::TUK_Reference ||
1504 (TUK == Sema::TUK_Friend &&
1505 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1506 ProhibitAttributes(attrs);
1507 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1509 TemplateId->TemplateKWLoc,
1510 TemplateId->Template,
1511 TemplateId->TemplateNameLoc,
1512 TemplateId->LAngleLoc,
1514 TemplateId->RAngleLoc);
1516 // This is an explicit specialization or a class template
1517 // partial specialization.
1518 TemplateParameterLists FakedParamLists;
1519 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1520 // This looks like an explicit instantiation, because we have
1523 // template class Foo<X>
1525 // but it actually has a definition. Most likely, this was
1526 // meant to be an explicit specialization, but the user forgot
1527 // the '<>' after 'template'.
1528 // It this is friend declaration however, since it cannot have a
1529 // template header, it is most likely that the user meant to
1530 // remove the 'template' keyword.
1531 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1532 "Expected a definition here");
1534 if (TUK == Sema::TUK_Friend) {
1535 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1536 TemplateParams = nullptr;
1538 SourceLocation LAngleLoc =
1539 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1540 Diag(TemplateId->TemplateNameLoc,
1541 diag::err_explicit_instantiation_with_definition)
1542 << SourceRange(TemplateInfo.TemplateLoc)
1543 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1545 // Create a fake template parameter list that contains only
1546 // "template<>", so that we treat this construct as a class
1547 // template specialization.
1548 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1549 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
1551 TemplateParams = &FakedParamLists;
1555 // Build the class template specialization.
1556 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1557 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1558 *TemplateId, attrs.getList(),
1559 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1561 TemplateParams ? TemplateParams->size() : 0));
1563 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1564 TUK == Sema::TUK_Declaration) {
1565 // Explicit instantiation of a member of a class template
1566 // specialization, e.g.,
1568 // template struct Outer<int>::Inner;
1570 ProhibitAttributes(attrs);
1573 = Actions.ActOnExplicitInstantiation(getCurScope(),
1574 TemplateInfo.ExternLoc,
1575 TemplateInfo.TemplateLoc,
1576 TagType, StartLoc, SS, Name,
1577 NameLoc, attrs.getList());
1578 } else if (TUK == Sema::TUK_Friend &&
1579 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1580 ProhibitAttributes(attrs);
1583 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1584 TagType, StartLoc, SS,
1585 Name, NameLoc, attrs.getList(),
1586 MultiTemplateParamsArg(
1587 TemplateParams? &(*TemplateParams)[0]
1589 TemplateParams? TemplateParams->size() : 0));
1591 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1592 ProhibitAttributes(attrs);
1594 if (TUK == Sema::TUK_Definition &&
1595 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1596 // If the declarator-id is not a template-id, issue a diagnostic and
1597 // recover by ignoring the 'template' keyword.
1598 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1599 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1600 TemplateParams = nullptr;
1603 bool IsDependent = false;
1605 // Don't pass down template parameter lists if this is just a tag
1606 // reference. For example, we don't need the template parameters here:
1607 // template <class T> class A *makeA(T t);
1608 MultiTemplateParamsArg TParams;
1609 if (TUK != Sema::TUK_Reference && TemplateParams)
1611 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1613 // Declaration or definition of a class type
1614 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1615 SS, Name, NameLoc, attrs.getList(), AS,
1616 DS.getModulePrivateSpecLoc(),
1617 TParams, Owned, IsDependent,
1618 SourceLocation(), false,
1619 clang::TypeResult(),
1620 DSC == DSC_type_specifier);
1622 // If ActOnTag said the type was dependent, try again with the
1623 // less common call.
1625 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1626 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1627 SS, Name, StartLoc, NameLoc);
1631 // If there is a body, parse it and inform the actions module.
1632 if (TUK == Sema::TUK_Definition) {
1633 assert(Tok.is(tok::l_brace) ||
1634 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1635 isCXX11FinalKeyword());
1636 if (getLangOpts().CPlusPlus)
1637 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1638 TagOrTempResult.get());
1640 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1643 const char *PrevSpec = nullptr;
1646 if (!TypeResult.isInvalid()) {
1647 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1648 NameLoc.isValid() ? NameLoc : StartLoc,
1649 PrevSpec, DiagID, TypeResult.get(), Policy);
1650 } else if (!TagOrTempResult.isInvalid()) {
1651 Result = DS.SetTypeSpecType(TagType, StartLoc,
1652 NameLoc.isValid() ? NameLoc : StartLoc,
1653 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1656 DS.SetTypeSpecError();
1661 Diag(StartLoc, DiagID) << PrevSpec;
1663 // At this point, we've successfully parsed a class-specifier in 'definition'
1664 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1665 // going to look at what comes after it to improve error recovery. If an
1666 // impossible token occurs next, we assume that the programmer forgot a ; at
1667 // the end of the declaration and recover that way.
1669 // Also enforce C++ [temp]p3:
1670 // In a template-declaration which defines a class, no declarator
1672 if (TUK == Sema::TUK_Definition &&
1673 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1674 if (Tok.isNot(tok::semi)) {
1675 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1676 ExpectAndConsume(tok::semi, diag::err_expected_after,
1677 DeclSpec::getSpecifierName(TagType, PPol));
1678 // Push this token back into the preprocessor and change our current token
1679 // to ';' so that the rest of the code recovers as though there were an
1680 // ';' after the definition.
1682 Tok.setKind(tok::semi);
1687 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1689 /// base-clause : [C++ class.derived]
1690 /// ':' base-specifier-list
1691 /// base-specifier-list:
1692 /// base-specifier '...'[opt]
1693 /// base-specifier-list ',' base-specifier '...'[opt]
1694 void Parser::ParseBaseClause(Decl *ClassDecl) {
1695 assert(Tok.is(tok::colon) && "Not a base clause");
1698 // Build up an array of parsed base specifiers.
1699 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1702 // Parse a base-specifier.
1703 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1704 if (Result.isInvalid()) {
1705 // Skip the rest of this base specifier, up until the comma or
1707 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
1709 // Add this to our array of base specifiers.
1710 BaseInfo.push_back(Result.get());
1713 // If the next token is a comma, consume it and keep reading
1715 if (!TryConsumeToken(tok::comma))
1719 // Attach the base specifiers
1720 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1723 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1724 /// one entry in the base class list of a class specifier, for example:
1725 /// class foo : public bar, virtual private baz {
1726 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1728 /// base-specifier: [C++ class.derived]
1729 /// attribute-specifier-seq[opt] base-type-specifier
1730 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
1731 /// base-type-specifier
1732 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
1733 /// base-type-specifier
1734 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1735 bool IsVirtual = false;
1736 SourceLocation StartLoc = Tok.getLocation();
1738 ParsedAttributesWithRange Attributes(AttrFactory);
1739 MaybeParseCXX11Attributes(Attributes);
1741 // Parse the 'virtual' keyword.
1742 if (TryConsumeToken(tok::kw_virtual))
1745 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1747 // Parse an (optional) access specifier.
1748 AccessSpecifier Access = getAccessSpecifierIfPresent();
1749 if (Access != AS_none)
1752 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1754 // Parse the 'virtual' keyword (again!), in case it came after the
1755 // access specifier.
1756 if (Tok.is(tok::kw_virtual)) {
1757 SourceLocation VirtualLoc = ConsumeToken();
1759 // Complain about duplicate 'virtual'
1760 Diag(VirtualLoc, diag::err_dup_virtual)
1761 << FixItHint::CreateRemoval(VirtualLoc);
1767 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1769 // Parse the class-name.
1770 SourceLocation EndLocation;
1771 SourceLocation BaseLoc;
1772 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1773 if (BaseType.isInvalid())
1776 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1777 // actually part of the base-specifier-list grammar productions, but we
1778 // parse it here for convenience.
1779 SourceLocation EllipsisLoc;
1780 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1782 // Find the complete source range for the base-specifier.
1783 SourceRange Range(StartLoc, EndLocation);
1785 // Notify semantic analysis that we have parsed a complete
1787 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
1788 Access, BaseType.get(), BaseLoc,
1792 /// getAccessSpecifierIfPresent - Determine whether the next token is
1793 /// a C++ access-specifier.
1795 /// access-specifier: [C++ class.derived]
1799 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1800 switch (Tok.getKind()) {
1801 default: return AS_none;
1802 case tok::kw_private: return AS_private;
1803 case tok::kw_protected: return AS_protected;
1804 case tok::kw_public: return AS_public;
1808 /// \brief If the given declarator has any parts for which parsing has to be
1809 /// delayed, e.g., default arguments, create a late-parsed method declaration
1810 /// record to handle the parsing at the end of the class definition.
1811 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1813 // We just declared a member function. If this member function
1814 // has any default arguments, we'll need to parse them later.
1815 LateParsedMethodDeclaration *LateMethod = nullptr;
1816 DeclaratorChunk::FunctionTypeInfo &FTI
1817 = DeclaratorInfo.getFunctionTypeInfo();
1819 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
1820 if (LateMethod || FTI.Params[ParamIdx].DefaultArgTokens) {
1822 // Push this method onto the stack of late-parsed method
1824 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1825 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1826 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1828 // Add all of the parameters prior to this one (they don't
1829 // have default arguments).
1830 LateMethod->DefaultArgs.reserve(FTI.NumParams);
1831 for (unsigned I = 0; I < ParamIdx; ++I)
1832 LateMethod->DefaultArgs.push_back(
1833 LateParsedDefaultArgument(FTI.Params[I].Param));
1836 // Add this parameter to the list of parameters (it may or may
1837 // not have a default argument).
1838 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
1839 FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
1844 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
1850 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
1851 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
1852 return VirtSpecifiers::VS_None;
1854 IdentifierInfo *II = Tok.getIdentifierInfo();
1856 // Initialize the contextual keywords.
1858 Ident_final = &PP.getIdentifierTable().get("final");
1859 if (getLangOpts().MicrosoftExt)
1860 Ident_sealed = &PP.getIdentifierTable().get("sealed");
1861 Ident_override = &PP.getIdentifierTable().get("override");
1864 if (II == Ident_override)
1865 return VirtSpecifiers::VS_Override;
1867 if (II == Ident_sealed)
1868 return VirtSpecifiers::VS_Sealed;
1870 if (II == Ident_final)
1871 return VirtSpecifiers::VS_Final;
1873 return VirtSpecifiers::VS_None;
1876 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
1878 /// virt-specifier-seq:
1880 /// virt-specifier-seq virt-specifier
1881 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
1884 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
1885 if (Specifier == VirtSpecifiers::VS_None)
1888 // C++ [class.mem]p8:
1889 // A virt-specifier-seq shall contain at most one of each virt-specifier.
1890 const char *PrevSpec = nullptr;
1891 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
1892 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
1894 << FixItHint::CreateRemoval(Tok.getLocation());
1896 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
1897 Specifier == VirtSpecifiers::VS_Sealed)) {
1898 Diag(Tok.getLocation(), diag::err_override_control_interface)
1899 << VirtSpecifiers::getSpecifierName(Specifier);
1900 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
1901 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
1903 Diag(Tok.getLocation(),
1904 getLangOpts().CPlusPlus11
1905 ? diag::warn_cxx98_compat_override_control_keyword
1906 : diag::ext_override_control_keyword)
1907 << VirtSpecifiers::getSpecifierName(Specifier);
1913 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
1914 /// 'final' or Microsoft 'sealed' contextual keyword.
1915 bool Parser::isCXX11FinalKeyword() const {
1916 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
1917 return Specifier == VirtSpecifiers::VS_Final ||
1918 Specifier == VirtSpecifiers::VS_Sealed;
1921 /// \brief Parse a C++ member-declarator up to, but not including, the optional
1922 /// brace-or-equal-initializer or pure-specifier.
1923 void Parser::ParseCXXMemberDeclaratorBeforeInitializer(
1924 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
1925 LateParsedAttrList &LateParsedAttrs) {
1926 // member-declarator:
1927 // declarator pure-specifier[opt]
1928 // declarator brace-or-equal-initializer[opt]
1929 // identifier[opt] ':' constant-expression
1930 if (Tok.isNot(tok::colon))
1931 ParseDeclarator(DeclaratorInfo);
1933 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
1934 BitfieldSize = ParseConstantExpression();
1935 if (BitfieldSize.isInvalid())
1936 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
1938 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface);
1940 // If a simple-asm-expr is present, parse it.
1941 if (Tok.is(tok::kw_asm)) {
1943 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1944 if (AsmLabel.isInvalid())
1945 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
1947 DeclaratorInfo.setAsmLabel(AsmLabel.get());
1948 DeclaratorInfo.SetRangeEnd(Loc);
1951 // If attributes exist after the declarator, but before an '{', parse them.
1952 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
1954 // For compatibility with code written to older Clang, also accept a
1955 // virt-specifier *after* the GNU attributes.
1956 // FIXME: If we saw any attributes that are known to GCC followed by a
1957 // virt-specifier, issue a GCC-compat warning.
1958 if (BitfieldSize.isUnset() && VS.isUnset())
1959 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface);
1962 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1964 /// member-declaration:
1965 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
1966 /// function-definition ';'[opt]
1967 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1968 /// using-declaration [TODO]
1969 /// [C++0x] static_assert-declaration
1970 /// template-declaration
1971 /// [GNU] '__extension__' member-declaration
1973 /// member-declarator-list:
1974 /// member-declarator
1975 /// member-declarator-list ',' member-declarator
1977 /// member-declarator:
1978 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
1979 /// declarator constant-initializer[opt]
1980 /// [C++11] declarator brace-or-equal-initializer[opt]
1981 /// identifier[opt] ':' constant-expression
1983 /// virt-specifier-seq:
1985 /// virt-specifier-seq virt-specifier
1995 /// constant-initializer:
1996 /// '=' constant-expression
1998 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1999 AttributeList *AccessAttrs,
2000 const ParsedTemplateInfo &TemplateInfo,
2001 ParsingDeclRAIIObject *TemplateDiags) {
2002 if (Tok.is(tok::at)) {
2003 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2004 Diag(Tok, diag::err_at_defs_cxx);
2006 Diag(Tok, diag::err_at_in_class);
2009 SkipUntil(tok::r_brace, StopAtSemi);
2013 // Turn on colon protection early, while parsing declspec, although there is
2014 // nothing to protect there. It prevents from false errors if error recovery
2015 // incorrectly determines where the declspec ends, as in the example:
2016 // struct A { enum class B { C }; };
2018 // struct D { A::B : C; };
2019 ColonProtectionRAIIObject X(*this);
2021 // Access declarations.
2022 bool MalformedTypeSpec = false;
2023 if (!TemplateInfo.Kind &&
2024 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) {
2025 if (TryAnnotateCXXScopeToken())
2026 MalformedTypeSpec = true;
2029 if (Tok.isNot(tok::annot_cxxscope))
2030 isAccessDecl = false;
2031 else if (NextToken().is(tok::identifier))
2032 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2034 isAccessDecl = NextToken().is(tok::kw_operator);
2037 // Collect the scope specifier token we annotated earlier.
2039 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
2040 /*EnteringContext=*/false);
2042 // Try to parse an unqualified-id.
2043 SourceLocation TemplateKWLoc;
2045 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
2046 TemplateKWLoc, Name)) {
2047 SkipUntil(tok::semi);
2051 // TODO: recover from mistakenly-qualified operator declarations.
2052 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2053 "access declaration")) {
2054 SkipUntil(tok::semi);
2058 Actions.ActOnUsingDeclaration(getCurScope(), AS,
2059 /* HasUsingKeyword */ false,
2062 /* AttrList */ nullptr,
2063 /* HasTypenameKeyword */ false,
2069 // static_assert-declaration
2070 if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) {
2071 // FIXME: Check for templates
2072 SourceLocation DeclEnd;
2073 ParseStaticAssertDeclaration(DeclEnd);
2077 if (Tok.is(tok::kw_template)) {
2078 assert(!TemplateInfo.TemplateParams &&
2079 "Nested template improperly parsed?");
2080 SourceLocation DeclEnd;
2081 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
2086 // Handle: member-declaration ::= '__extension__' member-declaration
2087 if (Tok.is(tok::kw___extension__)) {
2088 // __extension__ silences extension warnings in the subexpression.
2089 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2091 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2092 TemplateInfo, TemplateDiags);
2095 ParsedAttributesWithRange attrs(AttrFactory);
2096 ParsedAttributesWithRange FnAttrs(AttrFactory);
2097 // Optional C++11 attribute-specifier
2098 MaybeParseCXX11Attributes(attrs);
2099 // We need to keep these attributes for future diagnostic
2100 // before they are taken over by declaration specifier.
2101 FnAttrs.addAll(attrs.getList());
2102 FnAttrs.Range = attrs.Range;
2104 MaybeParseMicrosoftAttributes(attrs);
2106 if (Tok.is(tok::kw_using)) {
2107 ProhibitAttributes(attrs);
2110 SourceLocation UsingLoc = ConsumeToken();
2112 if (Tok.is(tok::kw_namespace)) {
2113 Diag(UsingLoc, diag::err_using_namespace_in_class);
2114 SkipUntil(tok::semi, StopBeforeMatch);
2116 SourceLocation DeclEnd;
2117 // Otherwise, it must be a using-declaration or an alias-declaration.
2118 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2119 UsingLoc, DeclEnd, AS);
2124 // Hold late-parsed attributes so we can attach a Decl to them later.
2125 LateParsedAttrList CommonLateParsedAttrs;
2127 // decl-specifier-seq:
2128 // Parse the common declaration-specifiers piece.
2129 ParsingDeclSpec DS(*this, TemplateDiags);
2130 DS.takeAttributesFrom(attrs);
2131 if (MalformedTypeSpec)
2132 DS.SetTypeSpecError();
2134 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2135 &CommonLateParsedAttrs);
2137 // Turn off colon protection that was set for declspec.
2140 // If we had a free-standing type definition with a missing semicolon, we
2141 // may get this far before the problem becomes obvious.
2142 if (DS.hasTagDefinition() &&
2143 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2144 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2145 &CommonLateParsedAttrs))
2148 MultiTemplateParamsArg TemplateParams(
2149 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2151 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2153 if (TryConsumeToken(tok::semi)) {
2154 if (DS.isFriendSpecified())
2155 ProhibitAttributes(FnAttrs);
2158 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
2159 DS.complete(TheDecl);
2163 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2166 // Hold late-parsed attributes so we can attach a Decl to them later.
2167 LateParsedAttrList LateParsedAttrs;
2169 SourceLocation EqualLoc;
2170 bool HasInitializer = false;
2173 SmallVector<Decl *, 8> DeclsInGroup;
2174 ExprResult BitfieldSize;
2175 bool ExpectSemi = true;
2177 // Parse the first declarator.
2178 ParseCXXMemberDeclaratorBeforeInitializer(DeclaratorInfo, VS, BitfieldSize,
2181 // If this has neither a name nor a bit width, something has gone seriously
2182 // wrong. Skip until the semi-colon or }.
2183 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2184 // If so, skip until the semi-colon or a }.
2185 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2186 TryConsumeToken(tok::semi);
2190 // Check for a member function definition.
2191 if (BitfieldSize.isUnset()) {
2192 // MSVC permits pure specifier on inline functions defined at class scope.
2193 // Hence check for =0 before checking for function definition.
2194 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
2195 DeclaratorInfo.isFunctionDeclarator() &&
2196 NextToken().is(tok::numeric_constant)) {
2197 EqualLoc = ConsumeToken();
2198 Init = ParseInitializer();
2199 if (Init.isInvalid())
2200 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2202 HasInitializer = true;
2205 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2206 // function-definition:
2208 // In C++11, a non-function declarator followed by an open brace is a
2209 // braced-init-list for an in-class member initialization, not an
2210 // erroneous function definition.
2211 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2212 DefinitionKind = FDK_Definition;
2213 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2214 if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
2215 DefinitionKind = FDK_Definition;
2216 } else if (Tok.is(tok::equal)) {
2217 const Token &KW = NextToken();
2218 if (KW.is(tok::kw_default))
2219 DefinitionKind = FDK_Defaulted;
2220 else if (KW.is(tok::kw_delete))
2221 DefinitionKind = FDK_Deleted;
2225 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2226 // to a friend declaration, that declaration shall be a definition.
2227 if (DeclaratorInfo.isFunctionDeclarator() &&
2228 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2229 // Diagnose attributes that appear before decl specifier:
2230 // [[]] friend int foo();
2231 ProhibitAttributes(FnAttrs);
2234 if (DefinitionKind) {
2235 if (!DeclaratorInfo.isFunctionDeclarator()) {
2236 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2238 SkipUntil(tok::r_brace);
2240 // Consume the optional ';'
2241 TryConsumeToken(tok::semi);
2246 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2247 Diag(DeclaratorInfo.getIdentifierLoc(),
2248 diag::err_function_declared_typedef);
2250 // Recover by treating the 'typedef' as spurious.
2251 DS.ClearStorageClassSpecs();
2255 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2256 VS, DefinitionKind, Init);
2259 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2260 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2262 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2263 LateParsedAttrs[i]->addDecl(FunDecl);
2266 LateParsedAttrs.clear();
2268 // Consume the ';' - it's optional unless we have a delete or default
2269 if (Tok.is(tok::semi))
2270 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2276 // member-declarator-list:
2277 // member-declarator
2278 // member-declarator-list ',' member-declarator
2281 InClassInitStyle HasInClassInit = ICIS_NoInit;
2282 if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
2283 if (BitfieldSize.get()) {
2284 Diag(Tok, diag::err_bitfield_member_init);
2285 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2287 HasInitializer = true;
2288 if (!DeclaratorInfo.isDeclarationOfFunction() &&
2289 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2290 != DeclSpec::SCS_typedef)
2291 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2295 // NOTE: If Sema is the Action module and declarator is an instance field,
2296 // this call will *not* return the created decl; It will return null.
2297 // See Sema::ActOnCXXMemberDeclarator for details.
2299 NamedDecl *ThisDecl = nullptr;
2300 if (DS.isFriendSpecified()) {
2301 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2302 // to a friend declaration, that declaration shall be a definition.
2304 // Diagnose attributes that appear in a friend member function declarator:
2305 // friend int foo [[]] ();
2306 SmallVector<SourceRange, 4> Ranges;
2307 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2308 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2309 E = Ranges.end(); I != E; ++I)
2310 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2312 // TODO: handle initializers, VS, bitfields, 'delete'
2313 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2316 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2320 VS, HasInClassInit);
2322 if (VarTemplateDecl *VT =
2323 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2324 // Re-direct this decl to refer to the templated decl so that we can
2326 ThisDecl = VT->getTemplatedDecl();
2328 if (ThisDecl && AccessAttrs)
2329 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2332 // Handle the initializer.
2333 if (HasInClassInit != ICIS_NoInit &&
2334 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2335 DeclSpec::SCS_static) {
2336 // The initializer was deferred; parse it and cache the tokens.
2337 Diag(Tok, getLangOpts().CPlusPlus11
2338 ? diag::warn_cxx98_compat_nonstatic_member_init
2339 : diag::ext_nonstatic_member_init);
2341 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2342 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2343 // declarator is followed by an initializer.
2345 // A brace-or-equal-initializer for a member-declarator is not an
2346 // initializer in the grammar, so this is ill-formed.
2347 Diag(Tok, diag::err_incomplete_array_member_init);
2348 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2350 // Avoid later warnings about a class member of incomplete type.
2352 ThisDecl->setInvalidDecl();
2354 ParseCXXNonStaticMemberInitializer(ThisDecl);
2355 } else if (HasInitializer) {
2356 // Normal initializer.
2357 if (!Init.isUsable())
2358 Init = ParseCXXMemberInitializer(
2359 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2361 if (Init.isInvalid())
2362 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2364 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2365 DS.containsPlaceholderType());
2366 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2368 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
2371 if (!ThisDecl->isInvalidDecl()) {
2372 // Set the Decl for any late parsed attributes
2373 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2374 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2376 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2377 LateParsedAttrs[i]->addDecl(ThisDecl);
2379 Actions.FinalizeDeclaration(ThisDecl);
2380 DeclsInGroup.push_back(ThisDecl);
2382 if (DeclaratorInfo.isFunctionDeclarator() &&
2383 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2384 DeclSpec::SCS_typedef)
2385 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2387 LateParsedAttrs.clear();
2389 DeclaratorInfo.complete(ThisDecl);
2391 // If we don't have a comma, it is either the end of the list (a ';')
2392 // or an error, bail out.
2393 SourceLocation CommaLoc;
2394 if (!TryConsumeToken(tok::comma, CommaLoc))
2397 if (Tok.isAtStartOfLine() &&
2398 !MightBeDeclarator(Declarator::MemberContext)) {
2399 // This comma was followed by a line-break and something which can't be
2400 // the start of a declarator. The comma was probably a typo for a
2402 Diag(CommaLoc, diag::err_expected_semi_declaration)
2403 << FixItHint::CreateReplacement(CommaLoc, ";");
2408 // Parse the next declarator.
2409 DeclaratorInfo.clear();
2411 BitfieldSize = true;
2413 HasInitializer = false;
2414 DeclaratorInfo.setCommaLoc(CommaLoc);
2416 // GNU attributes are allowed before the second and subsequent declarator.
2417 MaybeParseGNUAttributes(DeclaratorInfo);
2419 ParseCXXMemberDeclaratorBeforeInitializer(DeclaratorInfo, VS, BitfieldSize,
2424 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2425 // Skip to end of block or statement.
2426 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2427 // If we stopped at a ';', eat it.
2428 TryConsumeToken(tok::semi);
2432 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2435 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
2436 /// pure-specifier. Also detect and reject any attempted defaulted/deleted
2437 /// function definition. The location of the '=', if any, will be placed in
2443 /// brace-or-equal-initializer:
2444 /// '=' initializer-expression
2445 /// braced-init-list
2447 /// initializer-clause:
2448 /// assignment-expression
2449 /// braced-init-list
2451 /// defaulted/deleted function-definition:
2455 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2456 /// be a constant-expression.
2457 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2458 SourceLocation &EqualLoc) {
2459 assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
2460 && "Data member initializer not starting with '=' or '{'");
2462 EnterExpressionEvaluationContext Context(Actions,
2463 Sema::PotentiallyEvaluated,
2465 if (TryConsumeToken(tok::equal, EqualLoc)) {
2466 if (Tok.is(tok::kw_delete)) {
2467 // In principle, an initializer of '= delete p;' is legal, but it will
2468 // never type-check. It's better to diagnose it as an ill-formed expression
2469 // than as an ill-formed deleted non-function member.
2470 // An initializer of '= delete p, foo' will never be parsed, because
2471 // a top-level comma always ends the initializer expression.
2472 const Token &Next = NextToken();
2473 if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) ||
2474 Next.is(tok::eof)) {
2476 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2479 Diag(ConsumeToken(), diag::err_deleted_non_function);
2482 } else if (Tok.is(tok::kw_default)) {
2484 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2487 Diag(ConsumeToken(), diag::err_default_special_members);
2492 return ParseInitializer();
2495 /// ParseCXXMemberSpecification - Parse the class definition.
2497 /// member-specification:
2498 /// member-declaration member-specification[opt]
2499 /// access-specifier ':' member-specification[opt]
2501 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2502 SourceLocation AttrFixitLoc,
2503 ParsedAttributesWithRange &Attrs,
2504 unsigned TagType, Decl *TagDecl) {
2505 assert((TagType == DeclSpec::TST_struct ||
2506 TagType == DeclSpec::TST_interface ||
2507 TagType == DeclSpec::TST_union ||
2508 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2510 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2511 "parsing struct/union/class body");
2513 // Determine whether this is a non-nested class. Note that local
2514 // classes are *not* considered to be nested classes.
2515 bool NonNestedClass = true;
2516 if (!ClassStack.empty()) {
2517 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2518 if (S->isClassScope()) {
2519 // We're inside a class scope, so this is a nested class.
2520 NonNestedClass = false;
2522 // The Microsoft extension __interface does not permit nested classes.
2523 if (getCurrentClass().IsInterface) {
2524 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2526 << (isa<NamedDecl>(TagDecl)
2527 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2533 if ((S->getFlags() & Scope::FnScope)) {
2534 // If we're in a function or function template declared in the
2535 // body of a class, then this is a local class rather than a
2537 const Scope *Parent = S->getParent();
2538 if (Parent->isTemplateParamScope())
2539 Parent = Parent->getParent();
2540 if (Parent->isClassScope())
2546 // Enter a scope for the class.
2547 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2549 // Note that we are parsing a new (potentially-nested) class definition.
2550 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2551 TagType == DeclSpec::TST_interface);
2554 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2556 SourceLocation FinalLoc;
2557 bool IsFinalSpelledSealed = false;
2559 // Parse the optional 'final' keyword.
2560 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2561 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2562 assert((Specifier == VirtSpecifiers::VS_Final ||
2563 Specifier == VirtSpecifiers::VS_Sealed) &&
2564 "not a class definition");
2565 FinalLoc = ConsumeToken();
2566 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
2568 if (TagType == DeclSpec::TST_interface)
2569 Diag(FinalLoc, diag::err_override_control_interface)
2570 << VirtSpecifiers::getSpecifierName(Specifier);
2571 else if (Specifier == VirtSpecifiers::VS_Final)
2572 Diag(FinalLoc, getLangOpts().CPlusPlus11
2573 ? diag::warn_cxx98_compat_override_control_keyword
2574 : diag::ext_override_control_keyword)
2575 << VirtSpecifiers::getSpecifierName(Specifier);
2576 else if (Specifier == VirtSpecifiers::VS_Sealed)
2577 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
2579 // Parse any C++11 attributes after 'final' keyword.
2580 // These attributes are not allowed to appear here,
2581 // and the only possible place for them to appertain
2582 // to the class would be between class-key and class-name.
2583 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2586 if (Tok.is(tok::colon)) {
2587 ParseBaseClause(TagDecl);
2589 if (!Tok.is(tok::l_brace)) {
2590 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
2593 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2598 assert(Tok.is(tok::l_brace));
2599 BalancedDelimiterTracker T(*this, tok::l_brace);
2603 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2604 IsFinalSpelledSealed,
2605 T.getOpenLocation());
2607 // C++ 11p3: Members of a class defined with the keyword class are private
2608 // by default. Members of a class defined with the keywords struct or union
2609 // are public by default.
2610 AccessSpecifier CurAS;
2611 if (TagType == DeclSpec::TST_class)
2615 ParsedAttributes AccessAttrs(AttrFactory);
2618 // While we still have something to read, read the member-declarations.
2619 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2620 // Each iteration of this loop reads one member-declaration.
2622 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
2623 Tok.is(tok::kw___if_not_exists))) {
2624 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2628 // Check for extraneous top-level semicolon.
2629 if (Tok.is(tok::semi)) {
2630 ConsumeExtraSemi(InsideStruct, TagType);
2634 if (Tok.is(tok::annot_pragma_vis)) {
2635 HandlePragmaVisibility();
2639 if (Tok.is(tok::annot_pragma_pack)) {
2644 if (Tok.is(tok::annot_pragma_align)) {
2645 HandlePragmaAlign();
2649 if (Tok.is(tok::annot_pragma_openmp)) {
2650 ParseOpenMPDeclarativeDirective();
2654 if (Tok.is(tok::annot_pragma_ms_pointers_to_members)) {
2655 HandlePragmaMSPointersToMembers();
2659 if (Tok.is(tok::annot_pragma_ms_pragma)) {
2660 HandlePragmaMSPragma();
2664 // If we see a namespace here, a close brace was missing somewhere.
2665 if (Tok.is(tok::kw_namespace)) {
2666 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
2670 AccessSpecifier AS = getAccessSpecifierIfPresent();
2671 if (AS != AS_none) {
2672 // Current token is a C++ access specifier.
2674 SourceLocation ASLoc = Tok.getLocation();
2675 unsigned TokLength = Tok.getLength();
2677 AccessAttrs.clear();
2678 MaybeParseGNUAttributes(AccessAttrs);
2680 SourceLocation EndLoc;
2681 if (TryConsumeToken(tok::colon, EndLoc)) {
2682 } else if (TryConsumeToken(tok::semi, EndLoc)) {
2683 Diag(EndLoc, diag::err_expected)
2684 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
2686 EndLoc = ASLoc.getLocWithOffset(TokLength);
2687 Diag(EndLoc, diag::err_expected)
2688 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
2691 // The Microsoft extension __interface does not permit non-public
2692 // access specifiers.
2693 if (TagType == DeclSpec::TST_interface && CurAS != AS_public) {
2694 Diag(ASLoc, diag::err_access_specifier_interface)
2695 << (CurAS == AS_protected);
2698 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
2699 AccessAttrs.getList())) {
2700 // found another attribute than only annotations
2701 AccessAttrs.clear();
2707 // Parse all the comma separated declarators.
2708 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
2713 SkipUntil(tok::r_brace);
2716 // If attributes exist after class contents, parse them.
2717 ParsedAttributes attrs(AttrFactory);
2718 MaybeParseGNUAttributes(attrs);
2721 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
2722 T.getOpenLocation(),
2723 T.getCloseLocation(),
2726 // C++11 [class.mem]p2:
2727 // Within the class member-specification, the class is regarded as complete
2728 // within function bodies, default arguments, and
2729 // brace-or-equal-initializers for non-static data members (including such
2730 // things in nested classes).
2731 if (TagDecl && NonNestedClass) {
2732 // We are not inside a nested class. This class and its nested classes
2733 // are complete and we can parse the delayed portions of method
2734 // declarations and the lexed inline method definitions, along with any
2735 // delayed attributes.
2736 SourceLocation SavedPrevTokLocation = PrevTokLocation;
2737 ParseLexedAttributes(getCurrentClass());
2738 ParseLexedMethodDeclarations(getCurrentClass());
2740 // We've finished with all pending member declarations.
2741 Actions.ActOnFinishCXXMemberDecls();
2743 ParseLexedMemberInitializers(getCurrentClass());
2744 ParseLexedMethodDefs(getCurrentClass());
2745 PrevTokLocation = SavedPrevTokLocation;
2749 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
2750 T.getCloseLocation());
2752 // Leave the class scope.
2757 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
2758 assert(Tok.is(tok::kw_namespace));
2760 // FIXME: Suggest where the close brace should have gone by looking
2761 // at indentation changes within the definition body.
2762 Diag(D->getLocation(),
2763 diag::err_missing_end_of_definition) << D;
2764 Diag(Tok.getLocation(),
2765 diag::note_missing_end_of_definition_before) << D;
2767 // Push '};' onto the token stream to recover.
2771 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
2772 Tok.setKind(tok::semi);
2775 Tok.setKind(tok::r_brace);
2778 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
2779 /// which explicitly initializes the members or base classes of a
2780 /// class (C++ [class.base.init]). For example, the three initializers
2781 /// after the ':' in the Derived constructor below:
2785 /// class Derived : Base {
2789 /// Derived(float f) : Base(), x(17), f(f) { }
2793 /// [C++] ctor-initializer:
2794 /// ':' mem-initializer-list
2796 /// [C++] mem-initializer-list:
2797 /// mem-initializer ...[opt]
2798 /// mem-initializer ...[opt] , mem-initializer-list
2799 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
2800 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
2802 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers
2803 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
2804 SourceLocation ColonLoc = ConsumeToken();
2806 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
2807 bool AnyErrors = false;
2810 if (Tok.is(tok::code_completion)) {
2811 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
2813 return cutOffParsing();
2815 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
2816 if (!MemInit.isInvalid())
2817 MemInitializers.push_back(MemInit.get());
2822 if (Tok.is(tok::comma))
2824 else if (Tok.is(tok::l_brace))
2826 // If the next token looks like a base or member initializer, assume that
2827 // we're just missing a comma.
2828 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
2829 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2830 Diag(Loc, diag::err_ctor_init_missing_comma)
2831 << FixItHint::CreateInsertion(Loc, ", ");
2833 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2834 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
2836 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2841 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
2845 /// ParseMemInitializer - Parse a C++ member initializer, which is
2846 /// part of a constructor initializer that explicitly initializes one
2847 /// member or base class (C++ [class.base.init]). See
2848 /// ParseConstructorInitializer for an example.
2850 /// [C++] mem-initializer:
2851 /// mem-initializer-id '(' expression-list[opt] ')'
2852 /// [C++0x] mem-initializer-id braced-init-list
2854 /// [C++] mem-initializer-id:
2855 /// '::'[opt] nested-name-specifier[opt] class-name
2857 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
2858 // parse '::'[opt] nested-name-specifier[opt]
2860 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
2861 ParsedType TemplateTypeTy;
2862 if (Tok.is(tok::annot_template_id)) {
2863 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2864 if (TemplateId->Kind == TNK_Type_template ||
2865 TemplateId->Kind == TNK_Dependent_template_name) {
2866 AnnotateTemplateIdTokenAsType();
2867 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
2868 TemplateTypeTy = getTypeAnnotation(Tok);
2871 // Uses of decltype will already have been converted to annot_decltype by
2872 // ParseOptionalCXXScopeSpecifier at this point.
2873 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
2874 && Tok.isNot(tok::annot_decltype)) {
2875 Diag(Tok, diag::err_expected_member_or_base_name);
2879 IdentifierInfo *II = nullptr;
2880 DeclSpec DS(AttrFactory);
2881 SourceLocation IdLoc = Tok.getLocation();
2882 if (Tok.is(tok::annot_decltype)) {
2883 // Get the decltype expression, if there is one.
2884 ParseDecltypeSpecifier(DS);
2886 if (Tok.is(tok::identifier))
2887 // Get the identifier. This may be a member name or a class name,
2888 // but we'll let the semantic analysis determine which it is.
2889 II = Tok.getIdentifierInfo();
2895 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2896 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2898 ExprResult InitList = ParseBraceInitializer();
2899 if (InitList.isInvalid())
2902 SourceLocation EllipsisLoc;
2903 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2905 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2906 TemplateTypeTy, DS, IdLoc,
2907 InitList.get(), EllipsisLoc);
2908 } else if(Tok.is(tok::l_paren)) {
2909 BalancedDelimiterTracker T(*this, tok::l_paren);
2912 // Parse the optional expression-list.
2913 ExprVector ArgExprs;
2914 CommaLocsTy CommaLocs;
2915 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
2916 SkipUntil(tok::r_paren, StopAtSemi);
2922 SourceLocation EllipsisLoc;
2923 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2925 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2926 TemplateTypeTy, DS, IdLoc,
2927 T.getOpenLocation(), ArgExprs,
2928 T.getCloseLocation(), EllipsisLoc);
2931 if (getLangOpts().CPlusPlus11)
2932 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
2934 return Diag(Tok, diag::err_expected) << tok::l_paren;
2937 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
2939 /// exception-specification:
2940 /// dynamic-exception-specification
2941 /// noexcept-specification
2943 /// noexcept-specification:
2945 /// 'noexcept' '(' constant-expression ')'
2946 ExceptionSpecificationType
2947 Parser::tryParseExceptionSpecification(
2948 SourceRange &SpecificationRange,
2949 SmallVectorImpl<ParsedType> &DynamicExceptions,
2950 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2951 ExprResult &NoexceptExpr) {
2952 ExceptionSpecificationType Result = EST_None;
2954 // See if there's a dynamic specification.
2955 if (Tok.is(tok::kw_throw)) {
2956 Result = ParseDynamicExceptionSpecification(SpecificationRange,
2958 DynamicExceptionRanges);
2959 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
2960 "Produced different number of exception types and ranges.");
2963 // If there's no noexcept specification, we're done.
2964 if (Tok.isNot(tok::kw_noexcept))
2967 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
2969 // If we already had a dynamic specification, parse the noexcept for,
2970 // recovery, but emit a diagnostic and don't store the results.
2971 SourceRange NoexceptRange;
2972 ExceptionSpecificationType NoexceptType = EST_None;
2974 SourceLocation KeywordLoc = ConsumeToken();
2975 if (Tok.is(tok::l_paren)) {
2976 // There is an argument.
2977 BalancedDelimiterTracker T(*this, tok::l_paren);
2979 NoexceptType = EST_ComputedNoexcept;
2980 NoexceptExpr = ParseConstantExpression();
2981 // The argument must be contextually convertible to bool. We use
2982 // ActOnBooleanCondition for this purpose.
2983 if (!NoexceptExpr.isInvalid())
2984 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
2985 NoexceptExpr.get());
2987 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
2989 // There is no argument.
2990 NoexceptType = EST_BasicNoexcept;
2991 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
2994 if (Result == EST_None) {
2995 SpecificationRange = NoexceptRange;
2996 Result = NoexceptType;
2998 // If there's a dynamic specification after a noexcept specification,
2999 // parse that and ignore the results.
3000 if (Tok.is(tok::kw_throw)) {
3001 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3002 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3003 DynamicExceptionRanges);
3006 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3012 static void diagnoseDynamicExceptionSpecification(
3013 Parser &P, const SourceRange &Range, bool IsNoexcept) {
3014 if (P.getLangOpts().CPlusPlus11) {
3015 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3016 P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
3017 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3018 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3022 /// ParseDynamicExceptionSpecification - Parse a C++
3023 /// dynamic-exception-specification (C++ [except.spec]).
3025 /// dynamic-exception-specification:
3026 /// 'throw' '(' type-id-list [opt] ')'
3027 /// [MS] 'throw' '(' '...' ')'
3030 /// type-id ... [opt]
3031 /// type-id-list ',' type-id ... [opt]
3033 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3034 SourceRange &SpecificationRange,
3035 SmallVectorImpl<ParsedType> &Exceptions,
3036 SmallVectorImpl<SourceRange> &Ranges) {
3037 assert(Tok.is(tok::kw_throw) && "expected throw");
3039 SpecificationRange.setBegin(ConsumeToken());
3040 BalancedDelimiterTracker T(*this, tok::l_paren);
3041 if (T.consumeOpen()) {
3042 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3043 SpecificationRange.setEnd(SpecificationRange.getBegin());
3044 return EST_DynamicNone;
3047 // Parse throw(...), a Microsoft extension that means "this function
3048 // can throw anything".
3049 if (Tok.is(tok::ellipsis)) {
3050 SourceLocation EllipsisLoc = ConsumeToken();
3051 if (!getLangOpts().MicrosoftExt)
3052 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3054 SpecificationRange.setEnd(T.getCloseLocation());
3055 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3059 // Parse the sequence of type-ids.
3061 while (Tok.isNot(tok::r_paren)) {
3062 TypeResult Res(ParseTypeName(&Range));
3064 if (Tok.is(tok::ellipsis)) {
3065 // C++0x [temp.variadic]p5:
3066 // - In a dynamic-exception-specification (15.4); the pattern is a
3068 SourceLocation Ellipsis = ConsumeToken();
3069 Range.setEnd(Ellipsis);
3070 if (!Res.isInvalid())
3071 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3074 if (!Res.isInvalid()) {
3075 Exceptions.push_back(Res.get());
3076 Ranges.push_back(Range);
3079 if (!TryConsumeToken(tok::comma))
3084 SpecificationRange.setEnd(T.getCloseLocation());
3085 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3086 Exceptions.empty());
3087 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3090 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3091 /// function declaration.
3092 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3093 assert(Tok.is(tok::arrow) && "expected arrow");
3097 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3100 /// \brief We have just started parsing the definition of a new class,
3101 /// so push that class onto our stack of classes that is currently
3103 Sema::ParsingClassState
3104 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3106 assert((NonNestedClass || !ClassStack.empty()) &&
3107 "Nested class without outer class");
3108 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3109 return Actions.PushParsingClass();
3112 /// \brief Deallocate the given parsed class and all of its nested
3114 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3115 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3116 delete Class->LateParsedDeclarations[I];
3120 /// \brief Pop the top class of the stack of classes that are
3121 /// currently being parsed.
3123 /// This routine should be called when we have finished parsing the
3124 /// definition of a class, but have not yet popped the Scope
3125 /// associated with the class's definition.
3126 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3127 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3129 Actions.PopParsingClass(state);
3131 ParsingClass *Victim = ClassStack.top();
3133 if (Victim->TopLevelClass) {
3134 // Deallocate all of the nested classes of this class,
3135 // recursively: we don't need to keep any of this information.
3136 DeallocateParsedClasses(Victim);
3139 assert(!ClassStack.empty() && "Missing top-level class?");
3141 if (Victim->LateParsedDeclarations.empty()) {
3142 // The victim is a nested class, but we will not need to perform
3143 // any processing after the definition of this class since it has
3144 // no members whose handling was delayed. Therefore, we can just
3145 // remove this nested class.
3146 DeallocateParsedClasses(Victim);
3150 // This nested class has some members that will need to be processed
3151 // after the top-level class is completely defined. Therefore, add
3152 // it to the list of nested classes within its parent.
3153 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3154 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3155 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3158 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3160 /// \return the parsed identifier on success, and 0 if the next token is not an
3161 /// attribute-token.
3163 /// C++11 [dcl.attr.grammar]p3:
3164 /// If a keyword or an alternative token that satisfies the syntactic
3165 /// requirements of an identifier is contained in an attribute-token,
3166 /// it is considered an identifier.
3167 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3168 switch (Tok.getKind()) {
3170 // Identifiers and keywords have identifier info attached.
3171 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3172 Loc = ConsumeToken();
3177 case tok::ampamp: // 'and'
3178 case tok::pipe: // 'bitor'
3179 case tok::pipepipe: // 'or'
3180 case tok::caret: // 'xor'
3181 case tok::tilde: // 'compl'
3182 case tok::amp: // 'bitand'
3183 case tok::ampequal: // 'and_eq'
3184 case tok::pipeequal: // 'or_eq'
3185 case tok::caretequal: // 'xor_eq'
3186 case tok::exclaim: // 'not'
3187 case tok::exclaimequal: // 'not_eq'
3188 // Alternative tokens do not have identifier info, but their spelling
3189 // starts with an alphabetical character.
3190 SmallString<8> SpellingBuf;
3191 StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf);
3192 if (isLetter(Spelling[0])) {
3193 Loc = ConsumeToken();
3194 return &PP.getIdentifierTable().get(Spelling);
3200 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3201 IdentifierInfo *ScopeName) {
3202 switch (AttributeList::getKind(AttrName, ScopeName,
3203 AttributeList::AS_CXX11)) {
3204 case AttributeList::AT_CarriesDependency:
3205 case AttributeList::AT_Deprecated:
3206 case AttributeList::AT_FallThrough:
3207 case AttributeList::AT_CXX11NoReturn: {
3216 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3218 /// [C++11] attribute-argument-clause:
3219 /// '(' balanced-token-seq ')'
3221 /// [C++11] balanced-token-seq:
3223 /// balanced-token-seq balanced-token
3225 /// [C++11] balanced-token:
3226 /// '(' balanced-token-seq ')'
3227 /// '[' balanced-token-seq ']'
3228 /// '{' balanced-token-seq '}'
3229 /// any token but '(', ')', '[', ']', '{', or '}'
3230 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3231 SourceLocation AttrNameLoc,
3232 ParsedAttributes &Attrs,
3233 SourceLocation *EndLoc,
3234 IdentifierInfo *ScopeName,
3235 SourceLocation ScopeLoc) {
3236 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3237 SourceLocation LParenLoc = Tok.getLocation();
3239 // If the attribute isn't known, we will not attempt to parse any
3241 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
3242 getTargetInfo().getTriple(), getLangOpts())) {
3243 // Eat the left paren, then skip to the ending right paren.
3245 SkipUntil(tok::r_paren);
3249 if (ScopeName && ScopeName->getName() == "gnu")
3250 // GNU-scoped attributes have some special cases to handle GNU-specific
3252 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3253 ScopeLoc, AttributeList::AS_CXX11, nullptr);
3256 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3257 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3259 const AttributeList *Attr = Attrs.getList();
3260 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3261 // If the attribute is a standard or built-in attribute and we are
3262 // parsing an argument list, we need to determine whether this attribute
3263 // was allowed to have an argument list (such as [[deprecated]]), and how
3264 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3265 if (Attr->getMaxArgs() && !NumArgs) {
3266 // The attribute was allowed to have arguments, but none were provided
3267 // even though the attribute parsed successfully. This is an error.
3268 // FIXME: This is a good place for a fixit which removes the parens.
3269 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3271 } else if (!Attr->getMaxArgs()) {
3272 // The attribute parsed successfully, but was not allowed to have any
3273 // arguments. It doesn't matter whether any were provided -- the
3274 // presence of the argument list (even if empty) is diagnosed.
3275 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3284 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
3286 /// [C++11] attribute-specifier:
3287 /// '[' '[' attribute-list ']' ']'
3288 /// alignment-specifier
3290 /// [C++11] attribute-list:
3292 /// attribute-list ',' attribute[opt]
3294 /// attribute-list ',' attribute '...'
3296 /// [C++11] attribute:
3297 /// attribute-token attribute-argument-clause[opt]
3299 /// [C++11] attribute-token:
3301 /// attribute-scoped-token
3303 /// [C++11] attribute-scoped-token:
3304 /// attribute-namespace '::' identifier
3306 /// [C++11] attribute-namespace:
3308 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3309 SourceLocation *endLoc) {
3310 if (Tok.is(tok::kw_alignas)) {
3311 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3312 ParseAlignmentSpecifier(attrs, endLoc);
3316 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3317 && "Not a C++11 attribute list");
3319 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3324 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3326 while (Tok.isNot(tok::r_square)) {
3327 // attribute not present
3328 if (TryConsumeToken(tok::comma))
3331 SourceLocation ScopeLoc, AttrLoc;
3332 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3334 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3336 // Break out to the "expected ']'" diagnostic.
3340 if (TryConsumeToken(tok::coloncolon)) {
3341 ScopeName = AttrName;
3344 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3346 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3347 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3352 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
3353 bool AttrParsed = false;
3356 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3357 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
3358 << AttrName << SourceRange(SeenAttrs[AttrName]);
3360 // Parse attribute arguments
3361 if (Tok.is(tok::l_paren))
3362 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3363 ScopeName, ScopeLoc);
3366 attrs.addNew(AttrName,
3367 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3369 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
3371 if (TryConsumeToken(tok::ellipsis))
3372 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3373 << AttrName->getName();
3376 if (ExpectAndConsume(tok::r_square))
3377 SkipUntil(tok::r_square);
3379 *endLoc = Tok.getLocation();
3380 if (ExpectAndConsume(tok::r_square))
3381 SkipUntil(tok::r_square);
3384 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3386 /// attribute-specifier-seq:
3387 /// attribute-specifier-seq[opt] attribute-specifier
3388 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3389 SourceLocation *endLoc) {
3390 assert(getLangOpts().CPlusPlus11);
3392 SourceLocation StartLoc = Tok.getLocation(), Loc;
3397 ParseCXX11AttributeSpecifier(attrs, endLoc);
3398 } while (isCXX11AttributeSpecifier());
3400 attrs.Range = SourceRange(StartLoc, *endLoc);
3403 void Parser::DiagnoseAndSkipCXX11Attributes() {
3404 // Start and end location of an attribute or an attribute list.
3405 SourceLocation StartLoc = Tok.getLocation();
3406 SourceLocation EndLoc = SkipCXX11Attributes();
3408 if (EndLoc.isValid()) {
3409 SourceRange Range(StartLoc, EndLoc);
3410 Diag(StartLoc, diag::err_attributes_not_allowed)
3415 SourceLocation Parser::SkipCXX11Attributes() {
3416 SourceLocation EndLoc;
3418 if (!isCXX11AttributeSpecifier())
3422 if (Tok.is(tok::l_square)) {
3423 BalancedDelimiterTracker T(*this, tok::l_square);
3426 EndLoc = T.getCloseLocation();
3428 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
3430 BalancedDelimiterTracker T(*this, tok::l_paren);
3431 if (!T.consumeOpen())
3433 EndLoc = T.getCloseLocation();
3435 } while (isCXX11AttributeSpecifier());
3440 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
3442 /// [MS] ms-attribute:
3443 /// '[' token-seq ']'
3445 /// [MS] ms-attribute-seq:
3446 /// ms-attribute[opt]
3447 /// ms-attribute ms-attribute-seq
3448 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3449 SourceLocation *endLoc) {
3450 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3452 while (Tok.is(tok::l_square)) {
3453 // FIXME: If this is actually a C++11 attribute, parse it as one.
3455 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
3456 if (endLoc) *endLoc = Tok.getLocation();
3457 ExpectAndConsume(tok::r_square);
3461 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3462 AccessSpecifier& CurAS) {
3463 IfExistsCondition Result;
3464 if (ParseMicrosoftIfExistsCondition(Result))
3467 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3468 if (Braces.consumeOpen()) {
3469 Diag(Tok, diag::err_expected) << tok::l_brace;
3473 switch (Result.Behavior) {
3475 // Parse the declarations below.
3479 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3480 << Result.IsIfExists;
3481 // Fall through to skip.
3488 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
3489 // __if_exists, __if_not_exists can nest.
3490 if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
3491 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3495 // Check for extraneous top-level semicolon.
3496 if (Tok.is(tok::semi)) {
3497 ConsumeExtraSemi(InsideStruct, TagType);
3501 AccessSpecifier AS = getAccessSpecifierIfPresent();
3502 if (AS != AS_none) {
3503 // Current token is a C++ access specifier.
3505 SourceLocation ASLoc = Tok.getLocation();
3507 if (Tok.is(tok::colon))
3508 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3510 Diag(Tok, diag::err_expected) << tok::colon;
3515 // Parse all the comma separated declarators.
3516 ParseCXXClassMemberDeclaration(CurAS, nullptr);
3519 Braces.consumeClose();