1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++ Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Basic/Attributes.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/OperatorKinds.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/ADT/SmallString.h"
30 using namespace clang;
32 /// ParseNamespace - We know that the current token is a namespace keyword. This
33 /// may either be a top level namespace or a block-level namespace alias. If
34 /// there was an inline keyword, it has already been parsed.
36 /// namespace-definition: [C++ 7.3: basic.namespace]
37 /// named-namespace-definition
38 /// unnamed-namespace-definition
40 /// unnamed-namespace-definition:
41 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
43 /// named-namespace-definition:
44 /// original-namespace-definition
45 /// extension-namespace-definition
47 /// original-namespace-definition:
48 /// 'inline'[opt] 'namespace' identifier attributes[opt]
49 /// '{' namespace-body '}'
51 /// extension-namespace-definition:
52 /// 'inline'[opt] 'namespace' original-namespace-name
53 /// '{' namespace-body '}'
55 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
56 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
58 Parser::DeclGroupPtrTy Parser::ParseNamespace(unsigned Context,
59 SourceLocation &DeclEnd,
60 SourceLocation InlineLoc) {
61 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
62 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
63 ObjCDeclContextSwitch ObjCDC(*this);
65 if (Tok.is(tok::code_completion)) {
66 Actions.CodeCompleteNamespaceDecl(getCurScope());
68 return DeclGroupPtrTy();
71 SourceLocation IdentLoc;
72 IdentifierInfo *Ident = nullptr;
73 std::vector<SourceLocation> ExtraIdentLoc;
74 std::vector<IdentifierInfo*> ExtraIdent;
75 std::vector<SourceLocation> ExtraNamespaceLoc;
77 ParsedAttributesWithRange attrs(AttrFactory);
78 SourceLocation attrLoc;
79 if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
80 if (!getLangOpts().CPlusPlus1z)
81 Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
83 attrLoc = Tok.getLocation();
84 ParseCXX11Attributes(attrs);
87 if (Tok.is(tok::identifier)) {
88 Ident = Tok.getIdentifierInfo();
89 IdentLoc = ConsumeToken(); // eat the identifier.
90 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
91 ExtraNamespaceLoc.push_back(ConsumeToken());
92 ExtraIdent.push_back(Tok.getIdentifierInfo());
93 ExtraIdentLoc.push_back(ConsumeToken());
97 // A nested namespace definition cannot have attributes.
98 if (!ExtraNamespaceLoc.empty() && attrLoc.isValid())
99 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
101 // Read label attributes, if present.
102 if (Tok.is(tok::kw___attribute)) {
103 attrLoc = Tok.getLocation();
104 ParseGNUAttributes(attrs);
107 if (Tok.is(tok::equal)) {
109 Diag(Tok, diag::err_expected) << tok::identifier;
110 // Skip to end of the definition and eat the ';'.
111 SkipUntil(tok::semi);
112 return DeclGroupPtrTy();
114 if (attrLoc.isValid())
115 Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
116 if (InlineLoc.isValid())
117 Diag(InlineLoc, diag::err_inline_namespace_alias)
118 << FixItHint::CreateRemoval(InlineLoc);
119 Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
120 return Actions.ConvertDeclToDeclGroup(NSAlias);
123 BalancedDelimiterTracker T(*this, tok::l_brace);
124 if (T.consumeOpen()) {
126 Diag(Tok, diag::err_expected) << tok::l_brace;
128 Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
129 return DeclGroupPtrTy();
132 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
133 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
134 getCurScope()->getFnParent()) {
135 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
136 SkipUntil(tok::r_brace);
137 return DeclGroupPtrTy();
140 if (ExtraIdent.empty()) {
141 // Normal namespace definition, not a nested-namespace-definition.
142 } else if (InlineLoc.isValid()) {
143 Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
144 } else if (getLangOpts().CPlusPlus1z) {
145 Diag(ExtraNamespaceLoc[0],
146 diag::warn_cxx14_compat_nested_namespace_definition);
148 TentativeParsingAction TPA(*this);
149 SkipUntil(tok::r_brace, StopBeforeMatch);
150 Token rBraceToken = Tok;
153 if (!rBraceToken.is(tok::r_brace)) {
154 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
155 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
157 std::string NamespaceFix;
158 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
159 E = ExtraIdent.end(); I != E; ++I) {
160 NamespaceFix += " { namespace ";
161 NamespaceFix += (*I)->getName();
165 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
168 Diag(ExtraNamespaceLoc[0], diag::ext_nested_namespace_definition)
169 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
170 ExtraIdentLoc.back()),
172 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
176 // If we're still good, complain about inline namespaces in non-C++0x now.
177 if (InlineLoc.isValid())
178 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
179 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
181 // Enter a scope for the namespace.
182 ParseScope NamespaceScope(this, Scope::DeclScope);
184 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
186 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
187 IdentLoc, Ident, T.getOpenLocation(),
188 attrs.getList(), ImplicitUsingDirectiveDecl);
190 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
191 "parsing namespace");
193 // Parse the contents of the namespace. This includes parsing recovery on
194 // any improperly nested namespaces.
195 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
196 InlineLoc, attrs, T);
198 // Leave the namespace scope.
199 NamespaceScope.Exit();
201 DeclEnd = T.getCloseLocation();
202 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
204 return Actions.ConvertDeclToDeclGroup(NamespcDecl,
205 ImplicitUsingDirectiveDecl);
208 /// ParseInnerNamespace - Parse the contents of a namespace.
209 void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
210 std::vector<IdentifierInfo *> &Ident,
211 std::vector<SourceLocation> &NamespaceLoc,
212 unsigned int index, SourceLocation &InlineLoc,
213 ParsedAttributes &attrs,
214 BalancedDelimiterTracker &Tracker) {
215 if (index == Ident.size()) {
216 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
217 Tok.isNot(tok::eof)) {
218 ParsedAttributesWithRange attrs(AttrFactory);
219 MaybeParseCXX11Attributes(attrs);
220 MaybeParseMicrosoftAttributes(attrs);
221 ParseExternalDeclaration(attrs);
224 // The caller is what called check -- we are simply calling
226 Tracker.consumeClose();
231 // Handle a nested namespace definition.
232 // FIXME: Preserve the source information through to the AST rather than
233 // desugaring it here.
234 ParseScope NamespaceScope(this, Scope::DeclScope);
235 UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
237 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
238 NamespaceLoc[index], IdentLoc[index],
239 Ident[index], Tracker.getOpenLocation(),
240 attrs.getList(), ImplicitUsingDirectiveDecl);
241 assert(!ImplicitUsingDirectiveDecl &&
242 "nested namespace definition cannot define anonymous namespace");
244 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
247 NamespaceScope.Exit();
248 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
251 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
252 /// alias definition.
254 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
255 SourceLocation AliasLoc,
256 IdentifierInfo *Alias,
257 SourceLocation &DeclEnd) {
258 assert(Tok.is(tok::equal) && "Not equal token");
260 ConsumeToken(); // eat the '='.
262 if (Tok.is(tok::code_completion)) {
263 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
269 // Parse (optional) nested-name-specifier.
270 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
272 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
273 Diag(Tok, diag::err_expected_namespace_name);
274 // Skip to end of the definition and eat the ';'.
275 SkipUntil(tok::semi);
280 IdentifierInfo *Ident = Tok.getIdentifierInfo();
281 SourceLocation IdentLoc = ConsumeToken();
284 DeclEnd = Tok.getLocation();
285 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
286 SkipUntil(tok::semi);
288 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
289 Alias, SS, IdentLoc, Ident);
292 /// ParseLinkage - We know that the current token is a string_literal
293 /// and just before that, that extern was seen.
295 /// linkage-specification: [C++ 7.5p2: dcl.link]
296 /// 'extern' string-literal '{' declaration-seq[opt] '}'
297 /// 'extern' string-literal declaration
299 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
300 assert(isTokenStringLiteral() && "Not a string literal!");
301 ExprResult Lang = ParseStringLiteralExpression(false);
303 ParseScope LinkageScope(this, Scope::DeclScope);
307 : Actions.ActOnStartLinkageSpecification(
308 getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
309 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
311 ParsedAttributesWithRange attrs(AttrFactory);
312 MaybeParseCXX11Attributes(attrs);
313 MaybeParseMicrosoftAttributes(attrs);
315 if (Tok.isNot(tok::l_brace)) {
316 // Reset the source range in DS, as the leading "extern"
317 // does not really belong to the inner declaration ...
318 DS.SetRangeStart(SourceLocation());
319 DS.SetRangeEnd(SourceLocation());
320 // ... but anyway remember that such an "extern" was seen.
321 DS.setExternInLinkageSpec(true);
322 ParseExternalDeclaration(attrs, &DS);
323 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
324 getCurScope(), LinkageSpec, SourceLocation())
330 ProhibitAttributes(attrs);
332 BalancedDelimiterTracker T(*this, tok::l_brace);
335 unsigned NestedModules = 0;
337 switch (Tok.getKind()) {
338 case tok::annot_module_begin:
343 case tok::annot_module_end:
350 case tok::annot_module_include:
362 ParsedAttributesWithRange attrs(AttrFactory);
363 MaybeParseCXX11Attributes(attrs);
364 MaybeParseMicrosoftAttributes(attrs);
365 ParseExternalDeclaration(attrs);
373 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
374 getCurScope(), LinkageSpec, T.getCloseLocation())
378 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
379 /// using-directive. Assumes that current token is 'using'.
380 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
381 const ParsedTemplateInfo &TemplateInfo,
382 SourceLocation &DeclEnd,
383 ParsedAttributesWithRange &attrs,
385 assert(Tok.is(tok::kw_using) && "Not using token");
386 ObjCDeclContextSwitch ObjCDC(*this);
389 SourceLocation UsingLoc = ConsumeToken();
391 if (Tok.is(tok::code_completion)) {
392 Actions.CodeCompleteUsing(getCurScope());
397 // 'using namespace' means this is a using-directive.
398 if (Tok.is(tok::kw_namespace)) {
399 // Template parameters are always an error here.
400 if (TemplateInfo.Kind) {
401 SourceRange R = TemplateInfo.getSourceRange();
402 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
403 << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
406 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
409 // Otherwise, it must be a using-declaration or an alias-declaration.
411 // Using declarations can't have attributes.
412 ProhibitAttributes(attrs);
414 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
418 /// ParseUsingDirective - Parse C++ using-directive, assumes
419 /// that current token is 'namespace' and 'using' was already parsed.
421 /// using-directive: [C++ 7.3.p4: namespace.udir]
422 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
424 /// [GNU] using-directive:
425 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
426 /// namespace-name attributes[opt] ;
428 Decl *Parser::ParseUsingDirective(unsigned Context,
429 SourceLocation UsingLoc,
430 SourceLocation &DeclEnd,
431 ParsedAttributes &attrs) {
432 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
435 SourceLocation NamespcLoc = ConsumeToken();
437 if (Tok.is(tok::code_completion)) {
438 Actions.CodeCompleteUsingDirective(getCurScope());
444 // Parse (optional) nested-name-specifier.
445 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
447 IdentifierInfo *NamespcName = nullptr;
448 SourceLocation IdentLoc = SourceLocation();
450 // Parse namespace-name.
451 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
452 Diag(Tok, diag::err_expected_namespace_name);
453 // If there was invalid namespace name, skip to end of decl, and eat ';'.
454 SkipUntil(tok::semi);
455 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
460 NamespcName = Tok.getIdentifierInfo();
461 IdentLoc = ConsumeToken();
463 // Parse (optional) attributes (most likely GNU strong-using extension).
464 bool GNUAttr = false;
465 if (Tok.is(tok::kw___attribute)) {
467 ParseGNUAttributes(attrs);
471 DeclEnd = Tok.getLocation();
472 if (ExpectAndConsume(tok::semi,
473 GNUAttr ? diag::err_expected_semi_after_attribute_list
474 : diag::err_expected_semi_after_namespace_name))
475 SkipUntil(tok::semi);
477 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
478 IdentLoc, NamespcName, attrs.getList());
481 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
482 /// Assumes that 'using' was already seen.
484 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
485 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
487 /// 'using' :: unqualified-id
489 /// alias-declaration: C++11 [dcl.dcl]p1
490 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
492 Decl *Parser::ParseUsingDeclaration(unsigned Context,
493 const ParsedTemplateInfo &TemplateInfo,
494 SourceLocation UsingLoc,
495 SourceLocation &DeclEnd,
499 SourceLocation TypenameLoc;
500 bool HasTypenameKeyword = false;
502 // Check for misplaced attributes before the identifier in an
503 // alias-declaration.
504 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
505 MaybeParseCXX11Attributes(MisplacedAttrs);
507 // Ignore optional 'typename'.
508 // FIXME: This is wrong; we should parse this as a typename-specifier.
509 if (TryConsumeToken(tok::kw_typename, TypenameLoc))
510 HasTypenameKeyword = true;
512 if (Tok.is(tok::kw___super)) {
513 Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
514 SkipUntil(tok::semi);
518 // Parse nested-name-specifier.
519 IdentifierInfo *LastII = nullptr;
520 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false,
521 /*MayBePseudoDtor=*/nullptr,
522 /*IsTypename=*/false,
525 // Check nested-name specifier.
526 if (SS.isInvalid()) {
527 SkipUntil(tok::semi);
531 SourceLocation TemplateKWLoc;
534 // Parse the unqualified-id. We allow parsing of both constructor and
535 // destructor names and allow the action module to diagnose any semantic
538 // C++11 [class.qual]p2:
539 // [...] in a using-declaration that is a member-declaration, if the name
540 // specified after the nested-name-specifier is the same as the identifier
541 // or the simple-template-id's template-name in the last component of the
542 // nested-name-specifier, the name is [...] considered to name the
544 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
545 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
546 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
547 !SS.getScopeRep()->getAsNamespace() &&
548 !SS.getScopeRep()->getAsNamespaceAlias()) {
549 SourceLocation IdLoc = ConsumeToken();
550 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
551 Name.setConstructorName(Type, IdLoc, IdLoc);
552 } else if (ParseUnqualifiedId(
553 SS, /*EnteringContext=*/false,
554 /*AllowDestructorName=*/true,
555 /*AllowConstructorName=*/!(Tok.is(tok::identifier) &&
556 NextToken().is(tok::equal)),
557 ParsedType(), TemplateKWLoc, Name)) {
558 SkipUntil(tok::semi);
562 ParsedAttributesWithRange Attrs(AttrFactory);
563 MaybeParseGNUAttributes(Attrs);
564 MaybeParseCXX11Attributes(Attrs);
566 // Maybe this is an alias-declaration.
567 TypeResult TypeAlias;
568 bool IsAliasDecl = Tok.is(tok::equal);
569 Decl *DeclFromDeclSpec = nullptr;
571 // If we had any misplaced attributes from earlier, this is where they
572 // should have been written.
573 if (MisplacedAttrs.Range.isValid()) {
574 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
575 << FixItHint::CreateInsertionFromRange(
577 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
578 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
579 Attrs.takeAllFrom(MisplacedAttrs);
584 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
585 diag::warn_cxx98_compat_alias_declaration :
586 diag::ext_alias_declaration);
588 // Type alias templates cannot be specialized.
590 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
591 Name.getKind() == UnqualifiedId::IK_TemplateId)
593 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
595 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
597 if (SpecKind != -1) {
600 Range = SourceRange(Name.TemplateId->LAngleLoc,
601 Name.TemplateId->RAngleLoc);
603 Range = TemplateInfo.getSourceRange();
604 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
605 << SpecKind << Range;
606 SkipUntil(tok::semi);
610 // Name must be an identifier.
611 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
612 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
613 // No removal fixit: can't recover from this.
614 SkipUntil(tok::semi);
616 } else if (HasTypenameKeyword)
617 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
618 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
619 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
620 else if (SS.isNotEmpty())
621 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
622 << FixItHint::CreateRemoval(SS.getRange());
624 TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind
625 ? Declarator::AliasTemplateContext
626 : Declarator::AliasDeclContext,
627 AS, &DeclFromDeclSpec, &Attrs);
629 *OwnedType = DeclFromDeclSpec;
631 // C++11 attributes are not allowed on a using-declaration, but GNU ones
633 ProhibitAttributes(MisplacedAttrs);
634 ProhibitAttributes(Attrs);
636 // Parse (optional) attributes (most likely GNU strong-using extension).
637 MaybeParseGNUAttributes(Attrs);
641 DeclEnd = Tok.getLocation();
642 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
643 !Attrs.empty() ? "attributes list"
644 : IsAliasDecl ? "alias declaration"
645 : "using declaration"))
646 SkipUntil(tok::semi);
648 // Diagnose an attempt to declare a templated using-declaration.
649 // In C++11, alias-declarations can be templates:
650 // template <...> using id = type;
651 if (TemplateInfo.Kind && !IsAliasDecl) {
652 SourceRange R = TemplateInfo.getSourceRange();
653 Diag(UsingLoc, diag::err_templated_using_directive_declaration)
654 << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
656 // Unfortunately, we have to bail out instead of recovering by
657 // ignoring the parameters, just in case the nested name specifier
658 // depends on the parameters.
662 // "typename" keyword is allowed for identifiers only,
663 // because it may be a type definition.
664 if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
665 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
666 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
667 // Proceed parsing, but reset the HasTypenameKeyword flag.
668 HasTypenameKeyword = false;
672 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
673 MultiTemplateParamsArg TemplateParamsArg(
674 TemplateParams ? TemplateParams->data() : nullptr,
675 TemplateParams ? TemplateParams->size() : 0);
676 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
677 UsingLoc, Name, Attrs.getList(),
678 TypeAlias, DeclFromDeclSpec);
681 return Actions.ActOnUsingDeclaration(getCurScope(), AS,
682 /* HasUsingKeyword */ true, UsingLoc,
683 SS, Name, Attrs.getList(),
684 HasTypenameKeyword, TypenameLoc);
687 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
689 /// [C++0x] static_assert-declaration:
690 /// static_assert ( constant-expression , string-literal ) ;
692 /// [C11] static_assert-declaration:
693 /// _Static_assert ( constant-expression , string-literal ) ;
695 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
696 assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
697 "Not a static_assert declaration");
699 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
700 Diag(Tok, diag::ext_c11_static_assert);
701 if (Tok.is(tok::kw_static_assert))
702 Diag(Tok, diag::warn_cxx98_compat_static_assert);
704 SourceLocation StaticAssertLoc = ConsumeToken();
706 BalancedDelimiterTracker T(*this, tok::l_paren);
707 if (T.consumeOpen()) {
708 Diag(Tok, diag::err_expected) << tok::l_paren;
713 ExprResult AssertExpr(ParseConstantExpression());
714 if (AssertExpr.isInvalid()) {
719 ExprResult AssertMessage;
720 if (Tok.is(tok::r_paren)) {
721 Diag(Tok, getLangOpts().CPlusPlus1z
722 ? diag::warn_cxx14_compat_static_assert_no_message
723 : diag::ext_static_assert_no_message)
724 << (getLangOpts().CPlusPlus1z
726 : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\""));
728 if (ExpectAndConsume(tok::comma)) {
729 SkipUntil(tok::semi);
733 if (!isTokenStringLiteral()) {
734 Diag(Tok, diag::err_expected_string_literal)
735 << /*Source='static_assert'*/1;
740 AssertMessage = ParseStringLiteralExpression();
741 if (AssertMessage.isInvalid()) {
749 DeclEnd = Tok.getLocation();
750 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
752 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
755 T.getCloseLocation());
758 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
760 /// 'decltype' ( expression )
761 /// 'decltype' ( 'auto' ) [C++1y]
763 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
764 assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
765 && "Not a decltype specifier");
768 SourceLocation StartLoc = Tok.getLocation();
769 SourceLocation EndLoc;
771 if (Tok.is(tok::annot_decltype)) {
772 Result = getExprAnnotation(Tok);
773 EndLoc = Tok.getAnnotationEndLoc();
775 if (Result.isInvalid()) {
776 DS.SetTypeSpecError();
780 if (Tok.getIdentifierInfo()->isStr("decltype"))
781 Diag(Tok, diag::warn_cxx98_compat_decltype);
785 BalancedDelimiterTracker T(*this, tok::l_paren);
786 if (T.expectAndConsume(diag::err_expected_lparen_after,
787 "decltype", tok::r_paren)) {
788 DS.SetTypeSpecError();
789 return T.getOpenLocation() == Tok.getLocation() ?
790 StartLoc : T.getOpenLocation();
793 // Check for C++1y 'decltype(auto)'.
794 if (Tok.is(tok::kw_auto)) {
795 // No need to disambiguate here: an expression can't start with 'auto',
796 // because the typename-specifier in a function-style cast operation can't
798 Diag(Tok.getLocation(),
799 getLangOpts().CPlusPlus14
800 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
801 : diag::ext_decltype_auto_type_specifier);
804 // Parse the expression
806 // C++11 [dcl.type.simple]p4:
807 // The operand of the decltype specifier is an unevaluated operand.
808 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
809 nullptr,/*IsDecltype=*/true);
811 Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) {
812 return E->hasPlaceholderType() ? ExprError() : E;
814 if (Result.isInvalid()) {
815 DS.SetTypeSpecError();
816 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
817 EndLoc = ConsumeParen();
819 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
820 // Backtrack to get the location of the last token before the semi.
821 PP.RevertCachedTokens(2);
822 ConsumeToken(); // the semi.
823 EndLoc = ConsumeAnyToken();
824 assert(Tok.is(tok::semi));
826 EndLoc = Tok.getLocation();
832 Result = Actions.ActOnDecltypeExpression(Result.get());
837 if (T.getCloseLocation().isInvalid()) {
838 DS.SetTypeSpecError();
839 // FIXME: this should return the location of the last token
840 // that was consumed (by "consumeClose()")
841 return T.getCloseLocation();
844 if (Result.isInvalid()) {
845 DS.SetTypeSpecError();
846 return T.getCloseLocation();
849 EndLoc = T.getCloseLocation();
851 assert(!Result.isInvalid());
853 const char *PrevSpec = nullptr;
855 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
856 // Check for duplicate type specifiers (e.g. "int decltype(a)").
858 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
859 DiagID, Result.get(), Policy)
860 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
862 Diag(StartLoc, DiagID) << PrevSpec;
863 DS.SetTypeSpecError();
868 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
869 SourceLocation StartLoc,
870 SourceLocation EndLoc) {
871 // make sure we have a token we can turn into an annotation token
872 if (PP.isBacktrackEnabled())
873 PP.RevertCachedTokens(1);
877 Tok.setKind(tok::annot_decltype);
878 setExprAnnotation(Tok,
879 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
880 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
882 Tok.setAnnotationEndLoc(EndLoc);
883 Tok.setLocation(StartLoc);
884 PP.AnnotateCachedTokens(Tok);
887 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
888 assert(Tok.is(tok::kw___underlying_type) &&
889 "Not an underlying type specifier");
891 SourceLocation StartLoc = ConsumeToken();
892 BalancedDelimiterTracker T(*this, tok::l_paren);
893 if (T.expectAndConsume(diag::err_expected_lparen_after,
894 "__underlying_type", tok::r_paren)) {
898 TypeResult Result = ParseTypeName();
899 if (Result.isInvalid()) {
900 SkipUntil(tok::r_paren, StopAtSemi);
906 if (T.getCloseLocation().isInvalid())
909 const char *PrevSpec = nullptr;
911 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
912 DiagID, Result.get(),
913 Actions.getASTContext().getPrintingPolicy()))
914 Diag(StartLoc, DiagID) << PrevSpec;
915 DS.setTypeofParensRange(T.getRange());
918 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
919 /// class name or decltype-specifier. Note that we only check that the result
920 /// names a type; semantic analysis will need to verify that the type names a
921 /// class. The result is either a type or null, depending on whether a type
924 /// base-type-specifier: [C++11 class.derived]
925 /// class-or-decltype
926 /// class-or-decltype: [C++11 class.derived]
927 /// nested-name-specifier[opt] class-name
928 /// decltype-specifier
929 /// class-name: [C++ class.name]
931 /// simple-template-id
933 /// In C++98, instead of base-type-specifier, we have:
935 /// ::[opt] nested-name-specifier[opt] class-name
936 TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
937 SourceLocation &EndLocation) {
938 // Ignore attempts to use typename
939 if (Tok.is(tok::kw_typename)) {
940 Diag(Tok, diag::err_expected_class_name_not_template)
941 << FixItHint::CreateRemoval(Tok.getLocation());
945 // Parse optional nested-name-specifier
947 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
949 BaseLoc = Tok.getLocation();
951 // Parse decltype-specifier
952 // tok == kw_decltype is just error recovery, it can only happen when SS
954 if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
956 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
957 << FixItHint::CreateRemoval(SS.getRange());
958 // Fake up a Declarator to use with ActOnTypeName.
959 DeclSpec DS(AttrFactory);
961 EndLocation = ParseDecltypeSpecifier(DS);
963 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
964 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
967 // Check whether we have a template-id that names a type.
968 if (Tok.is(tok::annot_template_id)) {
969 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
970 if (TemplateId->Kind == TNK_Type_template ||
971 TemplateId->Kind == TNK_Dependent_template_name) {
972 AnnotateTemplateIdTokenAsType();
974 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
975 ParsedType Type = getTypeAnnotation(Tok);
976 EndLocation = Tok.getAnnotationEndLoc();
984 // Fall through to produce an error below.
987 if (Tok.isNot(tok::identifier)) {
988 Diag(Tok, diag::err_expected_class_name);
992 IdentifierInfo *Id = Tok.getIdentifierInfo();
993 SourceLocation IdLoc = ConsumeToken();
995 if (Tok.is(tok::less)) {
996 // It looks the user intended to write a template-id here, but the
997 // template-name was wrong. Try to fix that.
998 TemplateNameKind TNK = TNK_Type_template;
1000 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
1001 &SS, Template, TNK)) {
1002 Diag(IdLoc, diag::err_unknown_template_name)
1007 TemplateArgList TemplateArgs;
1008 SourceLocation LAngleLoc, RAngleLoc;
1009 ParseTemplateIdAfterTemplateName(TemplateTy(), IdLoc, SS,
1010 true, LAngleLoc, TemplateArgs, RAngleLoc);
1014 // Form the template name
1015 UnqualifiedId TemplateName;
1016 TemplateName.setIdentifier(Id, IdLoc);
1018 // Parse the full template-id, then turn it into a type.
1019 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
1020 TemplateName, true))
1022 if (TNK == TNK_Dependent_template_name)
1023 AnnotateTemplateIdTokenAsType();
1025 // If we didn't end up with a typename token, there's nothing more we
1027 if (Tok.isNot(tok::annot_typename))
1030 // Retrieve the type from the annotation token, consume that token, and
1032 EndLocation = Tok.getAnnotationEndLoc();
1033 ParsedType Type = getTypeAnnotation(Tok);
1038 // We have an identifier; check whether it is actually a type.
1039 IdentifierInfo *CorrectedII = nullptr;
1040 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
1041 false, ParsedType(),
1042 /*IsCtorOrDtorName=*/false,
1043 /*NonTrivialTypeSourceInfo=*/true,
1046 Diag(IdLoc, diag::err_expected_class_name);
1050 // Consume the identifier.
1051 EndLocation = IdLoc;
1053 // Fake up a Declarator to use with ActOnTypeName.
1054 DeclSpec DS(AttrFactory);
1055 DS.SetRangeStart(IdLoc);
1056 DS.SetRangeEnd(EndLocation);
1057 DS.getTypeSpecScope() = SS;
1059 const char *PrevSpec = nullptr;
1061 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
1062 Actions.getASTContext().getPrintingPolicy());
1064 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1065 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1068 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
1069 while (Tok.isOneOf(tok::kw___single_inheritance,
1070 tok::kw___multiple_inheritance,
1071 tok::kw___virtual_inheritance)) {
1072 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1073 SourceLocation AttrNameLoc = ConsumeToken();
1074 attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1075 AttributeList::AS_Keyword);
1079 /// Determine whether the following tokens are valid after a type-specifier
1080 /// which could be a standalone declaration. This will conservatively return
1081 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1082 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1083 // This switch enumerates the valid "follow" set for type-specifiers.
1084 switch (Tok.getKind()) {
1086 case tok::semi: // struct foo {...} ;
1087 case tok::star: // struct foo {...} * P;
1088 case tok::amp: // struct foo {...} & R = ...
1089 case tok::ampamp: // struct foo {...} && R = ...
1090 case tok::identifier: // struct foo {...} V ;
1091 case tok::r_paren: //(struct foo {...} ) {4}
1092 case tok::annot_cxxscope: // struct foo {...} a:: b;
1093 case tok::annot_typename: // struct foo {...} a ::b;
1094 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1095 case tok::l_paren: // struct foo {...} ( x);
1096 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1097 case tok::kw_operator: // struct foo operator ++() {...}
1098 case tok::kw___declspec: // struct foo {...} __declspec(...)
1099 case tok::l_square: // void f(struct f [ 3])
1100 case tok::ellipsis: // void f(struct f ... [Ns])
1101 // FIXME: we should emit semantic diagnostic when declaration
1102 // attribute is in type attribute position.
1103 case tok::kw___attribute: // struct foo __attribute__((used)) x;
1106 return CouldBeBitfield; // enum E { ... } : 2;
1108 case tok::kw_const: // struct foo {...} const x;
1109 case tok::kw_volatile: // struct foo {...} volatile x;
1110 case tok::kw_restrict: // struct foo {...} restrict x;
1111 case tok::kw__Atomic: // struct foo {...} _Atomic x;
1112 case tok::kw___unaligned: // struct foo {...} __unaligned *x;
1113 // Function specifiers
1114 // Note, no 'explicit'. An explicit function must be either a conversion
1115 // operator or a constructor. Either way, it can't have a return type.
1116 case tok::kw_inline: // struct foo inline f();
1117 case tok::kw_virtual: // struct foo virtual f();
1118 case tok::kw_friend: // struct foo friend f();
1119 // Storage-class specifiers
1120 case tok::kw_static: // struct foo {...} static x;
1121 case tok::kw_extern: // struct foo {...} extern x;
1122 case tok::kw_typedef: // struct foo {...} typedef x;
1123 case tok::kw_register: // struct foo {...} register x;
1124 case tok::kw_auto: // struct foo {...} auto x;
1125 case tok::kw_mutable: // struct foo {...} mutable x;
1126 case tok::kw_thread_local: // struct foo {...} thread_local x;
1127 case tok::kw_constexpr: // struct foo {...} constexpr x;
1128 // As shown above, type qualifiers and storage class specifiers absolutely
1129 // can occur after class specifiers according to the grammar. However,
1130 // almost no one actually writes code like this. If we see one of these,
1131 // it is much more likely that someone missed a semi colon and the
1132 // type/storage class specifier we're seeing is part of the *next*
1133 // intended declaration, as in:
1135 // struct foo { ... }
1138 // We'd really like to emit a missing semicolon error instead of emitting
1139 // an error on the 'int' saying that you can't have two type specifiers in
1140 // the same declaration of X. Because of this, we look ahead past this
1141 // token to see if it's a type specifier. If so, we know the code is
1142 // otherwise invalid, so we can produce the expected semi error.
1143 if (!isKnownToBeTypeSpecifier(NextToken()))
1146 case tok::r_brace: // struct bar { struct foo {...} }
1147 // Missing ';' at end of struct is accepted as an extension in C mode.
1148 if (!getLangOpts().CPlusPlus)
1152 // template<class T = class X>
1153 return getLangOpts().CPlusPlus;
1158 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1159 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1160 /// until we reach the start of a definition or see a token that
1161 /// cannot start a definition.
1163 /// class-specifier: [C++ class]
1164 /// class-head '{' member-specification[opt] '}'
1165 /// class-head '{' member-specification[opt] '}' attributes[opt]
1167 /// class-key identifier[opt] base-clause[opt]
1168 /// class-key nested-name-specifier identifier base-clause[opt]
1169 /// class-key nested-name-specifier[opt] simple-template-id
1170 /// base-clause[opt]
1171 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1172 /// [GNU] class-key attributes[opt] nested-name-specifier
1173 /// identifier base-clause[opt]
1174 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1175 /// simple-template-id base-clause[opt]
1181 /// elaborated-type-specifier: [C++ dcl.type.elab]
1182 /// class-key ::[opt] nested-name-specifier[opt] identifier
1183 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1184 /// simple-template-id
1186 /// Note that the C++ class-specifier and elaborated-type-specifier,
1187 /// together, subsume the C99 struct-or-union-specifier:
1189 /// struct-or-union-specifier: [C99 6.7.2.1]
1190 /// struct-or-union identifier[opt] '{' struct-contents '}'
1191 /// struct-or-union identifier
1192 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1193 /// '}' attributes[opt]
1194 /// [GNU] struct-or-union attributes[opt] identifier
1195 /// struct-or-union:
1198 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1199 SourceLocation StartLoc, DeclSpec &DS,
1200 const ParsedTemplateInfo &TemplateInfo,
1202 bool EnteringContext, DeclSpecContext DSC,
1203 ParsedAttributesWithRange &Attributes) {
1204 DeclSpec::TST TagType;
1205 if (TagTokKind == tok::kw_struct)
1206 TagType = DeclSpec::TST_struct;
1207 else if (TagTokKind == tok::kw___interface)
1208 TagType = DeclSpec::TST_interface;
1209 else if (TagTokKind == tok::kw_class)
1210 TagType = DeclSpec::TST_class;
1212 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1213 TagType = DeclSpec::TST_union;
1216 if (Tok.is(tok::code_completion)) {
1217 // Code completion for a struct, class, or union name.
1218 Actions.CodeCompleteTag(getCurScope(), TagType);
1219 return cutOffParsing();
1222 // C++03 [temp.explicit] 14.7.2/8:
1223 // The usual access checking rules do not apply to names used to specify
1224 // explicit instantiations.
1226 // As an extension we do not perform access checking on the names used to
1227 // specify explicit specializations either. This is important to allow
1228 // specializing traits classes for private types.
1230 // Note that we don't suppress if this turns out to be an elaborated
1232 bool shouldDelayDiagsInTag =
1233 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1234 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1235 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1237 ParsedAttributesWithRange attrs(AttrFactory);
1238 // If attributes exist after tag, parse them.
1239 MaybeParseGNUAttributes(attrs);
1240 MaybeParseMicrosoftDeclSpecs(attrs);
1242 // Parse inheritance specifiers.
1243 if (Tok.isOneOf(tok::kw___single_inheritance,
1244 tok::kw___multiple_inheritance,
1245 tok::kw___virtual_inheritance))
1246 ParseMicrosoftInheritanceClassAttributes(attrs);
1248 // If C++0x attributes exist here, parse them.
1249 // FIXME: Are we consistent with the ordering of parsing of different
1250 // styles of attributes?
1251 MaybeParseCXX11Attributes(attrs);
1253 // Source location used by FIXIT to insert misplaced
1255 SourceLocation AttrFixitLoc = Tok.getLocation();
1257 if (TagType == DeclSpec::TST_struct &&
1258 Tok.isNot(tok::identifier) &&
1259 !Tok.isAnnotation() &&
1260 Tok.getIdentifierInfo() &&
1261 Tok.isOneOf(tok::kw___is_abstract,
1262 tok::kw___is_arithmetic,
1264 tok::kw___is_base_of,
1266 tok::kw___is_complete_type,
1267 tok::kw___is_compound,
1269 tok::kw___is_constructible,
1270 tok::kw___is_convertible,
1271 tok::kw___is_convertible_to,
1272 tok::kw___is_destructible,
1275 tok::kw___is_floating_point,
1277 tok::kw___is_function,
1278 tok::kw___is_fundamental,
1279 tok::kw___is_integral,
1280 tok::kw___is_interface_class,
1281 tok::kw___is_literal,
1282 tok::kw___is_lvalue_expr,
1283 tok::kw___is_lvalue_reference,
1284 tok::kw___is_member_function_pointer,
1285 tok::kw___is_member_object_pointer,
1286 tok::kw___is_member_pointer,
1287 tok::kw___is_nothrow_assignable,
1288 tok::kw___is_nothrow_constructible,
1289 tok::kw___is_nothrow_destructible,
1290 tok::kw___is_object,
1292 tok::kw___is_pointer,
1293 tok::kw___is_polymorphic,
1294 tok::kw___is_reference,
1295 tok::kw___is_rvalue_expr,
1296 tok::kw___is_rvalue_reference,
1298 tok::kw___is_scalar,
1299 tok::kw___is_sealed,
1300 tok::kw___is_signed,
1301 tok::kw___is_standard_layout,
1302 tok::kw___is_trivial,
1303 tok::kw___is_trivially_assignable,
1304 tok::kw___is_trivially_constructible,
1305 tok::kw___is_trivially_copyable,
1307 tok::kw___is_unsigned,
1309 tok::kw___is_volatile))
1310 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1311 // name of struct templates, but some are keywords in GCC >= 4.3
1312 // and Clang. Therefore, when we see the token sequence "struct
1313 // X", make X into a normal identifier rather than a keyword, to
1314 // allow libstdc++ 4.2 and libc++ to work properly.
1315 TryKeywordIdentFallback(true);
1317 struct PreserveAtomicIdentifierInfoRAII {
1318 PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
1319 : AtomicII(nullptr) {
1322 assert(Tok.is(tok::kw__Atomic));
1323 AtomicII = Tok.getIdentifierInfo();
1324 AtomicII->revertTokenIDToIdentifier();
1325 Tok.setKind(tok::identifier);
1327 ~PreserveAtomicIdentifierInfoRAII() {
1330 AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
1332 IdentifierInfo *AtomicII;
1335 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1336 // implementation for VS2013 uses _Atomic as an identifier for one of the
1337 // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
1338 // '_Atomic' to be a keyword. We are careful to undo this so that clang can
1339 // use '_Atomic' in its own header files.
1340 bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
1341 Tok.is(tok::kw__Atomic) &&
1342 TagType == DeclSpec::TST_struct;
1343 PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
1344 Tok, ShouldChangeAtomicToIdentifier);
1346 // Parse the (optional) nested-name-specifier.
1347 CXXScopeSpec &SS = DS.getTypeSpecScope();
1348 if (getLangOpts().CPlusPlus) {
1349 // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
1350 // is a base-specifier-list.
1351 ColonProtectionRAIIObject X(*this);
1354 bool HasValidSpec = true;
1355 if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(), EnteringContext)) {
1356 DS.SetTypeSpecError();
1357 HasValidSpec = false;
1360 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
1361 Diag(Tok, diag::err_expected) << tok::identifier;
1362 HasValidSpec = false;
1368 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1370 // Parse the (optional) class name or simple-template-id.
1371 IdentifierInfo *Name = nullptr;
1372 SourceLocation NameLoc;
1373 TemplateIdAnnotation *TemplateId = nullptr;
1374 if (Tok.is(tok::identifier)) {
1375 Name = Tok.getIdentifierInfo();
1376 NameLoc = ConsumeToken();
1378 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1379 // The name was supposed to refer to a template, but didn't.
1380 // Eat the template argument list and try to continue parsing this as
1381 // a class (or template thereof).
1382 TemplateArgList TemplateArgs;
1383 SourceLocation LAngleLoc, RAngleLoc;
1384 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1386 TemplateArgs, RAngleLoc)) {
1387 // We couldn't parse the template argument list at all, so don't
1388 // try to give any location information for the list.
1389 LAngleLoc = RAngleLoc = SourceLocation();
1392 Diag(NameLoc, diag::err_explicit_spec_non_template)
1393 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1394 << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc);
1396 // Strip off the last template parameter list if it was empty, since
1397 // we've removed its template argument list.
1398 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1399 if (TemplateParams && TemplateParams->size() > 1) {
1400 TemplateParams->pop_back();
1402 TemplateParams = nullptr;
1403 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1404 = ParsedTemplateInfo::NonTemplate;
1406 } else if (TemplateInfo.Kind
1407 == ParsedTemplateInfo::ExplicitInstantiation) {
1408 // Pretend this is just a forward declaration.
1409 TemplateParams = nullptr;
1410 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1411 = ParsedTemplateInfo::NonTemplate;
1412 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1414 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1418 } else if (Tok.is(tok::annot_template_id)) {
1419 TemplateId = takeTemplateIdAnnotation(Tok);
1420 NameLoc = ConsumeToken();
1422 if (TemplateId->Kind != TNK_Type_template &&
1423 TemplateId->Kind != TNK_Dependent_template_name) {
1424 // The template-name in the simple-template-id refers to
1425 // something other than a class template. Give an appropriate
1426 // error message and skip to the ';'.
1427 SourceRange Range(NameLoc);
1428 if (SS.isNotEmpty())
1429 Range.setBegin(SS.getBeginLoc());
1431 // FIXME: Name may be null here.
1432 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1433 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1435 DS.SetTypeSpecError();
1436 SkipUntil(tok::semi, StopBeforeMatch);
1441 // There are four options here.
1442 // - If we are in a trailing return type, this is always just a reference,
1443 // and we must not try to parse a definition. For instance,
1444 // [] () -> struct S { };
1445 // does not define a type.
1446 // - If we have 'struct foo {...', 'struct foo :...',
1447 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1448 // - If we have 'struct foo;', then this is either a forward declaration
1449 // or a friend declaration, which have to be treated differently.
1450 // - Otherwise we have something like 'struct foo xyz', a reference.
1452 // We also detect these erroneous cases to provide better diagnostic for
1453 // C++11 attributes parsing.
1454 // - attributes follow class name:
1455 // struct foo [[]] {};
1456 // - attributes appear before or after 'final':
1457 // struct foo [[]] final [[]] {};
1459 // However, in type-specifier-seq's, things look like declarations but are
1460 // just references, e.g.
1463 // &T::operator struct s;
1464 // For these, DSC is DSC_type_specifier or DSC_alias_declaration.
1466 // If there are attributes after class name, parse them.
1467 MaybeParseCXX11Attributes(Attributes);
1469 const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
1470 Sema::TagUseKind TUK;
1471 if (DSC == DSC_trailing)
1472 TUK = Sema::TUK_Reference;
1473 else if (Tok.is(tok::l_brace) ||
1474 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1475 (isCXX11FinalKeyword() &&
1476 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1477 if (DS.isFriendSpecified()) {
1478 // C++ [class.friend]p2:
1479 // A class shall not be defined in a friend declaration.
1480 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1481 << SourceRange(DS.getFriendSpecLoc());
1483 // Skip everything up to the semicolon, so that this looks like a proper
1484 // friend class (or template thereof) declaration.
1485 SkipUntil(tok::semi, StopBeforeMatch);
1486 TUK = Sema::TUK_Friend;
1488 // Okay, this is a class definition.
1489 TUK = Sema::TUK_Definition;
1491 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1492 NextToken().is(tok::kw_alignas))) {
1493 // We can't tell if this is a definition or reference
1494 // until we skipped the 'final' and C++11 attribute specifiers.
1495 TentativeParsingAction PA(*this);
1497 // Skip the 'final' keyword.
1500 // Skip C++11 attribute specifiers.
1502 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1504 if (!SkipUntil(tok::r_square, StopAtSemi))
1506 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1509 if (!SkipUntil(tok::r_paren, StopAtSemi))
1516 if (Tok.isOneOf(tok::l_brace, tok::colon))
1517 TUK = Sema::TUK_Definition;
1519 TUK = Sema::TUK_Reference;
1522 } else if (!isTypeSpecifier(DSC) &&
1523 (Tok.is(tok::semi) ||
1524 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1525 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1526 if (Tok.isNot(tok::semi)) {
1527 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1528 // A semicolon was missing after this declaration. Diagnose and recover.
1529 ExpectAndConsume(tok::semi, diag::err_expected_after,
1530 DeclSpec::getSpecifierName(TagType, PPol));
1532 Tok.setKind(tok::semi);
1535 TUK = Sema::TUK_Reference;
1537 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1538 // to caller to handle.
1539 if (TUK != Sema::TUK_Reference) {
1540 // If this is not a reference, then the only possible
1541 // valid place for C++11 attributes to appear here
1542 // is between class-key and class-name. If there are
1543 // any attributes after class-name, we try a fixit to move
1544 // them to the right place.
1545 SourceRange AttrRange = Attributes.Range;
1546 if (AttrRange.isValid()) {
1547 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1549 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1550 CharSourceRange(AttrRange, true))
1551 << FixItHint::CreateRemoval(AttrRange);
1553 // Recover by adding misplaced attributes to the attribute list
1554 // of the class so they can be applied on the class later.
1555 attrs.takeAllFrom(Attributes);
1559 // If this is an elaborated type specifier, and we delayed
1560 // diagnostics before, just merge them into the current pool.
1561 if (shouldDelayDiagsInTag) {
1562 diagsFromTag.done();
1563 if (TUK == Sema::TUK_Reference)
1564 diagsFromTag.redelay();
1567 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1568 TUK != Sema::TUK_Definition)) {
1569 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1570 // We have a declaration or reference to an anonymous class.
1571 Diag(StartLoc, diag::err_anon_type_definition)
1572 << DeclSpec::getSpecifierName(TagType, Policy);
1575 // If we are parsing a definition and stop at a base-clause, continue on
1576 // until the semicolon. Continuing from the comma will just trick us into
1577 // thinking we are seeing a variable declaration.
1578 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1579 SkipUntil(tok::semi, StopBeforeMatch);
1581 SkipUntil(tok::comma, StopAtSemi);
1585 // Create the tag portion of the class or class template.
1586 DeclResult TagOrTempResult = true; // invalid
1587 TypeResult TypeResult = true; // invalid
1590 Sema::SkipBodyInfo SkipBody;
1592 // Explicit specialization, class template partial specialization,
1593 // or explicit instantiation.
1594 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1595 TemplateId->NumArgs);
1596 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1597 TUK == Sema::TUK_Declaration) {
1598 // This is an explicit instantiation of a class template.
1599 ProhibitAttributes(attrs);
1602 = Actions.ActOnExplicitInstantiation(getCurScope(),
1603 TemplateInfo.ExternLoc,
1604 TemplateInfo.TemplateLoc,
1608 TemplateId->Template,
1609 TemplateId->TemplateNameLoc,
1610 TemplateId->LAngleLoc,
1612 TemplateId->RAngleLoc,
1615 // Friend template-ids are treated as references unless
1616 // they have template headers, in which case they're ill-formed
1617 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1618 // We diagnose this error in ActOnClassTemplateSpecialization.
1619 } else if (TUK == Sema::TUK_Reference ||
1620 (TUK == Sema::TUK_Friend &&
1621 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1622 ProhibitAttributes(attrs);
1623 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1625 TemplateId->TemplateKWLoc,
1626 TemplateId->Template,
1627 TemplateId->TemplateNameLoc,
1628 TemplateId->LAngleLoc,
1630 TemplateId->RAngleLoc);
1632 // This is an explicit specialization or a class template
1633 // partial specialization.
1634 TemplateParameterLists FakedParamLists;
1635 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1636 // This looks like an explicit instantiation, because we have
1639 // template class Foo<X>
1641 // but it actually has a definition. Most likely, this was
1642 // meant to be an explicit specialization, but the user forgot
1643 // the '<>' after 'template'.
1644 // It this is friend declaration however, since it cannot have a
1645 // template header, it is most likely that the user meant to
1646 // remove the 'template' keyword.
1647 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1648 "Expected a definition here");
1650 if (TUK == Sema::TUK_Friend) {
1651 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1652 TemplateParams = nullptr;
1654 SourceLocation LAngleLoc =
1655 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1656 Diag(TemplateId->TemplateNameLoc,
1657 diag::err_explicit_instantiation_with_definition)
1658 << SourceRange(TemplateInfo.TemplateLoc)
1659 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1661 // Create a fake template parameter list that contains only
1662 // "template<>", so that we treat this construct as a class
1663 // template specialization.
1664 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1665 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
1667 TemplateParams = &FakedParamLists;
1671 // Build the class template specialization.
1672 TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
1673 getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
1674 *TemplateId, attrs.getList(),
1675 MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
1677 TemplateParams ? TemplateParams->size() : 0),
1680 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1681 TUK == Sema::TUK_Declaration) {
1682 // Explicit instantiation of a member of a class template
1683 // specialization, e.g.,
1685 // template struct Outer<int>::Inner;
1687 ProhibitAttributes(attrs);
1690 = Actions.ActOnExplicitInstantiation(getCurScope(),
1691 TemplateInfo.ExternLoc,
1692 TemplateInfo.TemplateLoc,
1693 TagType, StartLoc, SS, Name,
1694 NameLoc, attrs.getList());
1695 } else if (TUK == Sema::TUK_Friend &&
1696 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1697 ProhibitAttributes(attrs);
1700 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1701 TagType, StartLoc, SS,
1702 Name, NameLoc, attrs.getList(),
1703 MultiTemplateParamsArg(
1704 TemplateParams? &(*TemplateParams)[0]
1706 TemplateParams? TemplateParams->size() : 0));
1708 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1709 ProhibitAttributes(attrs);
1711 if (TUK == Sema::TUK_Definition &&
1712 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1713 // If the declarator-id is not a template-id, issue a diagnostic and
1714 // recover by ignoring the 'template' keyword.
1715 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1716 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1717 TemplateParams = nullptr;
1720 bool IsDependent = false;
1722 // Don't pass down template parameter lists if this is just a tag
1723 // reference. For example, we don't need the template parameters here:
1724 // template <class T> class A *makeA(T t);
1725 MultiTemplateParamsArg TParams;
1726 if (TUK != Sema::TUK_Reference && TemplateParams)
1728 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1730 handleDeclspecAlignBeforeClassKey(attrs, DS, TUK);
1732 // Declaration or definition of a class type
1733 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1734 SS, Name, NameLoc, attrs.getList(), AS,
1735 DS.getModulePrivateSpecLoc(),
1736 TParams, Owned, IsDependent,
1737 SourceLocation(), false,
1738 clang::TypeResult(),
1739 DSC == DSC_type_specifier,
1742 // If ActOnTag said the type was dependent, try again with the
1743 // less common call.
1745 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1746 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1747 SS, Name, StartLoc, NameLoc);
1751 // If there is a body, parse it and inform the actions module.
1752 if (TUK == Sema::TUK_Definition) {
1753 assert(Tok.is(tok::l_brace) ||
1754 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1755 isCXX11FinalKeyword());
1756 if (SkipBody.ShouldSkip)
1757 SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
1758 TagOrTempResult.get());
1759 else if (getLangOpts().CPlusPlus)
1760 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1761 TagOrTempResult.get());
1763 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1766 const char *PrevSpec = nullptr;
1769 if (!TypeResult.isInvalid()) {
1770 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1771 NameLoc.isValid() ? NameLoc : StartLoc,
1772 PrevSpec, DiagID, TypeResult.get(), Policy);
1773 } else if (!TagOrTempResult.isInvalid()) {
1774 Result = DS.SetTypeSpecType(TagType, StartLoc,
1775 NameLoc.isValid() ? NameLoc : StartLoc,
1776 PrevSpec, DiagID, TagOrTempResult.get(), Owned,
1779 DS.SetTypeSpecError();
1784 Diag(StartLoc, DiagID) << PrevSpec;
1786 // At this point, we've successfully parsed a class-specifier in 'definition'
1787 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1788 // going to look at what comes after it to improve error recovery. If an
1789 // impossible token occurs next, we assume that the programmer forgot a ; at
1790 // the end of the declaration and recover that way.
1792 // Also enforce C++ [temp]p3:
1793 // In a template-declaration which defines a class, no declarator
1796 // After a type-specifier, we don't expect a semicolon. This only happens in
1797 // C, since definitions are not permitted in this context in C++.
1798 if (TUK == Sema::TUK_Definition &&
1799 (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
1800 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1801 if (Tok.isNot(tok::semi)) {
1802 const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
1803 ExpectAndConsume(tok::semi, diag::err_expected_after,
1804 DeclSpec::getSpecifierName(TagType, PPol));
1805 // Push this token back into the preprocessor and change our current token
1806 // to ';' so that the rest of the code recovers as though there were an
1807 // ';' after the definition.
1809 Tok.setKind(tok::semi);
1814 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1816 /// base-clause : [C++ class.derived]
1817 /// ':' base-specifier-list
1818 /// base-specifier-list:
1819 /// base-specifier '...'[opt]
1820 /// base-specifier-list ',' base-specifier '...'[opt]
1821 void Parser::ParseBaseClause(Decl *ClassDecl) {
1822 assert(Tok.is(tok::colon) && "Not a base clause");
1825 // Build up an array of parsed base specifiers.
1826 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1829 // Parse a base-specifier.
1830 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1831 if (Result.isInvalid()) {
1832 // Skip the rest of this base specifier, up until the comma or
1834 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
1836 // Add this to our array of base specifiers.
1837 BaseInfo.push_back(Result.get());
1840 // If the next token is a comma, consume it and keep reading
1842 if (!TryConsumeToken(tok::comma))
1846 // Attach the base specifiers
1847 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
1850 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1851 /// one entry in the base class list of a class specifier, for example:
1852 /// class foo : public bar, virtual private baz {
1853 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1855 /// base-specifier: [C++ class.derived]
1856 /// attribute-specifier-seq[opt] base-type-specifier
1857 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
1858 /// base-type-specifier
1859 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
1860 /// base-type-specifier
1861 BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1862 bool IsVirtual = false;
1863 SourceLocation StartLoc = Tok.getLocation();
1865 ParsedAttributesWithRange Attributes(AttrFactory);
1866 MaybeParseCXX11Attributes(Attributes);
1868 // Parse the 'virtual' keyword.
1869 if (TryConsumeToken(tok::kw_virtual))
1872 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1874 // Parse an (optional) access specifier.
1875 AccessSpecifier Access = getAccessSpecifierIfPresent();
1876 if (Access != AS_none)
1879 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1881 // Parse the 'virtual' keyword (again!), in case it came after the
1882 // access specifier.
1883 if (Tok.is(tok::kw_virtual)) {
1884 SourceLocation VirtualLoc = ConsumeToken();
1886 // Complain about duplicate 'virtual'
1887 Diag(VirtualLoc, diag::err_dup_virtual)
1888 << FixItHint::CreateRemoval(VirtualLoc);
1894 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1896 // Parse the class-name.
1898 // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
1899 // implementation for VS2013 uses _Atomic as an identifier for one of the
1900 // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
1901 // parsing the class-name for a base specifier.
1902 if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
1903 NextToken().is(tok::less))
1904 Tok.setKind(tok::identifier);
1906 SourceLocation EndLocation;
1907 SourceLocation BaseLoc;
1908 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1909 if (BaseType.isInvalid())
1912 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1913 // actually part of the base-specifier-list grammar productions, but we
1914 // parse it here for convenience.
1915 SourceLocation EllipsisLoc;
1916 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1918 // Find the complete source range for the base-specifier.
1919 SourceRange Range(StartLoc, EndLocation);
1921 // Notify semantic analysis that we have parsed a complete
1923 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
1924 Access, BaseType.get(), BaseLoc,
1928 /// getAccessSpecifierIfPresent - Determine whether the next token is
1929 /// a C++ access-specifier.
1931 /// access-specifier: [C++ class.derived]
1935 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1936 switch (Tok.getKind()) {
1937 default: return AS_none;
1938 case tok::kw_private: return AS_private;
1939 case tok::kw_protected: return AS_protected;
1940 case tok::kw_public: return AS_public;
1944 /// \brief If the given declarator has any parts for which parsing has to be
1945 /// delayed, e.g., default arguments or an exception-specification, create a
1946 /// late-parsed method declaration record to handle the parsing at the end of
1947 /// the class definition.
1948 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1950 DeclaratorChunk::FunctionTypeInfo &FTI
1951 = DeclaratorInfo.getFunctionTypeInfo();
1952 // If there was a late-parsed exception-specification, we'll need a
1954 bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
1956 if (!NeedLateParse) {
1957 // Look ahead to see if there are any default args
1958 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
1959 auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
1960 if (Param->hasUnparsedDefaultArg()) {
1961 NeedLateParse = true;
1967 if (NeedLateParse) {
1968 // Push this method onto the stack of late-parsed method
1970 auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1971 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1972 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1974 // Stash the exception-specification tokens in the late-pased method.
1975 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
1976 FTI.ExceptionSpecTokens = nullptr;
1978 // Push tokens for each parameter. Those that do not have
1979 // defaults will be NULL.
1980 LateMethod->DefaultArgs.reserve(FTI.NumParams);
1981 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
1982 LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
1983 FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens));
1987 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
1993 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
1994 if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
1995 return VirtSpecifiers::VS_None;
1997 IdentifierInfo *II = Tok.getIdentifierInfo();
1999 // Initialize the contextual keywords.
2001 Ident_final = &PP.getIdentifierTable().get("final");
2002 if (getLangOpts().MicrosoftExt)
2003 Ident_sealed = &PP.getIdentifierTable().get("sealed");
2004 Ident_override = &PP.getIdentifierTable().get("override");
2007 if (II == Ident_override)
2008 return VirtSpecifiers::VS_Override;
2010 if (II == Ident_sealed)
2011 return VirtSpecifiers::VS_Sealed;
2013 if (II == Ident_final)
2014 return VirtSpecifiers::VS_Final;
2016 return VirtSpecifiers::VS_None;
2019 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
2021 /// virt-specifier-seq:
2023 /// virt-specifier-seq virt-specifier
2024 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
2026 SourceLocation FriendLoc) {
2028 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2029 if (Specifier == VirtSpecifiers::VS_None)
2032 if (FriendLoc.isValid()) {
2033 Diag(Tok.getLocation(), diag::err_friend_decl_spec)
2034 << VirtSpecifiers::getSpecifierName(Specifier)
2035 << FixItHint::CreateRemoval(Tok.getLocation())
2036 << SourceRange(FriendLoc, FriendLoc);
2041 // C++ [class.mem]p8:
2042 // A virt-specifier-seq shall contain at most one of each virt-specifier.
2043 const char *PrevSpec = nullptr;
2044 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
2045 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
2047 << FixItHint::CreateRemoval(Tok.getLocation());
2049 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
2050 Specifier == VirtSpecifiers::VS_Sealed)) {
2051 Diag(Tok.getLocation(), diag::err_override_control_interface)
2052 << VirtSpecifiers::getSpecifierName(Specifier);
2053 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
2054 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
2056 Diag(Tok.getLocation(),
2057 getLangOpts().CPlusPlus11
2058 ? diag::warn_cxx98_compat_override_control_keyword
2059 : diag::ext_override_control_keyword)
2060 << VirtSpecifiers::getSpecifierName(Specifier);
2066 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
2067 /// 'final' or Microsoft 'sealed' contextual keyword.
2068 bool Parser::isCXX11FinalKeyword() const {
2069 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
2070 return Specifier == VirtSpecifiers::VS_Final ||
2071 Specifier == VirtSpecifiers::VS_Sealed;
2074 /// \brief Parse a C++ member-declarator up to, but not including, the optional
2075 /// brace-or-equal-initializer or pure-specifier.
2076 bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
2077 Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
2078 LateParsedAttrList &LateParsedAttrs) {
2079 // member-declarator:
2080 // declarator pure-specifier[opt]
2081 // declarator brace-or-equal-initializer[opt]
2082 // identifier[opt] ':' constant-expression
2083 if (Tok.isNot(tok::colon))
2084 ParseDeclarator(DeclaratorInfo);
2086 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
2088 if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
2089 assert(DeclaratorInfo.isPastIdentifier() &&
2090 "don't know where identifier would go yet?");
2091 BitfieldSize = ParseConstantExpression();
2092 if (BitfieldSize.isInvalid())
2093 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2095 ParseOptionalCXX11VirtSpecifierSeq(
2096 VS, getCurrentClass().IsInterface,
2097 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2099 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2102 // If a simple-asm-expr is present, parse it.
2103 if (Tok.is(tok::kw_asm)) {
2105 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2106 if (AsmLabel.isInvalid())
2107 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2109 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2110 DeclaratorInfo.SetRangeEnd(Loc);
2113 // If attributes exist after the declarator, but before an '{', parse them.
2114 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2116 // For compatibility with code written to older Clang, also accept a
2117 // virt-specifier *after* the GNU attributes.
2118 if (BitfieldSize.isUnset() && VS.isUnset()) {
2119 ParseOptionalCXX11VirtSpecifierSeq(
2120 VS, getCurrentClass().IsInterface,
2121 DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
2122 if (!VS.isUnset()) {
2123 // If we saw any GNU-style attributes that are known to GCC followed by a
2124 // virt-specifier, issue a GCC-compat warning.
2125 const AttributeList *Attr = DeclaratorInfo.getAttributes();
2127 if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute())
2128 Diag(Attr->getLoc(), diag::warn_gcc_attribute_location);
2129 Attr = Attr->getNext();
2131 MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
2135 // If this has neither a name nor a bit width, something has gone seriously
2136 // wrong. Skip until the semi-colon or }.
2137 if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
2138 // If so, skip until the semi-colon or a }.
2139 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2145 /// \brief Look for declaration specifiers possibly occurring after C++11
2146 /// virt-specifier-seq and diagnose them.
2147 void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
2149 VirtSpecifiers &VS) {
2150 DeclSpec DS(AttrFactory);
2152 // GNU-style and C++11 attributes are not allowed here, but they will be
2153 // handled by the caller. Diagnose everything else.
2154 ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, false);
2155 D.ExtendWithDeclSpec(DS);
2157 if (D.isFunctionDeclarator()) {
2158 auto &Function = D.getFunctionTypeInfo();
2159 if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
2160 auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual,
2161 const char *FixItName,
2162 SourceLocation SpecLoc,
2163 unsigned* QualifierLoc) {
2164 FixItHint Insertion;
2165 if (DS.getTypeQualifiers() & TypeQual) {
2166 if (!(Function.TypeQuals & TypeQual)) {
2167 std::string Name(FixItName);
2169 Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name.c_str());
2170 Function.TypeQuals |= TypeQual;
2171 *QualifierLoc = SpecLoc.getRawEncoding();
2173 Diag(SpecLoc, diag::err_declspec_after_virtspec)
2175 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2176 << FixItHint::CreateRemoval(SpecLoc)
2180 DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(),
2181 &Function.ConstQualifierLoc);
2182 DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(),
2183 &Function.VolatileQualifierLoc);
2184 DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(),
2185 &Function.RestrictQualifierLoc);
2188 // Parse ref-qualifiers.
2189 bool RefQualifierIsLValueRef = true;
2190 SourceLocation RefQualifierLoc;
2191 if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
2192 const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
2193 FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
2194 Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
2195 Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
2197 Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
2198 << (RefQualifierIsLValueRef ? "&" : "&&")
2199 << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
2200 << FixItHint::CreateRemoval(RefQualifierLoc)
2202 D.SetRangeEnd(RefQualifierLoc);
2207 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
2209 /// member-declaration:
2210 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
2211 /// function-definition ';'[opt]
2212 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
2213 /// using-declaration [TODO]
2214 /// [C++0x] static_assert-declaration
2215 /// template-declaration
2216 /// [GNU] '__extension__' member-declaration
2218 /// member-declarator-list:
2219 /// member-declarator
2220 /// member-declarator-list ',' member-declarator
2222 /// member-declarator:
2223 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
2224 /// declarator constant-initializer[opt]
2225 /// [C++11] declarator brace-or-equal-initializer[opt]
2226 /// identifier[opt] ':' constant-expression
2228 /// virt-specifier-seq:
2230 /// virt-specifier-seq virt-specifier
2240 /// constant-initializer:
2241 /// '=' constant-expression
2243 Parser::DeclGroupPtrTy
2244 Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
2245 AttributeList *AccessAttrs,
2246 const ParsedTemplateInfo &TemplateInfo,
2247 ParsingDeclRAIIObject *TemplateDiags) {
2248 if (Tok.is(tok::at)) {
2249 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
2250 Diag(Tok, diag::err_at_defs_cxx);
2252 Diag(Tok, diag::err_at_in_class);
2255 SkipUntil(tok::r_brace, StopAtSemi);
2256 return DeclGroupPtrTy();
2259 // Turn on colon protection early, while parsing declspec, although there is
2260 // nothing to protect there. It prevents from false errors if error recovery
2261 // incorrectly determines where the declspec ends, as in the example:
2262 // struct A { enum class B { C }; };
2264 // struct D { A::B : C; };
2265 ColonProtectionRAIIObject X(*this);
2267 // Access declarations.
2268 bool MalformedTypeSpec = false;
2269 if (!TemplateInfo.Kind &&
2270 Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
2271 if (TryAnnotateCXXScopeToken())
2272 MalformedTypeSpec = true;
2275 if (Tok.isNot(tok::annot_cxxscope))
2276 isAccessDecl = false;
2277 else if (NextToken().is(tok::identifier))
2278 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
2280 isAccessDecl = NextToken().is(tok::kw_operator);
2283 // Collect the scope specifier token we annotated earlier.
2285 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
2286 /*EnteringContext=*/false);
2288 if (SS.isInvalid()) {
2289 SkipUntil(tok::semi);
2290 return DeclGroupPtrTy();
2293 // Try to parse an unqualified-id.
2294 SourceLocation TemplateKWLoc;
2296 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
2297 TemplateKWLoc, Name)) {
2298 SkipUntil(tok::semi);
2299 return DeclGroupPtrTy();
2302 // TODO: recover from mistakenly-qualified operator declarations.
2303 if (ExpectAndConsume(tok::semi, diag::err_expected_after,
2304 "access declaration")) {
2305 SkipUntil(tok::semi);
2306 return DeclGroupPtrTy();
2309 return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
2311 /* HasUsingKeyword */ false, SourceLocation(), SS, Name,
2312 /* AttrList */ nullptr,
2313 /* HasTypenameKeyword */ false, SourceLocation())));
2317 // static_assert-declaration. A templated static_assert declaration is
2318 // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
2319 if (!TemplateInfo.Kind &&
2320 Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
2321 SourceLocation DeclEnd;
2322 return DeclGroupPtrTy::make(
2323 DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
2326 if (Tok.is(tok::kw_template)) {
2327 assert(!TemplateInfo.TemplateParams &&
2328 "Nested template improperly parsed?");
2329 SourceLocation DeclEnd;
2330 return DeclGroupPtrTy::make(
2331 DeclGroupRef(ParseDeclarationStartingWithTemplate(
2332 Declarator::MemberContext, DeclEnd, AS, AccessAttrs)));
2335 // Handle: member-declaration ::= '__extension__' member-declaration
2336 if (Tok.is(tok::kw___extension__)) {
2337 // __extension__ silences extension warnings in the subexpression.
2338 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2340 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2341 TemplateInfo, TemplateDiags);
2344 ParsedAttributesWithRange attrs(AttrFactory);
2345 ParsedAttributesWithRange FnAttrs(AttrFactory);
2346 // Optional C++11 attribute-specifier
2347 MaybeParseCXX11Attributes(attrs);
2348 // We need to keep these attributes for future diagnostic
2349 // before they are taken over by declaration specifier.
2350 FnAttrs.addAll(attrs.getList());
2351 FnAttrs.Range = attrs.Range;
2353 MaybeParseMicrosoftAttributes(attrs);
2355 if (Tok.is(tok::kw_using)) {
2356 ProhibitAttributes(attrs);
2359 SourceLocation UsingLoc = ConsumeToken();
2361 if (Tok.is(tok::kw_namespace)) {
2362 Diag(UsingLoc, diag::err_using_namespace_in_class);
2363 SkipUntil(tok::semi, StopBeforeMatch);
2364 return DeclGroupPtrTy();
2366 SourceLocation DeclEnd;
2367 // Otherwise, it must be a using-declaration or an alias-declaration.
2368 return DeclGroupPtrTy::make(DeclGroupRef(ParseUsingDeclaration(
2369 Declarator::MemberContext, TemplateInfo, UsingLoc, DeclEnd, AS)));
2372 // Hold late-parsed attributes so we can attach a Decl to them later.
2373 LateParsedAttrList CommonLateParsedAttrs;
2375 // decl-specifier-seq:
2376 // Parse the common declaration-specifiers piece.
2377 ParsingDeclSpec DS(*this, TemplateDiags);
2378 DS.takeAttributesFrom(attrs);
2379 if (MalformedTypeSpec)
2380 DS.SetTypeSpecError();
2382 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2383 &CommonLateParsedAttrs);
2385 // Turn off colon protection that was set for declspec.
2388 // If we had a free-standing type definition with a missing semicolon, we
2389 // may get this far before the problem becomes obvious.
2390 if (DS.hasTagDefinition() &&
2391 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2392 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2393 &CommonLateParsedAttrs))
2394 return DeclGroupPtrTy();
2396 MultiTemplateParamsArg TemplateParams(
2397 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
2399 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2401 if (TryConsumeToken(tok::semi)) {
2402 if (DS.isFriendSpecified())
2403 ProhibitAttributes(FnAttrs);
2406 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
2407 DS.complete(TheDecl);
2408 return DeclGroupPtrTy::make(DeclGroupRef(TheDecl));
2411 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2414 // Hold late-parsed attributes so we can attach a Decl to them later.
2415 LateParsedAttrList LateParsedAttrs;
2417 SourceLocation EqualLoc;
2418 SourceLocation PureSpecLoc;
2420 auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
2421 if (Tok.isNot(tok::equal))
2424 auto &Zero = NextToken();
2425 SmallString<8> Buffer;
2426 if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
2427 PP.getSpelling(Zero, Buffer) != "0")
2430 auto &After = GetLookAheadToken(2);
2431 if (!After.isOneOf(tok::semi, tok::comma) &&
2432 !(AllowDefinition &&
2433 After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
2436 EqualLoc = ConsumeToken();
2437 PureSpecLoc = ConsumeToken();
2441 SmallVector<Decl *, 8> DeclsInGroup;
2442 ExprResult BitfieldSize;
2443 bool ExpectSemi = true;
2445 // Parse the first declarator.
2446 if (ParseCXXMemberDeclaratorBeforeInitializer(
2447 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
2448 TryConsumeToken(tok::semi);
2449 return DeclGroupPtrTy();
2452 // Check for a member function definition.
2453 if (BitfieldSize.isUnset()) {
2454 // MSVC permits pure specifier on inline functions defined at class scope.
2455 // Hence check for =0 before checking for function definition.
2456 if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
2457 TryConsumePureSpecifier(/*AllowDefinition*/ true);
2459 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2460 // function-definition:
2462 // In C++11, a non-function declarator followed by an open brace is a
2463 // braced-init-list for an in-class member initialization, not an
2464 // erroneous function definition.
2465 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2466 DefinitionKind = FDK_Definition;
2467 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2468 if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
2469 DefinitionKind = FDK_Definition;
2470 } else if (Tok.is(tok::equal)) {
2471 const Token &KW = NextToken();
2472 if (KW.is(tok::kw_default))
2473 DefinitionKind = FDK_Defaulted;
2474 else if (KW.is(tok::kw_delete))
2475 DefinitionKind = FDK_Deleted;
2478 DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
2480 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2481 // to a friend declaration, that declaration shall be a definition.
2482 if (DeclaratorInfo.isFunctionDeclarator() &&
2483 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2484 // Diagnose attributes that appear before decl specifier:
2485 // [[]] friend int foo();
2486 ProhibitAttributes(FnAttrs);
2489 if (DefinitionKind != FDK_Declaration) {
2490 if (!DeclaratorInfo.isFunctionDeclarator()) {
2491 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2493 SkipUntil(tok::r_brace);
2495 // Consume the optional ';'
2496 TryConsumeToken(tok::semi);
2498 return DeclGroupPtrTy();
2501 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2502 Diag(DeclaratorInfo.getIdentifierLoc(),
2503 diag::err_function_declared_typedef);
2505 // Recover by treating the 'typedef' as spurious.
2506 DS.ClearStorageClassSpecs();
2510 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2514 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2515 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2517 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2518 LateParsedAttrs[i]->addDecl(FunDecl);
2521 LateParsedAttrs.clear();
2523 // Consume the ';' - it's optional unless we have a delete or default
2524 if (Tok.is(tok::semi))
2525 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2527 return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
2531 // member-declarator-list:
2532 // member-declarator
2533 // member-declarator-list ',' member-declarator
2536 InClassInitStyle HasInClassInit = ICIS_NoInit;
2537 bool HasStaticInitializer = false;
2538 if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
2539 if (BitfieldSize.get()) {
2540 Diag(Tok, diag::err_bitfield_member_init);
2541 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2542 } else if (DeclaratorInfo.isDeclarationOfFunction()) {
2543 // It's a pure-specifier.
2544 if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
2545 // Parse it as an expression so that Sema can diagnose it.
2546 HasStaticInitializer = true;
2547 } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2548 DeclSpec::SCS_static &&
2549 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2550 DeclSpec::SCS_typedef &&
2551 !DS.isFriendSpecified()) {
2552 // It's a default member initializer.
2553 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2555 HasStaticInitializer = true;
2559 // NOTE: If Sema is the Action module and declarator is an instance field,
2560 // this call will *not* return the created decl; It will return null.
2561 // See Sema::ActOnCXXMemberDeclarator for details.
2563 NamedDecl *ThisDecl = nullptr;
2564 if (DS.isFriendSpecified()) {
2565 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2566 // to a friend declaration, that declaration shall be a definition.
2568 // Diagnose attributes that appear in a friend member function declarator:
2569 // friend int foo [[]] ();
2570 SmallVector<SourceRange, 4> Ranges;
2571 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2572 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2573 E = Ranges.end(); I != E; ++I)
2574 Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
2576 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2579 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2583 VS, HasInClassInit);
2585 if (VarTemplateDecl *VT =
2586 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
2587 // Re-direct this decl to refer to the templated decl so that we can
2589 ThisDecl = VT->getTemplatedDecl();
2591 if (ThisDecl && AccessAttrs)
2592 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2595 // Error recovery might have converted a non-static member into a static
2597 if (HasInClassInit != ICIS_NoInit &&
2598 DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
2599 DeclSpec::SCS_static) {
2600 HasInClassInit = ICIS_NoInit;
2601 HasStaticInitializer = true;
2604 if (ThisDecl && PureSpecLoc.isValid())
2605 Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
2607 // Handle the initializer.
2608 if (HasInClassInit != ICIS_NoInit) {
2609 // The initializer was deferred; parse it and cache the tokens.
2610 Diag(Tok, getLangOpts().CPlusPlus11
2611 ? diag::warn_cxx98_compat_nonstatic_member_init
2612 : diag::ext_nonstatic_member_init);
2614 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2615 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2616 // declarator is followed by an initializer.
2618 // A brace-or-equal-initializer for a member-declarator is not an
2619 // initializer in the grammar, so this is ill-formed.
2620 Diag(Tok, diag::err_incomplete_array_member_init);
2621 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2623 // Avoid later warnings about a class member of incomplete type.
2625 ThisDecl->setInvalidDecl();
2627 ParseCXXNonStaticMemberInitializer(ThisDecl);
2628 } else if (HasStaticInitializer) {
2629 // Normal initializer.
2630 ExprResult Init = ParseCXXMemberInitializer(
2631 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2633 if (Init.isInvalid())
2634 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2636 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2637 DS.containsPlaceholderType());
2638 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2640 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
2643 if (!ThisDecl->isInvalidDecl()) {
2644 // Set the Decl for any late parsed attributes
2645 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2646 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2648 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2649 LateParsedAttrs[i]->addDecl(ThisDecl);
2651 Actions.FinalizeDeclaration(ThisDecl);
2652 DeclsInGroup.push_back(ThisDecl);
2654 if (DeclaratorInfo.isFunctionDeclarator() &&
2655 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2656 DeclSpec::SCS_typedef)
2657 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2659 LateParsedAttrs.clear();
2661 DeclaratorInfo.complete(ThisDecl);
2663 // If we don't have a comma, it is either the end of the list (a ';')
2664 // or an error, bail out.
2665 SourceLocation CommaLoc;
2666 if (!TryConsumeToken(tok::comma, CommaLoc))
2669 if (Tok.isAtStartOfLine() &&
2670 !MightBeDeclarator(Declarator::MemberContext)) {
2671 // This comma was followed by a line-break and something which can't be
2672 // the start of a declarator. The comma was probably a typo for a
2674 Diag(CommaLoc, diag::err_expected_semi_declaration)
2675 << FixItHint::CreateReplacement(CommaLoc, ";");
2680 // Parse the next declarator.
2681 DeclaratorInfo.clear();
2683 BitfieldSize = ExprResult(/*Invalid=*/false);
2684 EqualLoc = PureSpecLoc = SourceLocation();
2685 DeclaratorInfo.setCommaLoc(CommaLoc);
2687 // GNU attributes are allowed before the second and subsequent declarator.
2688 MaybeParseGNUAttributes(DeclaratorInfo);
2690 if (ParseCXXMemberDeclaratorBeforeInitializer(
2691 DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
2696 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2697 // Skip to end of block or statement.
2698 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2699 // If we stopped at a ';', eat it.
2700 TryConsumeToken(tok::semi);
2701 return DeclGroupPtrTy();
2704 return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2707 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
2708 /// Also detect and reject any attempted defaulted/deleted function definition.
2709 /// The location of the '=', if any, will be placed in EqualLoc.
2711 /// This does not check for a pure-specifier; that's handled elsewhere.
2713 /// brace-or-equal-initializer:
2714 /// '=' initializer-expression
2715 /// braced-init-list
2717 /// initializer-clause:
2718 /// assignment-expression
2719 /// braced-init-list
2721 /// defaulted/deleted function-definition:
2725 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2726 /// be a constant-expression.
2727 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2728 SourceLocation &EqualLoc) {
2729 assert(Tok.isOneOf(tok::equal, tok::l_brace)
2730 && "Data member initializer not starting with '=' or '{'");
2732 EnterExpressionEvaluationContext Context(Actions,
2733 Sema::PotentiallyEvaluated,
2735 if (TryConsumeToken(tok::equal, EqualLoc)) {
2736 if (Tok.is(tok::kw_delete)) {
2737 // In principle, an initializer of '= delete p;' is legal, but it will
2738 // never type-check. It's better to diagnose it as an ill-formed expression
2739 // than as an ill-formed deleted non-function member.
2740 // An initializer of '= delete p, foo' will never be parsed, because
2741 // a top-level comma always ends the initializer expression.
2742 const Token &Next = NextToken();
2743 if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
2745 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2748 Diag(ConsumeToken(), diag::err_deleted_non_function);
2751 } else if (Tok.is(tok::kw_default)) {
2753 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2756 Diag(ConsumeToken(), diag::err_default_special_members);
2760 if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
2761 Diag(Tok, diag::err_ms_property_initializer) << PD;
2764 return ParseInitializer();
2767 void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
2768 SourceLocation AttrFixitLoc,
2769 unsigned TagType, Decl *TagDecl) {
2770 // Skip the optional 'final' keyword.
2771 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2772 assert(isCXX11FinalKeyword() && "not a class definition");
2775 // Diagnose any C++11 attributes after 'final' keyword.
2776 // We deliberately discard these attributes.
2777 ParsedAttributesWithRange Attrs(AttrFactory);
2778 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2780 // This can only happen if we had malformed misplaced attributes;
2781 // we only get called if there is a colon or left-brace after the
2783 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
2787 // Skip the base clauses. This requires actually parsing them, because
2788 // otherwise we can't be sure where they end (a left brace may appear
2789 // within a template argument).
2790 if (Tok.is(tok::colon)) {
2791 // Enter the scope of the class so that we can correctly parse its bases.
2792 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2793 ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
2794 TagType == DeclSpec::TST_interface);
2796 Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
2798 // Parse the bases but don't attach them to the class.
2799 ParseBaseClause(nullptr);
2801 Actions.ActOnTagFinishSkippedDefinition(OldContext);
2803 if (!Tok.is(tok::l_brace)) {
2804 Diag(PP.getLocForEndOfToken(PrevTokLocation),
2805 diag::err_expected_lbrace_after_base_specifiers);
2811 assert(Tok.is(tok::l_brace));
2812 BalancedDelimiterTracker T(*this, tok::l_brace);
2816 // Parse and discard any trailing attributes.
2817 ParsedAttributes Attrs(AttrFactory);
2818 if (Tok.is(tok::kw___attribute))
2819 MaybeParseGNUAttributes(Attrs);
2822 Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
2823 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
2824 DeclSpec::TST TagType, Decl *TagDecl) {
2825 if (getLangOpts().MicrosoftExt &&
2826 Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
2827 ParseMicrosoftIfExistsClassDeclaration(TagType, AS);
2828 return DeclGroupPtrTy();
2831 // Check for extraneous top-level semicolon.
2832 if (Tok.is(tok::semi)) {
2833 ConsumeExtraSemi(InsideStruct, TagType);
2834 return DeclGroupPtrTy();
2837 if (Tok.is(tok::annot_pragma_vis)) {
2838 HandlePragmaVisibility();
2839 return DeclGroupPtrTy();
2842 if (Tok.is(tok::annot_pragma_pack)) {
2844 return DeclGroupPtrTy();
2847 if (Tok.is(tok::annot_pragma_align)) {
2848 HandlePragmaAlign();
2849 return DeclGroupPtrTy();
2852 if (Tok.is(tok::annot_pragma_ms_pointers_to_members)) {
2853 HandlePragmaMSPointersToMembers();
2854 return DeclGroupPtrTy();
2857 if (Tok.is(tok::annot_pragma_ms_pragma)) {
2858 HandlePragmaMSPragma();
2859 return DeclGroupPtrTy();
2862 if (Tok.is(tok::annot_pragma_ms_vtordisp)) {
2863 HandlePragmaMSVtorDisp();
2864 return DeclGroupPtrTy();
2867 // If we see a namespace here, a close brace was missing somewhere.
2868 if (Tok.is(tok::kw_namespace)) {
2869 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
2870 return DeclGroupPtrTy();
2873 AccessSpecifier NewAS = getAccessSpecifierIfPresent();
2874 if (NewAS != AS_none) {
2875 // Current token is a C++ access specifier.
2877 SourceLocation ASLoc = Tok.getLocation();
2878 unsigned TokLength = Tok.getLength();
2880 AccessAttrs.clear();
2881 MaybeParseGNUAttributes(AccessAttrs);
2883 SourceLocation EndLoc;
2884 if (TryConsumeToken(tok::colon, EndLoc)) {
2885 } else if (TryConsumeToken(tok::semi, EndLoc)) {
2886 Diag(EndLoc, diag::err_expected)
2887 << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
2889 EndLoc = ASLoc.getLocWithOffset(TokLength);
2890 Diag(EndLoc, diag::err_expected)
2891 << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
2894 // The Microsoft extension __interface does not permit non-public
2895 // access specifiers.
2896 if (TagType == DeclSpec::TST_interface && AS != AS_public) {
2897 Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
2900 if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc,
2901 AccessAttrs.getList())) {
2902 // found another attribute than only annotations
2903 AccessAttrs.clear();
2906 return DeclGroupPtrTy();
2909 if (Tok.is(tok::annot_pragma_openmp))
2910 return ParseOpenMPDeclarativeDirective();
2912 // Parse all the comma separated declarators.
2913 return ParseCXXClassMemberDeclaration(AS, AccessAttrs.getList());
2916 /// ParseCXXMemberSpecification - Parse the class definition.
2918 /// member-specification:
2919 /// member-declaration member-specification[opt]
2920 /// access-specifier ':' member-specification[opt]
2922 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2923 SourceLocation AttrFixitLoc,
2924 ParsedAttributesWithRange &Attrs,
2925 unsigned TagType, Decl *TagDecl) {
2926 assert((TagType == DeclSpec::TST_struct ||
2927 TagType == DeclSpec::TST_interface ||
2928 TagType == DeclSpec::TST_union ||
2929 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2931 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2932 "parsing struct/union/class body");
2934 // Determine whether this is a non-nested class. Note that local
2935 // classes are *not* considered to be nested classes.
2936 bool NonNestedClass = true;
2937 if (!ClassStack.empty()) {
2938 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2939 if (S->isClassScope()) {
2940 // We're inside a class scope, so this is a nested class.
2941 NonNestedClass = false;
2943 // The Microsoft extension __interface does not permit nested classes.
2944 if (getCurrentClass().IsInterface) {
2945 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2947 << (isa<NamedDecl>(TagDecl)
2948 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2954 if ((S->getFlags() & Scope::FnScope))
2955 // If we're in a function or function template then this is a local
2956 // class rather than a nested class.
2961 // Enter a scope for the class.
2962 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2964 // Note that we are parsing a new (potentially-nested) class definition.
2965 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2966 TagType == DeclSpec::TST_interface);
2969 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2971 SourceLocation FinalLoc;
2972 bool IsFinalSpelledSealed = false;
2974 // Parse the optional 'final' keyword.
2975 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2976 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2977 assert((Specifier == VirtSpecifiers::VS_Final ||
2978 Specifier == VirtSpecifiers::VS_Sealed) &&
2979 "not a class definition");
2980 FinalLoc = ConsumeToken();
2981 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
2983 if (TagType == DeclSpec::TST_interface)
2984 Diag(FinalLoc, diag::err_override_control_interface)
2985 << VirtSpecifiers::getSpecifierName(Specifier);
2986 else if (Specifier == VirtSpecifiers::VS_Final)
2987 Diag(FinalLoc, getLangOpts().CPlusPlus11
2988 ? diag::warn_cxx98_compat_override_control_keyword
2989 : diag::ext_override_control_keyword)
2990 << VirtSpecifiers::getSpecifierName(Specifier);
2991 else if (Specifier == VirtSpecifiers::VS_Sealed)
2992 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
2994 // Parse any C++11 attributes after 'final' keyword.
2995 // These attributes are not allowed to appear here,
2996 // and the only possible place for them to appertain
2997 // to the class would be between class-key and class-name.
2998 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
3000 // ParseClassSpecifier() does only a superficial check for attributes before
3001 // deciding to call this method. For example, for
3002 // `class C final alignas ([l) {` it will decide that this looks like a
3003 // misplaced attribute since it sees `alignas '(' ')'`. But the actual
3004 // attribute parsing code will try to parse the '[' as a constexpr lambda
3005 // and consume enough tokens that the alignas parsing code will eat the
3006 // opening '{'. So bail out if the next token isn't one we expect.
3007 if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
3009 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3014 if (Tok.is(tok::colon)) {
3015 ParseBaseClause(TagDecl);
3016 if (!Tok.is(tok::l_brace)) {
3017 bool SuggestFixIt = false;
3018 SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
3019 if (Tok.isAtStartOfLine()) {
3020 switch (Tok.getKind()) {
3021 case tok::kw_private:
3022 case tok::kw_protected:
3023 case tok::kw_public:
3024 SuggestFixIt = NextToken().getKind() == tok::colon;
3026 case tok::kw_static_assert:
3029 // base-clause can have simple-template-id; 'template' can't be there
3030 case tok::kw_template:
3031 SuggestFixIt = true;
3033 case tok::identifier:
3034 SuggestFixIt = isConstructorDeclarator(true);
3037 SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
3041 DiagnosticBuilder LBraceDiag =
3042 Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
3044 LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
3045 // Try recovering from missing { after base-clause.
3047 Tok.setKind(tok::l_brace);
3050 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
3056 assert(Tok.is(tok::l_brace));
3057 BalancedDelimiterTracker T(*this, tok::l_brace);
3061 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
3062 IsFinalSpelledSealed,
3063 T.getOpenLocation());
3065 // C++ 11p3: Members of a class defined with the keyword class are private
3066 // by default. Members of a class defined with the keywords struct or union
3067 // are public by default.
3068 AccessSpecifier CurAS;
3069 if (TagType == DeclSpec::TST_class)
3073 ParsedAttributesWithRange AccessAttrs(AttrFactory);
3076 // While we still have something to read, read the member-declarations.
3077 while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
3078 Tok.isNot(tok::eof)) {
3079 // Each iteration of this loop reads one member-declaration.
3080 ParseCXXClassMemberDeclarationWithPragmas(
3081 CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
3085 SkipUntil(tok::r_brace);
3088 // If attributes exist after class contents, parse them.
3089 ParsedAttributes attrs(AttrFactory);
3090 MaybeParseGNUAttributes(attrs);
3093 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
3094 T.getOpenLocation(),
3095 T.getCloseLocation(),
3098 // C++11 [class.mem]p2:
3099 // Within the class member-specification, the class is regarded as complete
3100 // within function bodies, default arguments, exception-specifications, and
3101 // brace-or-equal-initializers for non-static data members (including such
3102 // things in nested classes).
3103 if (TagDecl && NonNestedClass) {
3104 // We are not inside a nested class. This class and its nested classes
3105 // are complete and we can parse the delayed portions of method
3106 // declarations and the lexed inline method definitions, along with any
3107 // delayed attributes.
3108 SourceLocation SavedPrevTokLocation = PrevTokLocation;
3109 ParseLexedAttributes(getCurrentClass());
3110 ParseLexedMethodDeclarations(getCurrentClass());
3112 // We've finished with all pending member declarations.
3113 Actions.ActOnFinishCXXMemberDecls();
3115 ParseLexedMemberInitializers(getCurrentClass());
3116 ParseLexedMethodDefs(getCurrentClass());
3117 PrevTokLocation = SavedPrevTokLocation;
3119 // We've finished parsing everything, including default argument
3121 Actions.ActOnFinishCXXNonNestedClass(TagDecl);
3125 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
3126 T.getCloseLocation());
3128 // Leave the class scope.
3133 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
3134 assert(Tok.is(tok::kw_namespace));
3136 // FIXME: Suggest where the close brace should have gone by looking
3137 // at indentation changes within the definition body.
3138 Diag(D->getLocation(),
3139 diag::err_missing_end_of_definition) << D;
3140 Diag(Tok.getLocation(),
3141 diag::note_missing_end_of_definition_before) << D;
3143 // Push '};' onto the token stream to recover.
3147 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
3148 Tok.setKind(tok::semi);
3151 Tok.setKind(tok::r_brace);
3154 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
3155 /// which explicitly initializes the members or base classes of a
3156 /// class (C++ [class.base.init]). For example, the three initializers
3157 /// after the ':' in the Derived constructor below:
3161 /// class Derived : Base {
3165 /// Derived(float f) : Base(), x(17), f(f) { }
3169 /// [C++] ctor-initializer:
3170 /// ':' mem-initializer-list
3172 /// [C++] mem-initializer-list:
3173 /// mem-initializer ...[opt]
3174 /// mem-initializer ...[opt] , mem-initializer-list
3175 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
3176 assert(Tok.is(tok::colon) &&
3177 "Constructor initializer always starts with ':'");
3179 // Poison the SEH identifiers so they are flagged as illegal in constructor
3181 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
3182 SourceLocation ColonLoc = ConsumeToken();
3184 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
3185 bool AnyErrors = false;
3188 if (Tok.is(tok::code_completion)) {
3189 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
3191 return cutOffParsing();
3193 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
3194 if (!MemInit.isInvalid())
3195 MemInitializers.push_back(MemInit.get());
3200 if (Tok.is(tok::comma))
3202 else if (Tok.is(tok::l_brace))
3204 // If the next token looks like a base or member initializer, assume that
3205 // we're just missing a comma.
3206 else if (Tok.isOneOf(tok::identifier, tok::coloncolon)) {
3207 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
3208 Diag(Loc, diag::err_ctor_init_missing_comma)
3209 << FixItHint::CreateInsertion(Loc, ", ");
3211 // Skip over garbage, until we get to '{'. Don't eat the '{'.
3212 Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
3214 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
3219 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
3223 /// ParseMemInitializer - Parse a C++ member initializer, which is
3224 /// part of a constructor initializer that explicitly initializes one
3225 /// member or base class (C++ [class.base.init]). See
3226 /// ParseConstructorInitializer for an example.
3228 /// [C++] mem-initializer:
3229 /// mem-initializer-id '(' expression-list[opt] ')'
3230 /// [C++0x] mem-initializer-id braced-init-list
3232 /// [C++] mem-initializer-id:
3233 /// '::'[opt] nested-name-specifier[opt] class-name
3235 MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
3236 // parse '::'[opt] nested-name-specifier[opt]
3238 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
3239 ParsedType TemplateTypeTy;
3240 if (Tok.is(tok::annot_template_id)) {
3241 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3242 if (TemplateId->Kind == TNK_Type_template ||
3243 TemplateId->Kind == TNK_Dependent_template_name) {
3244 AnnotateTemplateIdTokenAsType();
3245 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
3246 TemplateTypeTy = getTypeAnnotation(Tok);
3249 // Uses of decltype will already have been converted to annot_decltype by
3250 // ParseOptionalCXXScopeSpecifier at this point.
3251 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
3252 && Tok.isNot(tok::annot_decltype)) {
3253 Diag(Tok, diag::err_expected_member_or_base_name);
3257 IdentifierInfo *II = nullptr;
3258 DeclSpec DS(AttrFactory);
3259 SourceLocation IdLoc = Tok.getLocation();
3260 if (Tok.is(tok::annot_decltype)) {
3261 // Get the decltype expression, if there is one.
3262 ParseDecltypeSpecifier(DS);
3264 if (Tok.is(tok::identifier))
3265 // Get the identifier. This may be a member name or a class name,
3266 // but we'll let the semantic analysis determine which it is.
3267 II = Tok.getIdentifierInfo();
3273 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3274 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3276 ExprResult InitList = ParseBraceInitializer();
3277 if (InitList.isInvalid())
3280 SourceLocation EllipsisLoc;
3281 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3283 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3284 TemplateTypeTy, DS, IdLoc,
3285 InitList.get(), EllipsisLoc);
3286 } else if(Tok.is(tok::l_paren)) {
3287 BalancedDelimiterTracker T(*this, tok::l_paren);
3290 // Parse the optional expression-list.
3291 ExprVector ArgExprs;
3292 CommaLocsTy CommaLocs;
3293 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
3294 SkipUntil(tok::r_paren, StopAtSemi);
3300 SourceLocation EllipsisLoc;
3301 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3303 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
3304 TemplateTypeTy, DS, IdLoc,
3305 T.getOpenLocation(), ArgExprs,
3306 T.getCloseLocation(), EllipsisLoc);
3309 if (getLangOpts().CPlusPlus11)
3310 return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
3312 return Diag(Tok, diag::err_expected) << tok::l_paren;
3315 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
3317 /// exception-specification:
3318 /// dynamic-exception-specification
3319 /// noexcept-specification
3321 /// noexcept-specification:
3323 /// 'noexcept' '(' constant-expression ')'
3324 ExceptionSpecificationType
3325 Parser::tryParseExceptionSpecification(bool Delayed,
3326 SourceRange &SpecificationRange,
3327 SmallVectorImpl<ParsedType> &DynamicExceptions,
3328 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
3329 ExprResult &NoexceptExpr,
3330 CachedTokens *&ExceptionSpecTokens) {
3331 ExceptionSpecificationType Result = EST_None;
3332 ExceptionSpecTokens = nullptr;
3334 // Handle delayed parsing of exception-specifications.
3336 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
3339 // Consume and cache the starting token.
3340 bool IsNoexcept = Tok.is(tok::kw_noexcept);
3341 Token StartTok = Tok;
3342 SpecificationRange = SourceRange(ConsumeToken());
3345 if (!Tok.is(tok::l_paren)) {
3346 // If this is a bare 'noexcept', we're done.
3348 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3349 NoexceptExpr = nullptr;
3350 return EST_BasicNoexcept;
3353 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3354 return EST_DynamicNone;
3357 // Cache the tokens for the exception-specification.
3358 ExceptionSpecTokens = new CachedTokens;
3359 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
3360 ExceptionSpecTokens->push_back(Tok); // '('
3361 SpecificationRange.setEnd(ConsumeParen()); // '('
3363 ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
3364 /*StopAtSemi=*/true,
3365 /*ConsumeFinalToken=*/true);
3366 SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
3368 return EST_Unparsed;
3371 // See if there's a dynamic specification.
3372 if (Tok.is(tok::kw_throw)) {
3373 Result = ParseDynamicExceptionSpecification(SpecificationRange,
3375 DynamicExceptionRanges);
3376 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
3377 "Produced different number of exception types and ranges.");
3380 // If there's no noexcept specification, we're done.
3381 if (Tok.isNot(tok::kw_noexcept))
3384 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
3386 // If we already had a dynamic specification, parse the noexcept for,
3387 // recovery, but emit a diagnostic and don't store the results.
3388 SourceRange NoexceptRange;
3389 ExceptionSpecificationType NoexceptType = EST_None;
3391 SourceLocation KeywordLoc = ConsumeToken();
3392 if (Tok.is(tok::l_paren)) {
3393 // There is an argument.
3394 BalancedDelimiterTracker T(*this, tok::l_paren);
3396 NoexceptType = EST_ComputedNoexcept;
3397 NoexceptExpr = ParseConstantExpression();
3399 // The argument must be contextually convertible to bool. We use
3400 // ActOnBooleanCondition for this purpose.
3401 if (!NoexceptExpr.isInvalid()) {
3402 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
3403 NoexceptExpr.get());
3404 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
3406 NoexceptType = EST_None;
3409 // There is no argument.
3410 NoexceptType = EST_BasicNoexcept;
3411 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
3414 if (Result == EST_None) {
3415 SpecificationRange = NoexceptRange;
3416 Result = NoexceptType;
3418 // If there's a dynamic specification after a noexcept specification,
3419 // parse that and ignore the results.
3420 if (Tok.is(tok::kw_throw)) {
3421 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3422 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
3423 DynamicExceptionRanges);
3426 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
3432 static void diagnoseDynamicExceptionSpecification(
3433 Parser &P, SourceRange Range, bool IsNoexcept) {
3434 if (P.getLangOpts().CPlusPlus11) {
3435 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
3436 P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
3437 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
3438 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3442 /// ParseDynamicExceptionSpecification - Parse a C++
3443 /// dynamic-exception-specification (C++ [except.spec]).
3445 /// dynamic-exception-specification:
3446 /// 'throw' '(' type-id-list [opt] ')'
3447 /// [MS] 'throw' '(' '...' ')'
3450 /// type-id ... [opt]
3451 /// type-id-list ',' type-id ... [opt]
3453 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3454 SourceRange &SpecificationRange,
3455 SmallVectorImpl<ParsedType> &Exceptions,
3456 SmallVectorImpl<SourceRange> &Ranges) {
3457 assert(Tok.is(tok::kw_throw) && "expected throw");
3459 SpecificationRange.setBegin(ConsumeToken());
3460 BalancedDelimiterTracker T(*this, tok::l_paren);
3461 if (T.consumeOpen()) {
3462 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3463 SpecificationRange.setEnd(SpecificationRange.getBegin());
3464 return EST_DynamicNone;
3467 // Parse throw(...), a Microsoft extension that means "this function
3468 // can throw anything".
3469 if (Tok.is(tok::ellipsis)) {
3470 SourceLocation EllipsisLoc = ConsumeToken();
3471 if (!getLangOpts().MicrosoftExt)
3472 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3474 SpecificationRange.setEnd(T.getCloseLocation());
3475 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3479 // Parse the sequence of type-ids.
3481 while (Tok.isNot(tok::r_paren)) {
3482 TypeResult Res(ParseTypeName(&Range));
3484 if (Tok.is(tok::ellipsis)) {
3485 // C++0x [temp.variadic]p5:
3486 // - In a dynamic-exception-specification (15.4); the pattern is a
3488 SourceLocation Ellipsis = ConsumeToken();
3489 Range.setEnd(Ellipsis);
3490 if (!Res.isInvalid())
3491 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3494 if (!Res.isInvalid()) {
3495 Exceptions.push_back(Res.get());
3496 Ranges.push_back(Range);
3499 if (!TryConsumeToken(tok::comma))
3504 SpecificationRange.setEnd(T.getCloseLocation());
3505 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3506 Exceptions.empty());
3507 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3510 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3511 /// function declaration.
3512 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3513 assert(Tok.is(tok::arrow) && "expected arrow");
3517 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3520 /// \brief We have just started parsing the definition of a new class,
3521 /// so push that class onto our stack of classes that is currently
3523 Sema::ParsingClassState
3524 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3526 assert((NonNestedClass || !ClassStack.empty()) &&
3527 "Nested class without outer class");
3528 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3529 return Actions.PushParsingClass();
3532 /// \brief Deallocate the given parsed class and all of its nested
3534 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3535 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3536 delete Class->LateParsedDeclarations[I];
3540 /// \brief Pop the top class of the stack of classes that are
3541 /// currently being parsed.
3543 /// This routine should be called when we have finished parsing the
3544 /// definition of a class, but have not yet popped the Scope
3545 /// associated with the class's definition.
3546 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3547 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3549 Actions.PopParsingClass(state);
3551 ParsingClass *Victim = ClassStack.top();
3553 if (Victim->TopLevelClass) {
3554 // Deallocate all of the nested classes of this class,
3555 // recursively: we don't need to keep any of this information.
3556 DeallocateParsedClasses(Victim);
3559 assert(!ClassStack.empty() && "Missing top-level class?");
3561 if (Victim->LateParsedDeclarations.empty()) {
3562 // The victim is a nested class, but we will not need to perform
3563 // any processing after the definition of this class since it has
3564 // no members whose handling was delayed. Therefore, we can just
3565 // remove this nested class.
3566 DeallocateParsedClasses(Victim);
3570 // This nested class has some members that will need to be processed
3571 // after the top-level class is completely defined. Therefore, add
3572 // it to the list of nested classes within its parent.
3573 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3574 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3575 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3578 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3580 /// \return the parsed identifier on success, and 0 if the next token is not an
3581 /// attribute-token.
3583 /// C++11 [dcl.attr.grammar]p3:
3584 /// If a keyword or an alternative token that satisfies the syntactic
3585 /// requirements of an identifier is contained in an attribute-token,
3586 /// it is considered an identifier.
3587 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3588 switch (Tok.getKind()) {
3590 // Identifiers and keywords have identifier info attached.
3591 if (!Tok.isAnnotation()) {
3592 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3593 Loc = ConsumeToken();
3599 case tok::ampamp: // 'and'
3600 case tok::pipe: // 'bitor'
3601 case tok::pipepipe: // 'or'
3602 case tok::caret: // 'xor'
3603 case tok::tilde: // 'compl'
3604 case tok::amp: // 'bitand'
3605 case tok::ampequal: // 'and_eq'
3606 case tok::pipeequal: // 'or_eq'
3607 case tok::caretequal: // 'xor_eq'
3608 case tok::exclaim: // 'not'
3609 case tok::exclaimequal: // 'not_eq'
3610 // Alternative tokens do not have identifier info, but their spelling
3611 // starts with an alphabetical character.
3612 SmallString<8> SpellingBuf;
3613 SourceLocation SpellingLoc =
3614 PP.getSourceManager().getSpellingLoc(Tok.getLocation());
3615 StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
3616 if (isLetter(Spelling[0])) {
3617 Loc = ConsumeToken();
3618 return &PP.getIdentifierTable().get(Spelling);
3624 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3625 IdentifierInfo *ScopeName) {
3626 switch (AttributeList::getKind(AttrName, ScopeName,
3627 AttributeList::AS_CXX11)) {
3628 case AttributeList::AT_CarriesDependency:
3629 case AttributeList::AT_Deprecated:
3630 case AttributeList::AT_FallThrough:
3631 case AttributeList::AT_CXX11NoReturn:
3639 /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
3641 /// [C++11] attribute-argument-clause:
3642 /// '(' balanced-token-seq ')'
3644 /// [C++11] balanced-token-seq:
3646 /// balanced-token-seq balanced-token
3648 /// [C++11] balanced-token:
3649 /// '(' balanced-token-seq ')'
3650 /// '[' balanced-token-seq ']'
3651 /// '{' balanced-token-seq '}'
3652 /// any token but '(', ')', '[', ']', '{', or '}'
3653 bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
3654 SourceLocation AttrNameLoc,
3655 ParsedAttributes &Attrs,
3656 SourceLocation *EndLoc,
3657 IdentifierInfo *ScopeName,
3658 SourceLocation ScopeLoc) {
3659 assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
3660 SourceLocation LParenLoc = Tok.getLocation();
3662 // If the attribute isn't known, we will not attempt to parse any
3664 if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName,
3665 getTargetInfo(), getLangOpts())) {
3666 // Eat the left paren, then skip to the ending right paren.
3668 SkipUntil(tok::r_paren);
3672 if (ScopeName && ScopeName->getName() == "gnu")
3673 // GNU-scoped attributes have some special cases to handle GNU-specific
3675 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
3676 ScopeLoc, AttributeList::AS_CXX11, nullptr);
3679 ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
3680 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3682 const AttributeList *Attr = Attrs.getList();
3683 if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
3684 // If the attribute is a standard or built-in attribute and we are
3685 // parsing an argument list, we need to determine whether this attribute
3686 // was allowed to have an argument list (such as [[deprecated]]), and how
3687 // many arguments were parsed (so we can diagnose on [[deprecated()]]).
3688 if (Attr->getMaxArgs() && !NumArgs) {
3689 // The attribute was allowed to have arguments, but none were provided
3690 // even though the attribute parsed successfully. This is an error.
3691 Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
3692 } else if (!Attr->getMaxArgs()) {
3693 // The attribute parsed successfully, but was not allowed to have any
3694 // arguments. It doesn't matter whether any were provided -- the
3695 // presence of the argument list (even if empty) is diagnosed.
3696 Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
3698 << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
3705 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier.
3707 /// [C++11] attribute-specifier:
3708 /// '[' '[' attribute-list ']' ']'
3709 /// alignment-specifier
3711 /// [C++11] attribute-list:
3713 /// attribute-list ',' attribute[opt]
3715 /// attribute-list ',' attribute '...'
3717 /// [C++11] attribute:
3718 /// attribute-token attribute-argument-clause[opt]
3720 /// [C++11] attribute-token:
3722 /// attribute-scoped-token
3724 /// [C++11] attribute-scoped-token:
3725 /// attribute-namespace '::' identifier
3727 /// [C++11] attribute-namespace:
3729 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3730 SourceLocation *endLoc) {
3731 if (Tok.is(tok::kw_alignas)) {
3732 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3733 ParseAlignmentSpecifier(attrs, endLoc);
3737 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3738 && "Not a C++11 attribute list");
3740 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3745 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3747 while (Tok.isNot(tok::r_square)) {
3748 // attribute not present
3749 if (TryConsumeToken(tok::comma))
3752 SourceLocation ScopeLoc, AttrLoc;
3753 IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
3755 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3757 // Break out to the "expected ']'" diagnostic.
3761 if (TryConsumeToken(tok::coloncolon)) {
3762 ScopeName = AttrName;
3765 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3767 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
3768 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3773 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
3774 bool AttrParsed = false;
3777 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3778 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
3779 << AttrName << SourceRange(SeenAttrs[AttrName]);
3781 // Parse attribute arguments
3782 if (Tok.is(tok::l_paren))
3783 AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3784 ScopeName, ScopeLoc);
3787 attrs.addNew(AttrName,
3788 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3790 ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11);
3792 if (TryConsumeToken(tok::ellipsis))
3793 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3794 << AttrName->getName();
3797 if (ExpectAndConsume(tok::r_square))
3798 SkipUntil(tok::r_square);
3800 *endLoc = Tok.getLocation();
3801 if (ExpectAndConsume(tok::r_square))
3802 SkipUntil(tok::r_square);
3805 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3807 /// attribute-specifier-seq:
3808 /// attribute-specifier-seq[opt] attribute-specifier
3809 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3810 SourceLocation *endLoc) {
3811 assert(getLangOpts().CPlusPlus11);
3813 SourceLocation StartLoc = Tok.getLocation(), Loc;
3818 ParseCXX11AttributeSpecifier(attrs, endLoc);
3819 } while (isCXX11AttributeSpecifier());
3821 attrs.Range = SourceRange(StartLoc, *endLoc);
3824 void Parser::DiagnoseAndSkipCXX11Attributes() {
3825 // Start and end location of an attribute or an attribute list.
3826 SourceLocation StartLoc = Tok.getLocation();
3827 SourceLocation EndLoc = SkipCXX11Attributes();
3829 if (EndLoc.isValid()) {
3830 SourceRange Range(StartLoc, EndLoc);
3831 Diag(StartLoc, diag::err_attributes_not_allowed)
3836 SourceLocation Parser::SkipCXX11Attributes() {
3837 SourceLocation EndLoc;
3839 if (!isCXX11AttributeSpecifier())
3843 if (Tok.is(tok::l_square)) {
3844 BalancedDelimiterTracker T(*this, tok::l_square);
3847 EndLoc = T.getCloseLocation();
3849 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
3851 BalancedDelimiterTracker T(*this, tok::l_paren);
3852 if (!T.consumeOpen())
3854 EndLoc = T.getCloseLocation();
3856 } while (isCXX11AttributeSpecifier());
3861 /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
3863 /// [MS] ms-attribute:
3864 /// '[' token-seq ']'
3866 /// [MS] ms-attribute-seq:
3867 /// ms-attribute[opt]
3868 /// ms-attribute ms-attribute-seq
3869 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3870 SourceLocation *endLoc) {
3871 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3874 // FIXME: If this is actually a C++11 attribute, parse it as one.
3875 BalancedDelimiterTracker T(*this, tok::l_square);
3877 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
3880 *endLoc = T.getCloseLocation();
3881 } while (Tok.is(tok::l_square));
3884 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3885 AccessSpecifier& CurAS) {
3886 IfExistsCondition Result;
3887 if (ParseMicrosoftIfExistsCondition(Result))
3890 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3891 if (Braces.consumeOpen()) {
3892 Diag(Tok, diag::err_expected) << tok::l_brace;
3896 switch (Result.Behavior) {
3898 // Parse the declarations below.
3902 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3903 << Result.IsIfExists;
3904 // Fall through to skip.
3911 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
3912 // __if_exists, __if_not_exists can nest.
3913 if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
3914 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3918 // Check for extraneous top-level semicolon.
3919 if (Tok.is(tok::semi)) {
3920 ConsumeExtraSemi(InsideStruct, TagType);
3924 AccessSpecifier AS = getAccessSpecifierIfPresent();
3925 if (AS != AS_none) {
3926 // Current token is a C++ access specifier.
3928 SourceLocation ASLoc = Tok.getLocation();
3930 if (Tok.is(tok::colon))
3931 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3933 Diag(Tok, diag::err_expected) << tok::colon;
3938 // Parse all the comma separated declarators.
3939 ParseCXXClassMemberDeclaration(CurAS, nullptr);
3942 Braces.consumeClose();