1 //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++ Declaration portions of the Parser interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Basic/OperatorKinds.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/ParsedTemplate.h"
21 #include "clang/Sema/PrettyDeclStackTrace.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/Sema/SemaDiagnostic.h"
24 #include "llvm/ADT/SmallString.h"
25 using namespace clang;
27 /// ParseNamespace - We know that the current token is a namespace keyword. This
28 /// may either be a top level namespace or a block-level namespace alias. If
29 /// there was an inline keyword, it has already been parsed.
31 /// namespace-definition: [C++ 7.3: basic.namespace]
32 /// named-namespace-definition
33 /// unnamed-namespace-definition
35 /// unnamed-namespace-definition:
36 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
38 /// named-namespace-definition:
39 /// original-namespace-definition
40 /// extension-namespace-definition
42 /// original-namespace-definition:
43 /// 'inline'[opt] 'namespace' identifier attributes[opt]
44 /// '{' namespace-body '}'
46 /// extension-namespace-definition:
47 /// 'inline'[opt] 'namespace' original-namespace-name
48 /// '{' namespace-body '}'
50 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
51 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
53 Decl *Parser::ParseNamespace(unsigned Context,
54 SourceLocation &DeclEnd,
55 SourceLocation InlineLoc) {
56 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
57 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
58 ObjCDeclContextSwitch ObjCDC(*this);
60 if (Tok.is(tok::code_completion)) {
61 Actions.CodeCompleteNamespaceDecl(getCurScope());
66 SourceLocation IdentLoc;
67 IdentifierInfo *Ident = 0;
68 std::vector<SourceLocation> ExtraIdentLoc;
69 std::vector<IdentifierInfo*> ExtraIdent;
70 std::vector<SourceLocation> ExtraNamespaceLoc;
74 if (Tok.is(tok::identifier)) {
75 Ident = Tok.getIdentifierInfo();
76 IdentLoc = ConsumeToken(); // eat the identifier.
77 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
78 ExtraNamespaceLoc.push_back(ConsumeToken());
79 ExtraIdent.push_back(Tok.getIdentifierInfo());
80 ExtraIdentLoc.push_back(ConsumeToken());
84 // Read label attributes, if present.
85 ParsedAttributes attrs(AttrFactory);
86 if (Tok.is(tok::kw___attribute)) {
88 ParseGNUAttributes(attrs);
91 if (Tok.is(tok::equal)) {
93 Diag(Tok, diag::err_expected_ident);
94 // Skip to end of the definition and eat the ';'.
99 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
100 if (InlineLoc.isValid())
101 Diag(InlineLoc, diag::err_inline_namespace_alias)
102 << FixItHint::CreateRemoval(InlineLoc);
103 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
107 BalancedDelimiterTracker T(*this, tok::l_brace);
108 if (T.consumeOpen()) {
109 if (!ExtraIdent.empty()) {
110 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
111 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
113 Diag(Tok, Ident ? diag::err_expected_lbrace :
114 diag::err_expected_ident_lbrace);
118 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
119 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
120 getCurScope()->getFnParent()) {
121 if (!ExtraIdent.empty()) {
122 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
123 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
125 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
126 SkipUntil(tok::r_brace, false);
130 if (!ExtraIdent.empty()) {
131 TentativeParsingAction TPA(*this);
132 SkipUntil(tok::r_brace, /*StopAtSemi*/false, /*DontConsume*/true);
133 Token rBraceToken = Tok;
136 if (!rBraceToken.is(tok::r_brace)) {
137 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
138 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
140 std::string NamespaceFix;
141 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
142 E = ExtraIdent.end(); I != E; ++I) {
143 NamespaceFix += " { namespace ";
144 NamespaceFix += (*I)->getName();
148 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
151 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
152 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
153 ExtraIdentLoc.back()),
155 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
159 // If we're still good, complain about inline namespaces in non-C++0x now.
160 if (InlineLoc.isValid())
161 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
162 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
164 // Enter a scope for the namespace.
165 ParseScope NamespaceScope(this, Scope::DeclScope);
168 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
169 IdentLoc, Ident, T.getOpenLocation(),
172 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
173 "parsing namespace");
175 // Parse the contents of the namespace. This includes parsing recovery on
176 // any improperly nested namespaces.
177 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
178 InlineLoc, attrs, T);
180 // Leave the namespace scope.
181 NamespaceScope.Exit();
183 DeclEnd = T.getCloseLocation();
184 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
189 /// ParseInnerNamespace - Parse the contents of a namespace.
190 void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
191 std::vector<IdentifierInfo*>& Ident,
192 std::vector<SourceLocation>& NamespaceLoc,
193 unsigned int index, SourceLocation& InlineLoc,
194 ParsedAttributes& attrs,
195 BalancedDelimiterTracker &Tracker) {
196 if (index == Ident.size()) {
197 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
198 ParsedAttributesWithRange attrs(AttrFactory);
199 MaybeParseCXX11Attributes(attrs);
200 MaybeParseMicrosoftAttributes(attrs);
201 ParseExternalDeclaration(attrs);
204 // The caller is what called check -- we are simply calling
206 Tracker.consumeClose();
211 // Parse improperly nested namespaces.
212 ParseScope NamespaceScope(this, Scope::DeclScope);
214 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
215 NamespaceLoc[index], IdentLoc[index],
216 Ident[index], Tracker.getOpenLocation(),
219 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
222 NamespaceScope.Exit();
224 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
227 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
228 /// alias definition.
230 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
231 SourceLocation AliasLoc,
232 IdentifierInfo *Alias,
233 SourceLocation &DeclEnd) {
234 assert(Tok.is(tok::equal) && "Not equal token");
236 ConsumeToken(); // eat the '='.
238 if (Tok.is(tok::code_completion)) {
239 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
245 // Parse (optional) nested-name-specifier.
246 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
248 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
249 Diag(Tok, diag::err_expected_namespace_name);
250 // Skip to end of the definition and eat the ';'.
251 SkipUntil(tok::semi);
256 IdentifierInfo *Ident = Tok.getIdentifierInfo();
257 SourceLocation IdentLoc = ConsumeToken();
260 DeclEnd = Tok.getLocation();
261 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
264 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
265 SS, IdentLoc, Ident);
268 /// ParseLinkage - We know that the current token is a string_literal
269 /// and just before that, that extern was seen.
271 /// linkage-specification: [C++ 7.5p2: dcl.link]
272 /// 'extern' string-literal '{' declaration-seq[opt] '}'
273 /// 'extern' string-literal declaration
275 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
276 assert(Tok.is(tok::string_literal) && "Not a string literal!");
277 SmallString<8> LangBuffer;
278 bool Invalid = false;
279 StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid);
283 // FIXME: This is incorrect: linkage-specifiers are parsed in translation
284 // phase 7, so string-literal concatenation is supposed to occur.
285 // extern "" "C" "" "+" "+" { } is legal.
286 if (Tok.hasUDSuffix())
287 Diag(Tok, diag::err_invalid_string_udl);
288 SourceLocation Loc = ConsumeStringToken();
290 ParseScope LinkageScope(this, Scope::DeclScope);
292 = Actions.ActOnStartLinkageSpecification(getCurScope(),
293 DS.getSourceRange().getBegin(),
295 Tok.is(tok::l_brace) ? Tok.getLocation()
298 ParsedAttributesWithRange attrs(AttrFactory);
299 MaybeParseCXX11Attributes(attrs);
300 MaybeParseMicrosoftAttributes(attrs);
302 if (Tok.isNot(tok::l_brace)) {
303 // Reset the source range in DS, as the leading "extern"
304 // does not really belong to the inner declaration ...
305 DS.SetRangeStart(SourceLocation());
306 DS.SetRangeEnd(SourceLocation());
307 // ... but anyway remember that such an "extern" was seen.
308 DS.setExternInLinkageSpec(true);
309 ParseExternalDeclaration(attrs, &DS);
310 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
316 ProhibitAttributes(attrs);
318 BalancedDelimiterTracker T(*this, tok::l_brace);
320 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
321 ParsedAttributesWithRange attrs(AttrFactory);
322 MaybeParseCXX11Attributes(attrs);
323 MaybeParseMicrosoftAttributes(attrs);
324 ParseExternalDeclaration(attrs);
328 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
329 T.getCloseLocation());
332 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
333 /// using-directive. Assumes that current token is 'using'.
334 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
335 const ParsedTemplateInfo &TemplateInfo,
336 SourceLocation &DeclEnd,
337 ParsedAttributesWithRange &attrs,
339 assert(Tok.is(tok::kw_using) && "Not using token");
340 ObjCDeclContextSwitch ObjCDC(*this);
343 SourceLocation UsingLoc = ConsumeToken();
345 if (Tok.is(tok::code_completion)) {
346 Actions.CodeCompleteUsing(getCurScope());
351 // 'using namespace' means this is a using-directive.
352 if (Tok.is(tok::kw_namespace)) {
353 // Template parameters are always an error here.
354 if (TemplateInfo.Kind) {
355 SourceRange R = TemplateInfo.getSourceRange();
356 Diag(UsingLoc, diag::err_templated_using_directive)
357 << R << FixItHint::CreateRemoval(R);
360 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
363 // Otherwise, it must be a using-declaration or an alias-declaration.
365 // Using declarations can't have attributes.
366 ProhibitAttributes(attrs);
368 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
372 /// ParseUsingDirective - Parse C++ using-directive, assumes
373 /// that current token is 'namespace' and 'using' was already parsed.
375 /// using-directive: [C++ 7.3.p4: namespace.udir]
376 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
378 /// [GNU] using-directive:
379 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
380 /// namespace-name attributes[opt] ;
382 Decl *Parser::ParseUsingDirective(unsigned Context,
383 SourceLocation UsingLoc,
384 SourceLocation &DeclEnd,
385 ParsedAttributes &attrs) {
386 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
389 SourceLocation NamespcLoc = ConsumeToken();
391 if (Tok.is(tok::code_completion)) {
392 Actions.CodeCompleteUsingDirective(getCurScope());
398 // Parse (optional) nested-name-specifier.
399 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
401 IdentifierInfo *NamespcName = 0;
402 SourceLocation IdentLoc = SourceLocation();
404 // Parse namespace-name.
405 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
406 Diag(Tok, diag::err_expected_namespace_name);
407 // If there was invalid namespace name, skip to end of decl, and eat ';'.
408 SkipUntil(tok::semi);
409 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
414 NamespcName = Tok.getIdentifierInfo();
415 IdentLoc = ConsumeToken();
417 // Parse (optional) attributes (most likely GNU strong-using extension).
418 bool GNUAttr = false;
419 if (Tok.is(tok::kw___attribute)) {
421 ParseGNUAttributes(attrs);
425 DeclEnd = Tok.getLocation();
426 ExpectAndConsume(tok::semi,
427 GNUAttr ? diag::err_expected_semi_after_attribute_list
428 : diag::err_expected_semi_after_namespace_name,
431 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
432 IdentLoc, NamespcName, attrs.getList());
435 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
436 /// Assumes that 'using' was already seen.
438 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
439 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
441 /// 'using' :: unqualified-id
443 /// alias-declaration: C++11 [dcl.dcl]p1
444 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
446 Decl *Parser::ParseUsingDeclaration(unsigned Context,
447 const ParsedTemplateInfo &TemplateInfo,
448 SourceLocation UsingLoc,
449 SourceLocation &DeclEnd,
453 SourceLocation TypenameLoc;
454 bool IsTypeName = false;
455 ParsedAttributesWithRange Attrs(AttrFactory);
457 // FIXME: Simply skip the attributes and diagnose, don't bother parsing them.
458 MaybeParseCXX11Attributes(Attrs);
459 ProhibitAttributes(Attrs);
461 Attrs.Range = SourceRange();
463 // Ignore optional 'typename'.
464 // FIXME: This is wrong; we should parse this as a typename-specifier.
465 if (Tok.is(tok::kw_typename)) {
466 TypenameLoc = ConsumeToken();
470 // Parse nested-name-specifier.
471 IdentifierInfo *LastII = 0;
472 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false,
473 /*MayBePseudoDtor=*/0, /*IsTypename=*/false,
476 // Check nested-name specifier.
477 if (SS.isInvalid()) {
478 SkipUntil(tok::semi);
482 SourceLocation TemplateKWLoc;
485 // Parse the unqualified-id. We allow parsing of both constructor and
486 // destructor names and allow the action module to diagnose any semantic
489 // C++11 [class.qual]p2:
490 // [...] in a using-declaration that is a member-declaration, if the name
491 // specified after the nested-name-specifier is the same as the identifier
492 // or the simple-template-id's template-name in the last component of the
493 // nested-name-specifier, the name is [...] considered to name the
495 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
496 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
497 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
498 !SS.getScopeRep()->getAsNamespace() &&
499 !SS.getScopeRep()->getAsNamespaceAlias()) {
500 SourceLocation IdLoc = ConsumeToken();
501 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
502 Name.setConstructorName(Type, IdLoc, IdLoc);
503 } else if (ParseUnqualifiedId(SS, /*EnteringContext=*/ false,
504 /*AllowDestructorName=*/ true,
505 /*AllowConstructorName=*/ true, ParsedType(),
506 TemplateKWLoc, Name)) {
507 SkipUntil(tok::semi);
511 MaybeParseCXX11Attributes(Attrs);
513 // Maybe this is an alias-declaration.
514 bool IsAliasDecl = Tok.is(tok::equal);
515 TypeResult TypeAlias;
517 // TODO: Can GNU attributes appear here?
520 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
521 diag::warn_cxx98_compat_alias_declaration :
522 diag::ext_alias_declaration);
524 // Type alias templates cannot be specialized.
526 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
527 Name.getKind() == UnqualifiedId::IK_TemplateId)
529 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
531 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
533 if (SpecKind != -1) {
536 Range = SourceRange(Name.TemplateId->LAngleLoc,
537 Name.TemplateId->RAngleLoc);
539 Range = TemplateInfo.getSourceRange();
540 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
541 << SpecKind << Range;
542 SkipUntil(tok::semi);
546 // Name must be an identifier.
547 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
548 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
549 // No removal fixit: can't recover from this.
550 SkipUntil(tok::semi);
552 } else if (IsTypeName)
553 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
554 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
555 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
556 else if (SS.isNotEmpty())
557 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
558 << FixItHint::CreateRemoval(SS.getRange());
560 TypeAlias = ParseTypeName(0, TemplateInfo.Kind ?
561 Declarator::AliasTemplateContext :
562 Declarator::AliasDeclContext, AS, OwnedType,
565 // C++11 attributes are not allowed on a using-declaration, but GNU ones
567 ProhibitAttributes(Attrs);
569 // Parse (optional) attributes (most likely GNU strong-using extension).
570 MaybeParseGNUAttributes(Attrs);
574 DeclEnd = Tok.getLocation();
575 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
576 !Attrs.empty() ? "attributes list" :
577 IsAliasDecl ? "alias declaration" : "using declaration",
580 // Diagnose an attempt to declare a templated using-declaration.
581 // In C++11, alias-declarations can be templates:
582 // template <...> using id = type;
583 if (TemplateInfo.Kind && !IsAliasDecl) {
584 SourceRange R = TemplateInfo.getSourceRange();
585 Diag(UsingLoc, diag::err_templated_using_declaration)
586 << R << FixItHint::CreateRemoval(R);
588 // Unfortunately, we have to bail out instead of recovering by
589 // ignoring the parameters, just in case the nested name specifier
590 // depends on the parameters.
594 // "typename" keyword is allowed for identifiers only,
595 // because it may be a type definition.
596 if (IsTypeName && Name.getKind() != UnqualifiedId::IK_Identifier) {
597 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
598 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
599 // Proceed parsing, but reset the IsTypeName flag.
604 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
605 MultiTemplateParamsArg TemplateParamsArg(
606 TemplateParams ? TemplateParams->data() : 0,
607 TemplateParams ? TemplateParams->size() : 0);
608 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
609 UsingLoc, Name, Attrs.getList(),
613 return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS,
614 Name, Attrs.getList(),
615 IsTypeName, TypenameLoc);
618 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
620 /// [C++0x] static_assert-declaration:
621 /// static_assert ( constant-expression , string-literal ) ;
623 /// [C11] static_assert-declaration:
624 /// _Static_assert ( constant-expression , string-literal ) ;
626 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
627 assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) &&
628 "Not a static_assert declaration");
630 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
631 Diag(Tok, diag::ext_c11_static_assert);
632 if (Tok.is(tok::kw_static_assert))
633 Diag(Tok, diag::warn_cxx98_compat_static_assert);
635 SourceLocation StaticAssertLoc = ConsumeToken();
637 BalancedDelimiterTracker T(*this, tok::l_paren);
638 if (T.consumeOpen()) {
639 Diag(Tok, diag::err_expected_lparen);
644 ExprResult AssertExpr(ParseConstantExpression());
645 if (AssertExpr.isInvalid()) {
650 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
653 if (!isTokenStringLiteral()) {
654 Diag(Tok, diag::err_expected_string_literal)
655 << /*Source='static_assert'*/1;
660 ExprResult AssertMessage(ParseStringLiteralExpression());
661 if (AssertMessage.isInvalid()) {
668 DeclEnd = Tok.getLocation();
669 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
671 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
673 AssertMessage.take(),
674 T.getCloseLocation());
677 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
679 /// 'decltype' ( expression )
680 /// 'decltype' ( 'auto' ) [C++1y]
682 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
683 assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
684 && "Not a decltype specifier");
687 SourceLocation StartLoc = Tok.getLocation();
688 SourceLocation EndLoc;
690 if (Tok.is(tok::annot_decltype)) {
691 Result = getExprAnnotation(Tok);
692 EndLoc = Tok.getAnnotationEndLoc();
694 if (Result.isInvalid()) {
695 DS.SetTypeSpecError();
699 if (Tok.getIdentifierInfo()->isStr("decltype"))
700 Diag(Tok, diag::warn_cxx98_compat_decltype);
704 BalancedDelimiterTracker T(*this, tok::l_paren);
705 if (T.expectAndConsume(diag::err_expected_lparen_after,
706 "decltype", tok::r_paren)) {
707 DS.SetTypeSpecError();
708 return T.getOpenLocation() == Tok.getLocation() ?
709 StartLoc : T.getOpenLocation();
712 // Check for C++1y 'decltype(auto)'.
713 if (Tok.is(tok::kw_auto)) {
714 // No need to disambiguate here: an expression can't start with 'auto',
715 // because the typename-specifier in a function-style cast operation can't
717 Diag(Tok.getLocation(),
718 getLangOpts().CPlusPlus1y
719 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
720 : diag::ext_decltype_auto_type_specifier);
723 // Parse the expression
725 // C++11 [dcl.type.simple]p4:
726 // The operand of the decltype specifier is an unevaluated operand.
727 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
728 0, /*IsDecltype=*/true);
729 Result = ParseExpression();
730 if (Result.isInvalid()) {
731 DS.SetTypeSpecError();
732 if (SkipUntil(tok::r_paren, /*StopAtSemi=*/true,
733 /*DontConsume=*/true)) {
734 EndLoc = ConsumeParen();
736 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
737 // Backtrack to get the location of the last token before the semi.
738 PP.RevertCachedTokens(2);
739 ConsumeToken(); // the semi.
740 EndLoc = ConsumeAnyToken();
741 assert(Tok.is(tok::semi));
743 EndLoc = Tok.getLocation();
749 Result = Actions.ActOnDecltypeExpression(Result.take());
754 if (T.getCloseLocation().isInvalid()) {
755 DS.SetTypeSpecError();
756 // FIXME: this should return the location of the last token
757 // that was consumed (by "consumeClose()")
758 return T.getCloseLocation();
761 if (Result.isInvalid()) {
762 DS.SetTypeSpecError();
763 return T.getCloseLocation();
766 EndLoc = T.getCloseLocation();
768 assert(!Result.isInvalid());
770 const char *PrevSpec = 0;
772 // Check for duplicate type specifiers (e.g. "int decltype(a)").
774 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
775 DiagID, Result.release())
776 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
778 Diag(StartLoc, DiagID) << PrevSpec;
779 DS.SetTypeSpecError();
784 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
785 SourceLocation StartLoc,
786 SourceLocation EndLoc) {
787 // make sure we have a token we can turn into an annotation token
788 if (PP.isBacktrackEnabled())
789 PP.RevertCachedTokens(1);
793 Tok.setKind(tok::annot_decltype);
794 setExprAnnotation(Tok,
795 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
796 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
798 Tok.setAnnotationEndLoc(EndLoc);
799 Tok.setLocation(StartLoc);
800 PP.AnnotateCachedTokens(Tok);
803 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
804 assert(Tok.is(tok::kw___underlying_type) &&
805 "Not an underlying type specifier");
807 SourceLocation StartLoc = ConsumeToken();
808 BalancedDelimiterTracker T(*this, tok::l_paren);
809 if (T.expectAndConsume(diag::err_expected_lparen_after,
810 "__underlying_type", tok::r_paren)) {
814 TypeResult Result = ParseTypeName();
815 if (Result.isInvalid()) {
816 SkipUntil(tok::r_paren);
822 if (T.getCloseLocation().isInvalid())
825 const char *PrevSpec = 0;
827 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
828 DiagID, Result.release()))
829 Diag(StartLoc, DiagID) << PrevSpec;
832 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
833 /// class name or decltype-specifier. Note that we only check that the result
834 /// names a type; semantic analysis will need to verify that the type names a
835 /// class. The result is either a type or null, depending on whether a type
838 /// base-type-specifier: [C++11 class.derived]
839 /// class-or-decltype
840 /// class-or-decltype: [C++11 class.derived]
841 /// nested-name-specifier[opt] class-name
842 /// decltype-specifier
843 /// class-name: [C++ class.name]
845 /// simple-template-id
847 /// In C++98, instead of base-type-specifier, we have:
849 /// ::[opt] nested-name-specifier[opt] class-name
850 Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
851 SourceLocation &EndLocation) {
852 // Ignore attempts to use typename
853 if (Tok.is(tok::kw_typename)) {
854 Diag(Tok, diag::err_expected_class_name_not_template)
855 << FixItHint::CreateRemoval(Tok.getLocation());
859 // Parse optional nested-name-specifier
861 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
863 BaseLoc = Tok.getLocation();
865 // Parse decltype-specifier
866 // tok == kw_decltype is just error recovery, it can only happen when SS
868 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
870 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
871 << FixItHint::CreateRemoval(SS.getRange());
872 // Fake up a Declarator to use with ActOnTypeName.
873 DeclSpec DS(AttrFactory);
875 EndLocation = ParseDecltypeSpecifier(DS);
877 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
878 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
881 // Check whether we have a template-id that names a type.
882 if (Tok.is(tok::annot_template_id)) {
883 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
884 if (TemplateId->Kind == TNK_Type_template ||
885 TemplateId->Kind == TNK_Dependent_template_name) {
886 AnnotateTemplateIdTokenAsType();
888 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
889 ParsedType Type = getTypeAnnotation(Tok);
890 EndLocation = Tok.getAnnotationEndLoc();
898 // Fall through to produce an error below.
901 if (Tok.isNot(tok::identifier)) {
902 Diag(Tok, diag::err_expected_class_name);
906 IdentifierInfo *Id = Tok.getIdentifierInfo();
907 SourceLocation IdLoc = ConsumeToken();
909 if (Tok.is(tok::less)) {
910 // It looks the user intended to write a template-id here, but the
911 // template-name was wrong. Try to fix that.
912 TemplateNameKind TNK = TNK_Type_template;
914 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
915 &SS, Template, TNK)) {
916 Diag(IdLoc, diag::err_unknown_template_name)
923 // Form the template name
924 UnqualifiedId TemplateName;
925 TemplateName.setIdentifier(Id, IdLoc);
927 // Parse the full template-id, then turn it into a type.
928 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
931 if (TNK == TNK_Dependent_template_name)
932 AnnotateTemplateIdTokenAsType();
934 // If we didn't end up with a typename token, there's nothing more we
936 if (Tok.isNot(tok::annot_typename))
939 // Retrieve the type from the annotation token, consume that token, and
941 EndLocation = Tok.getAnnotationEndLoc();
942 ParsedType Type = getTypeAnnotation(Tok);
947 // We have an identifier; check whether it is actually a type.
948 IdentifierInfo *CorrectedII = 0;
949 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
951 /*IsCtorOrDtorName=*/false,
952 /*NonTrivialTypeSourceInfo=*/true,
955 Diag(IdLoc, diag::err_expected_class_name);
959 // Consume the identifier.
962 // Fake up a Declarator to use with ActOnTypeName.
963 DeclSpec DS(AttrFactory);
964 DS.SetRangeStart(IdLoc);
965 DS.SetRangeEnd(EndLocation);
966 DS.getTypeSpecScope() = SS;
968 const char *PrevSpec = 0;
970 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type);
972 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
973 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
976 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
977 while (Tok.is(tok::kw___single_inheritance) ||
978 Tok.is(tok::kw___multiple_inheritance) ||
979 Tok.is(tok::kw___virtual_inheritance)) {
980 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
981 SourceLocation AttrNameLoc = ConsumeToken();
982 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
983 SourceLocation(), 0, 0, AttributeList::AS_GNU);
987 /// Determine whether the following tokens are valid after a type-specifier
988 /// which could be a standalone declaration. This will conservatively return
989 /// true if there's any doubt, and is appropriate for insert-';' fixits.
990 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
991 // This switch enumerates the valid "follow" set for type-specifiers.
992 switch (Tok.getKind()) {
994 case tok::semi: // struct foo {...} ;
995 case tok::star: // struct foo {...} * P;
996 case tok::amp: // struct foo {...} & R = ...
997 case tok::ampamp: // struct foo {...} && R = ...
998 case tok::identifier: // struct foo {...} V ;
999 case tok::r_paren: //(struct foo {...} ) {4}
1000 case tok::annot_cxxscope: // struct foo {...} a:: b;
1001 case tok::annot_typename: // struct foo {...} a ::b;
1002 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1003 case tok::l_paren: // struct foo {...} ( x);
1004 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1005 case tok::kw_operator: // struct foo operator ++() {...}
1008 return CouldBeBitfield; // enum E { ... } : 2;
1010 case tok::kw_const: // struct foo {...} const x;
1011 case tok::kw_volatile: // struct foo {...} volatile x;
1012 case tok::kw_restrict: // struct foo {...} restrict x;
1013 // Function specifiers
1014 // Note, no 'explicit'. An explicit function must be either a conversion
1015 // operator or a constructor. Either way, it can't have a return type.
1016 case tok::kw_inline: // struct foo inline f();
1017 case tok::kw_virtual: // struct foo virtual f();
1018 case tok::kw_friend: // struct foo friend f();
1019 // Storage-class specifiers
1020 case tok::kw_static: // struct foo {...} static x;
1021 case tok::kw_extern: // struct foo {...} extern x;
1022 case tok::kw_typedef: // struct foo {...} typedef x;
1023 case tok::kw_register: // struct foo {...} register x;
1024 case tok::kw_auto: // struct foo {...} auto x;
1025 case tok::kw_mutable: // struct foo {...} mutable x;
1026 case tok::kw_thread_local: // struct foo {...} thread_local x;
1027 case tok::kw_constexpr: // struct foo {...} constexpr x;
1028 // As shown above, type qualifiers and storage class specifiers absolutely
1029 // can occur after class specifiers according to the grammar. However,
1030 // almost no one actually writes code like this. If we see one of these,
1031 // it is much more likely that someone missed a semi colon and the
1032 // type/storage class specifier we're seeing is part of the *next*
1033 // intended declaration, as in:
1035 // struct foo { ... }
1038 // We'd really like to emit a missing semicolon error instead of emitting
1039 // an error on the 'int' saying that you can't have two type specifiers in
1040 // the same declaration of X. Because of this, we look ahead past this
1041 // token to see if it's a type specifier. If so, we know the code is
1042 // otherwise invalid, so we can produce the expected semi error.
1043 if (!isKnownToBeTypeSpecifier(NextToken()))
1046 case tok::r_brace: // struct bar { struct foo {...} }
1047 // Missing ';' at end of struct is accepted as an extension in C mode.
1048 if (!getLangOpts().CPlusPlus)
1052 case tok::l_square: // enum E [[]] x
1053 // Note, no tok::kw_alignas here; alignas cannot appertain to a type.
1054 return getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1056 // template<class T = class X>
1057 return getLangOpts().CPlusPlus;
1062 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1063 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1064 /// until we reach the start of a definition or see a token that
1065 /// cannot start a definition.
1067 /// class-specifier: [C++ class]
1068 /// class-head '{' member-specification[opt] '}'
1069 /// class-head '{' member-specification[opt] '}' attributes[opt]
1071 /// class-key identifier[opt] base-clause[opt]
1072 /// class-key nested-name-specifier identifier base-clause[opt]
1073 /// class-key nested-name-specifier[opt] simple-template-id
1074 /// base-clause[opt]
1075 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1076 /// [GNU] class-key attributes[opt] nested-name-specifier
1077 /// identifier base-clause[opt]
1078 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1079 /// simple-template-id base-clause[opt]
1085 /// elaborated-type-specifier: [C++ dcl.type.elab]
1086 /// class-key ::[opt] nested-name-specifier[opt] identifier
1087 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1088 /// simple-template-id
1090 /// Note that the C++ class-specifier and elaborated-type-specifier,
1091 /// together, subsume the C99 struct-or-union-specifier:
1093 /// struct-or-union-specifier: [C99 6.7.2.1]
1094 /// struct-or-union identifier[opt] '{' struct-contents '}'
1095 /// struct-or-union identifier
1096 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1097 /// '}' attributes[opt]
1098 /// [GNU] struct-or-union attributes[opt] identifier
1099 /// struct-or-union:
1102 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1103 SourceLocation StartLoc, DeclSpec &DS,
1104 const ParsedTemplateInfo &TemplateInfo,
1106 bool EnteringContext, DeclSpecContext DSC,
1107 ParsedAttributesWithRange &Attributes) {
1108 DeclSpec::TST TagType;
1109 if (TagTokKind == tok::kw_struct)
1110 TagType = DeclSpec::TST_struct;
1111 else if (TagTokKind == tok::kw___interface)
1112 TagType = DeclSpec::TST_interface;
1113 else if (TagTokKind == tok::kw_class)
1114 TagType = DeclSpec::TST_class;
1116 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1117 TagType = DeclSpec::TST_union;
1120 if (Tok.is(tok::code_completion)) {
1121 // Code completion for a struct, class, or union name.
1122 Actions.CodeCompleteTag(getCurScope(), TagType);
1123 return cutOffParsing();
1126 // C++03 [temp.explicit] 14.7.2/8:
1127 // The usual access checking rules do not apply to names used to specify
1128 // explicit instantiations.
1130 // As an extension we do not perform access checking on the names used to
1131 // specify explicit specializations either. This is important to allow
1132 // specializing traits classes for private types.
1134 // Note that we don't suppress if this turns out to be an elaborated
1136 bool shouldDelayDiagsInTag =
1137 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1138 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1139 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1141 ParsedAttributesWithRange attrs(AttrFactory);
1142 // If attributes exist after tag, parse them.
1143 if (Tok.is(tok::kw___attribute))
1144 ParseGNUAttributes(attrs);
1146 // If declspecs exist after tag, parse them.
1147 while (Tok.is(tok::kw___declspec))
1148 ParseMicrosoftDeclSpec(attrs);
1150 // Parse inheritance specifiers.
1151 if (Tok.is(tok::kw___single_inheritance) ||
1152 Tok.is(tok::kw___multiple_inheritance) ||
1153 Tok.is(tok::kw___virtual_inheritance))
1154 ParseMicrosoftInheritanceClassAttributes(attrs);
1156 // If C++0x attributes exist here, parse them.
1157 // FIXME: Are we consistent with the ordering of parsing of different
1158 // styles of attributes?
1159 MaybeParseCXX11Attributes(attrs);
1161 // Source location used by FIXIT to insert misplaced
1163 SourceLocation AttrFixitLoc = Tok.getLocation();
1165 if (TagType == DeclSpec::TST_struct &&
1166 !Tok.is(tok::identifier) &&
1167 Tok.getIdentifierInfo() &&
1168 (Tok.is(tok::kw___is_arithmetic) ||
1169 Tok.is(tok::kw___is_convertible) ||
1170 Tok.is(tok::kw___is_empty) ||
1171 Tok.is(tok::kw___is_floating_point) ||
1172 Tok.is(tok::kw___is_function) ||
1173 Tok.is(tok::kw___is_fundamental) ||
1174 Tok.is(tok::kw___is_integral) ||
1175 Tok.is(tok::kw___is_member_function_pointer) ||
1176 Tok.is(tok::kw___is_member_pointer) ||
1177 Tok.is(tok::kw___is_pod) ||
1178 Tok.is(tok::kw___is_pointer) ||
1179 Tok.is(tok::kw___is_same) ||
1180 Tok.is(tok::kw___is_scalar) ||
1181 Tok.is(tok::kw___is_signed) ||
1182 Tok.is(tok::kw___is_unsigned) ||
1183 Tok.is(tok::kw___is_void))) {
1184 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1185 // name of struct templates, but some are keywords in GCC >= 4.3
1186 // and Clang. Therefore, when we see the token sequence "struct
1187 // X", make X into a normal identifier rather than a keyword, to
1188 // allow libstdc++ 4.2 and libc++ to work properly.
1189 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1190 Tok.setKind(tok::identifier);
1193 // Parse the (optional) nested-name-specifier.
1194 CXXScopeSpec &SS = DS.getTypeSpecScope();
1195 if (getLangOpts().CPlusPlus) {
1196 // "FOO : BAR" is not a potential typo for "FOO::BAR".
1197 ColonProtectionRAIIObject X(*this);
1199 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1200 DS.SetTypeSpecError();
1202 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
1203 Diag(Tok, diag::err_expected_ident);
1206 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1208 // Parse the (optional) class name or simple-template-id.
1209 IdentifierInfo *Name = 0;
1210 SourceLocation NameLoc;
1211 TemplateIdAnnotation *TemplateId = 0;
1212 if (Tok.is(tok::identifier)) {
1213 Name = Tok.getIdentifierInfo();
1214 NameLoc = ConsumeToken();
1216 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1217 // The name was supposed to refer to a template, but didn't.
1218 // Eat the template argument list and try to continue parsing this as
1219 // a class (or template thereof).
1220 TemplateArgList TemplateArgs;
1221 SourceLocation LAngleLoc, RAngleLoc;
1222 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1224 TemplateArgs, RAngleLoc)) {
1225 // We couldn't parse the template argument list at all, so don't
1226 // try to give any location information for the list.
1227 LAngleLoc = RAngleLoc = SourceLocation();
1230 Diag(NameLoc, diag::err_explicit_spec_non_template)
1231 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1232 << (TagType == DeclSpec::TST_class? 0
1233 : TagType == DeclSpec::TST_struct? 1
1234 : TagType == DeclSpec::TST_interface? 2
1237 << SourceRange(LAngleLoc, RAngleLoc);
1239 // Strip off the last template parameter list if it was empty, since
1240 // we've removed its template argument list.
1241 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1242 if (TemplateParams && TemplateParams->size() > 1) {
1243 TemplateParams->pop_back();
1246 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1247 = ParsedTemplateInfo::NonTemplate;
1249 } else if (TemplateInfo.Kind
1250 == ParsedTemplateInfo::ExplicitInstantiation) {
1251 // Pretend this is just a forward declaration.
1253 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1254 = ParsedTemplateInfo::NonTemplate;
1255 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1257 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1261 } else if (Tok.is(tok::annot_template_id)) {
1262 TemplateId = takeTemplateIdAnnotation(Tok);
1263 NameLoc = ConsumeToken();
1265 if (TemplateId->Kind != TNK_Type_template &&
1266 TemplateId->Kind != TNK_Dependent_template_name) {
1267 // The template-name in the simple-template-id refers to
1268 // something other than a class template. Give an appropriate
1269 // error message and skip to the ';'.
1270 SourceRange Range(NameLoc);
1271 if (SS.isNotEmpty())
1272 Range.setBegin(SS.getBeginLoc());
1274 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1275 << Name << static_cast<int>(TemplateId->Kind) << Range;
1277 DS.SetTypeSpecError();
1278 SkipUntil(tok::semi, false, true);
1283 // There are four options here.
1284 // - If we are in a trailing return type, this is always just a reference,
1285 // and we must not try to parse a definition. For instance,
1286 // [] () -> struct S { };
1287 // does not define a type.
1288 // - If we have 'struct foo {...', 'struct foo :...',
1289 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1290 // - If we have 'struct foo;', then this is either a forward declaration
1291 // or a friend declaration, which have to be treated differently.
1292 // - Otherwise we have something like 'struct foo xyz', a reference.
1294 // We also detect these erroneous cases to provide better diagnostic for
1295 // C++11 attributes parsing.
1296 // - attributes follow class name:
1297 // struct foo [[]] {};
1298 // - attributes appear before or after 'final':
1299 // struct foo [[]] final [[]] {};
1301 // However, in type-specifier-seq's, things look like declarations but are
1302 // just references, e.g.
1305 // &T::operator struct s;
1306 // For these, DSC is DSC_type_specifier.
1308 // If there are attributes after class name, parse them.
1309 MaybeParseCXX11Attributes(Attributes);
1311 Sema::TagUseKind TUK;
1312 if (DSC == DSC_trailing)
1313 TUK = Sema::TUK_Reference;
1314 else if (Tok.is(tok::l_brace) ||
1315 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1316 (isCXX11FinalKeyword() &&
1317 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1318 if (DS.isFriendSpecified()) {
1319 // C++ [class.friend]p2:
1320 // A class shall not be defined in a friend declaration.
1321 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1322 << SourceRange(DS.getFriendSpecLoc());
1324 // Skip everything up to the semicolon, so that this looks like a proper
1325 // friend class (or template thereof) declaration.
1326 SkipUntil(tok::semi, true, true);
1327 TUK = Sema::TUK_Friend;
1329 // Okay, this is a class definition.
1330 TUK = Sema::TUK_Definition;
1332 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1333 NextToken().is(tok::kw_alignas))) {
1334 // We can't tell if this is a definition or reference
1335 // until we skipped the 'final' and C++11 attribute specifiers.
1336 TentativeParsingAction PA(*this);
1338 // Skip the 'final' keyword.
1341 // Skip C++11 attribute specifiers.
1343 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1345 if (!SkipUntil(tok::r_square))
1347 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1350 if (!SkipUntil(tok::r_paren))
1357 if (Tok.is(tok::l_brace) || Tok.is(tok::colon))
1358 TUK = Sema::TUK_Definition;
1360 TUK = Sema::TUK_Reference;
1363 } else if (DSC != DSC_type_specifier &&
1364 (Tok.is(tok::semi) ||
1365 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1366 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1367 if (Tok.isNot(tok::semi)) {
1368 // A semicolon was missing after this declaration. Diagnose and recover.
1369 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1370 DeclSpec::getSpecifierName(TagType));
1372 Tok.setKind(tok::semi);
1375 TUK = Sema::TUK_Reference;
1377 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1378 // to caller to handle.
1379 if (TUK != Sema::TUK_Reference) {
1380 // If this is not a reference, then the only possible
1381 // valid place for C++11 attributes to appear here
1382 // is between class-key and class-name. If there are
1383 // any attributes after class-name, we try a fixit to move
1384 // them to the right place.
1385 SourceRange AttrRange = Attributes.Range;
1386 if (AttrRange.isValid()) {
1387 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1389 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1390 CharSourceRange(AttrRange, true))
1391 << FixItHint::CreateRemoval(AttrRange);
1393 // Recover by adding misplaced attributes to the attribute list
1394 // of the class so they can be applied on the class later.
1395 attrs.takeAllFrom(Attributes);
1399 // If this is an elaborated type specifier, and we delayed
1400 // diagnostics before, just merge them into the current pool.
1401 if (shouldDelayDiagsInTag) {
1402 diagsFromTag.done();
1403 if (TUK == Sema::TUK_Reference)
1404 diagsFromTag.redelay();
1407 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1408 TUK != Sema::TUK_Definition)) {
1409 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1410 // We have a declaration or reference to an anonymous class.
1411 Diag(StartLoc, diag::err_anon_type_definition)
1412 << DeclSpec::getSpecifierName(TagType);
1415 SkipUntil(tok::comma, true);
1419 // Create the tag portion of the class or class template.
1420 DeclResult TagOrTempResult = true; // invalid
1421 TypeResult TypeResult = true; // invalid
1425 // Explicit specialization, class template partial specialization,
1426 // or explicit instantiation.
1427 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1428 TemplateId->NumArgs);
1429 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1430 TUK == Sema::TUK_Declaration) {
1431 // This is an explicit instantiation of a class template.
1432 ProhibitAttributes(attrs);
1435 = Actions.ActOnExplicitInstantiation(getCurScope(),
1436 TemplateInfo.ExternLoc,
1437 TemplateInfo.TemplateLoc,
1441 TemplateId->Template,
1442 TemplateId->TemplateNameLoc,
1443 TemplateId->LAngleLoc,
1445 TemplateId->RAngleLoc,
1448 // Friend template-ids are treated as references unless
1449 // they have template headers, in which case they're ill-formed
1450 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1451 // We diagnose this error in ActOnClassTemplateSpecialization.
1452 } else if (TUK == Sema::TUK_Reference ||
1453 (TUK == Sema::TUK_Friend &&
1454 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1455 ProhibitAttributes(attrs);
1456 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1458 TemplateId->TemplateKWLoc,
1459 TemplateId->Template,
1460 TemplateId->TemplateNameLoc,
1461 TemplateId->LAngleLoc,
1463 TemplateId->RAngleLoc);
1465 // This is an explicit specialization or a class template
1466 // partial specialization.
1467 TemplateParameterLists FakedParamLists;
1469 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1470 // This looks like an explicit instantiation, because we have
1473 // template class Foo<X>
1475 // but it actually has a definition. Most likely, this was
1476 // meant to be an explicit specialization, but the user forgot
1477 // the '<>' after 'template'.
1478 assert(TUK == Sema::TUK_Definition && "Expected a definition here");
1480 SourceLocation LAngleLoc
1481 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1482 Diag(TemplateId->TemplateNameLoc,
1483 diag::err_explicit_instantiation_with_definition)
1484 << SourceRange(TemplateInfo.TemplateLoc)
1485 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1487 // Create a fake template parameter list that contains only
1488 // "template<>", so that we treat this construct as a class
1489 // template specialization.
1490 FakedParamLists.push_back(
1491 Actions.ActOnTemplateParameterList(0, SourceLocation(),
1492 TemplateInfo.TemplateLoc,
1496 TemplateParams = &FakedParamLists;
1499 // Build the class template specialization.
1501 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK,
1502 StartLoc, DS.getModulePrivateSpecLoc(), SS,
1503 TemplateId->Template,
1504 TemplateId->TemplateNameLoc,
1505 TemplateId->LAngleLoc,
1507 TemplateId->RAngleLoc,
1509 MultiTemplateParamsArg(
1510 TemplateParams? &(*TemplateParams)[0] : 0,
1511 TemplateParams? TemplateParams->size() : 0));
1513 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1514 TUK == Sema::TUK_Declaration) {
1515 // Explicit instantiation of a member of a class template
1516 // specialization, e.g.,
1518 // template struct Outer<int>::Inner;
1520 ProhibitAttributes(attrs);
1523 = Actions.ActOnExplicitInstantiation(getCurScope(),
1524 TemplateInfo.ExternLoc,
1525 TemplateInfo.TemplateLoc,
1526 TagType, StartLoc, SS, Name,
1527 NameLoc, attrs.getList());
1528 } else if (TUK == Sema::TUK_Friend &&
1529 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1530 ProhibitAttributes(attrs);
1533 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1534 TagType, StartLoc, SS,
1535 Name, NameLoc, attrs.getList(),
1536 MultiTemplateParamsArg(
1537 TemplateParams? &(*TemplateParams)[0] : 0,
1538 TemplateParams? TemplateParams->size() : 0));
1540 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1541 ProhibitAttributes(attrs);
1543 bool IsDependent = false;
1545 // Don't pass down template parameter lists if this is just a tag
1546 // reference. For example, we don't need the template parameters here:
1547 // template <class T> class A *makeA(T t);
1548 MultiTemplateParamsArg TParams;
1549 if (TUK != Sema::TUK_Reference && TemplateParams)
1551 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1553 // Declaration or definition of a class type
1554 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1555 SS, Name, NameLoc, attrs.getList(), AS,
1556 DS.getModulePrivateSpecLoc(),
1557 TParams, Owned, IsDependent,
1558 SourceLocation(), false,
1559 clang::TypeResult());
1561 // If ActOnTag said the type was dependent, try again with the
1562 // less common call.
1564 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1565 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1566 SS, Name, StartLoc, NameLoc);
1570 // If there is a body, parse it and inform the actions module.
1571 if (TUK == Sema::TUK_Definition) {
1572 assert(Tok.is(tok::l_brace) ||
1573 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1574 isCXX11FinalKeyword());
1575 if (getLangOpts().CPlusPlus)
1576 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1577 TagOrTempResult.get());
1579 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1582 const char *PrevSpec = 0;
1585 if (!TypeResult.isInvalid()) {
1586 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1587 NameLoc.isValid() ? NameLoc : StartLoc,
1588 PrevSpec, DiagID, TypeResult.get());
1589 } else if (!TagOrTempResult.isInvalid()) {
1590 Result = DS.SetTypeSpecType(TagType, StartLoc,
1591 NameLoc.isValid() ? NameLoc : StartLoc,
1592 PrevSpec, DiagID, TagOrTempResult.get(), Owned);
1594 DS.SetTypeSpecError();
1599 Diag(StartLoc, DiagID) << PrevSpec;
1601 // At this point, we've successfully parsed a class-specifier in 'definition'
1602 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1603 // going to look at what comes after it to improve error recovery. If an
1604 // impossible token occurs next, we assume that the programmer forgot a ; at
1605 // the end of the declaration and recover that way.
1607 // Also enforce C++ [temp]p3:
1608 // In a template-declaration which defines a class, no declarator
1610 if (TUK == Sema::TUK_Definition &&
1611 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1612 if (Tok.isNot(tok::semi)) {
1613 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1614 DeclSpec::getSpecifierName(TagType));
1615 // Push this token back into the preprocessor and change our current token
1616 // to ';' so that the rest of the code recovers as though there were an
1617 // ';' after the definition.
1619 Tok.setKind(tok::semi);
1624 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1626 /// base-clause : [C++ class.derived]
1627 /// ':' base-specifier-list
1628 /// base-specifier-list:
1629 /// base-specifier '...'[opt]
1630 /// base-specifier-list ',' base-specifier '...'[opt]
1631 void Parser::ParseBaseClause(Decl *ClassDecl) {
1632 assert(Tok.is(tok::colon) && "Not a base clause");
1635 // Build up an array of parsed base specifiers.
1636 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1639 // Parse a base-specifier.
1640 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1641 if (Result.isInvalid()) {
1642 // Skip the rest of this base specifier, up until the comma or
1644 SkipUntil(tok::comma, tok::l_brace, true, true);
1646 // Add this to our array of base specifiers.
1647 BaseInfo.push_back(Result.get());
1650 // If the next token is a comma, consume it and keep reading
1652 if (Tok.isNot(tok::comma)) break;
1654 // Consume the comma.
1658 // Attach the base specifiers
1659 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1662 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1663 /// one entry in the base class list of a class specifier, for example:
1664 /// class foo : public bar, virtual private baz {
1665 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1667 /// base-specifier: [C++ class.derived]
1668 /// attribute-specifier-seq[opt] base-type-specifier
1669 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
1670 /// base-type-specifier
1671 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
1672 /// base-type-specifier
1673 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1674 bool IsVirtual = false;
1675 SourceLocation StartLoc = Tok.getLocation();
1677 ParsedAttributesWithRange Attributes(AttrFactory);
1678 MaybeParseCXX11Attributes(Attributes);
1680 // Parse the 'virtual' keyword.
1681 if (Tok.is(tok::kw_virtual)) {
1686 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1688 // Parse an (optional) access specifier.
1689 AccessSpecifier Access = getAccessSpecifierIfPresent();
1690 if (Access != AS_none)
1693 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1695 // Parse the 'virtual' keyword (again!), in case it came after the
1696 // access specifier.
1697 if (Tok.is(tok::kw_virtual)) {
1698 SourceLocation VirtualLoc = ConsumeToken();
1700 // Complain about duplicate 'virtual'
1701 Diag(VirtualLoc, diag::err_dup_virtual)
1702 << FixItHint::CreateRemoval(VirtualLoc);
1708 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1710 // Parse the class-name.
1711 SourceLocation EndLocation;
1712 SourceLocation BaseLoc;
1713 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1714 if (BaseType.isInvalid())
1717 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1718 // actually part of the base-specifier-list grammar productions, but we
1719 // parse it here for convenience.
1720 SourceLocation EllipsisLoc;
1721 if (Tok.is(tok::ellipsis))
1722 EllipsisLoc = ConsumeToken();
1724 // Find the complete source range for the base-specifier.
1725 SourceRange Range(StartLoc, EndLocation);
1727 // Notify semantic analysis that we have parsed a complete
1729 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
1730 Access, BaseType.get(), BaseLoc,
1734 /// getAccessSpecifierIfPresent - Determine whether the next token is
1735 /// a C++ access-specifier.
1737 /// access-specifier: [C++ class.derived]
1741 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1742 switch (Tok.getKind()) {
1743 default: return AS_none;
1744 case tok::kw_private: return AS_private;
1745 case tok::kw_protected: return AS_protected;
1746 case tok::kw_public: return AS_public;
1750 /// \brief If the given declarator has any parts for which parsing has to be
1751 /// delayed, e.g., default arguments, create a late-parsed method declaration
1752 /// record to handle the parsing at the end of the class definition.
1753 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1755 // We just declared a member function. If this member function
1756 // has any default arguments, we'll need to parse them later.
1757 LateParsedMethodDeclaration *LateMethod = 0;
1758 DeclaratorChunk::FunctionTypeInfo &FTI
1759 = DeclaratorInfo.getFunctionTypeInfo();
1761 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1762 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1764 // Push this method onto the stack of late-parsed method
1766 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1767 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1768 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1770 // Add all of the parameters prior to this one (they don't
1771 // have default arguments).
1772 LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1773 for (unsigned I = 0; I < ParamIdx; ++I)
1774 LateMethod->DefaultArgs.push_back(
1775 LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
1778 // Add this parameter to the list of parameters (it may or may
1779 // not have a default argument).
1780 LateMethod->DefaultArgs.push_back(
1781 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1782 FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1787 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
1793 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
1794 if (!getLangOpts().CPlusPlus)
1795 return VirtSpecifiers::VS_None;
1797 if (Tok.is(tok::identifier)) {
1798 IdentifierInfo *II = Tok.getIdentifierInfo();
1800 // Initialize the contextual keywords.
1802 Ident_final = &PP.getIdentifierTable().get("final");
1803 Ident_override = &PP.getIdentifierTable().get("override");
1806 if (II == Ident_override)
1807 return VirtSpecifiers::VS_Override;
1809 if (II == Ident_final)
1810 return VirtSpecifiers::VS_Final;
1813 return VirtSpecifiers::VS_None;
1816 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
1818 /// virt-specifier-seq:
1820 /// virt-specifier-seq virt-specifier
1821 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
1824 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
1825 if (Specifier == VirtSpecifiers::VS_None)
1828 // C++ [class.mem]p8:
1829 // A virt-specifier-seq shall contain at most one of each virt-specifier.
1830 const char *PrevSpec = 0;
1831 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
1832 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
1834 << FixItHint::CreateRemoval(Tok.getLocation());
1836 if (IsInterface && Specifier == VirtSpecifiers::VS_Final) {
1837 Diag(Tok.getLocation(), diag::err_override_control_interface)
1838 << VirtSpecifiers::getSpecifierName(Specifier);
1840 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
1841 diag::warn_cxx98_compat_override_control_keyword :
1842 diag::ext_override_control_keyword)
1843 << VirtSpecifiers::getSpecifierName(Specifier);
1849 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
1850 /// contextual 'final' keyword.
1851 bool Parser::isCXX11FinalKeyword() const {
1852 if (!getLangOpts().CPlusPlus)
1855 if (!Tok.is(tok::identifier))
1858 // Initialize the contextual keywords.
1860 Ident_final = &PP.getIdentifierTable().get("final");
1861 Ident_override = &PP.getIdentifierTable().get("override");
1864 return Tok.getIdentifierInfo() == Ident_final;
1867 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1869 /// member-declaration:
1870 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
1871 /// function-definition ';'[opt]
1872 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1873 /// using-declaration [TODO]
1874 /// [C++0x] static_assert-declaration
1875 /// template-declaration
1876 /// [GNU] '__extension__' member-declaration
1878 /// member-declarator-list:
1879 /// member-declarator
1880 /// member-declarator-list ',' member-declarator
1882 /// member-declarator:
1883 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
1884 /// declarator constant-initializer[opt]
1885 /// [C++11] declarator brace-or-equal-initializer[opt]
1886 /// identifier[opt] ':' constant-expression
1888 /// virt-specifier-seq:
1890 /// virt-specifier-seq virt-specifier
1899 /// constant-initializer:
1900 /// '=' constant-expression
1902 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1903 AttributeList *AccessAttrs,
1904 const ParsedTemplateInfo &TemplateInfo,
1905 ParsingDeclRAIIObject *TemplateDiags) {
1906 if (Tok.is(tok::at)) {
1907 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
1908 Diag(Tok, diag::err_at_defs_cxx);
1910 Diag(Tok, diag::err_at_in_class);
1913 SkipUntil(tok::r_brace);
1917 // Access declarations.
1918 bool MalformedTypeSpec = false;
1919 if (!TemplateInfo.Kind &&
1920 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) {
1921 if (TryAnnotateCXXScopeToken())
1922 MalformedTypeSpec = true;
1925 if (Tok.isNot(tok::annot_cxxscope))
1926 isAccessDecl = false;
1927 else if (NextToken().is(tok::identifier))
1928 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
1930 isAccessDecl = NextToken().is(tok::kw_operator);
1933 // Collect the scope specifier token we annotated earlier.
1935 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1936 /*EnteringContext=*/false);
1938 // Try to parse an unqualified-id.
1939 SourceLocation TemplateKWLoc;
1941 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
1942 TemplateKWLoc, Name)) {
1943 SkipUntil(tok::semi);
1947 // TODO: recover from mistakenly-qualified operator declarations.
1948 if (ExpectAndConsume(tok::semi,
1949 diag::err_expected_semi_after,
1950 "access declaration",
1954 Actions.ActOnUsingDeclaration(getCurScope(), AS,
1955 false, SourceLocation(),
1958 /* IsTypeName */ false,
1964 // static_assert-declaration
1965 if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) {
1966 // FIXME: Check for templates
1967 SourceLocation DeclEnd;
1968 ParseStaticAssertDeclaration(DeclEnd);
1972 if (Tok.is(tok::kw_template)) {
1973 assert(!TemplateInfo.TemplateParams &&
1974 "Nested template improperly parsed?");
1975 SourceLocation DeclEnd;
1976 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
1981 // Handle: member-declaration ::= '__extension__' member-declaration
1982 if (Tok.is(tok::kw___extension__)) {
1983 // __extension__ silences extension warnings in the subexpression.
1984 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1986 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
1987 TemplateInfo, TemplateDiags);
1990 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1992 ColonProtectionRAIIObject X(*this);
1994 ParsedAttributesWithRange attrs(AttrFactory);
1995 ParsedAttributesWithRange FnAttrs(AttrFactory);
1996 // Optional C++11 attribute-specifier
1997 MaybeParseCXX11Attributes(attrs);
1998 // We need to keep these attributes for future diagnostic
1999 // before they are taken over by declaration specifier.
2000 FnAttrs.addAll(attrs.getList());
2001 FnAttrs.Range = attrs.Range;
2003 MaybeParseMicrosoftAttributes(attrs);
2005 if (Tok.is(tok::kw_using)) {
2006 ProhibitAttributes(attrs);
2009 SourceLocation UsingLoc = ConsumeToken();
2011 if (Tok.is(tok::kw_namespace)) {
2012 Diag(UsingLoc, diag::err_using_namespace_in_class);
2013 SkipUntil(tok::semi, true, true);
2015 SourceLocation DeclEnd;
2016 // Otherwise, it must be a using-declaration or an alias-declaration.
2017 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2018 UsingLoc, DeclEnd, AS);
2023 // Hold late-parsed attributes so we can attach a Decl to them later.
2024 LateParsedAttrList CommonLateParsedAttrs;
2026 // decl-specifier-seq:
2027 // Parse the common declaration-specifiers piece.
2028 ParsingDeclSpec DS(*this, TemplateDiags);
2029 DS.takeAttributesFrom(attrs);
2030 if (MalformedTypeSpec)
2031 DS.SetTypeSpecError();
2032 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2033 &CommonLateParsedAttrs);
2035 MultiTemplateParamsArg TemplateParams(
2036 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
2037 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2039 if (Tok.is(tok::semi)) {
2042 if (DS.isFriendSpecified())
2043 ProhibitAttributes(FnAttrs);
2046 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
2047 DS.complete(TheDecl);
2051 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2054 // Hold late-parsed attributes so we can attach a Decl to them later.
2055 LateParsedAttrList LateParsedAttrs;
2057 SourceLocation EqualLoc;
2058 bool HasInitializer = false;
2060 if (Tok.isNot(tok::colon)) {
2061 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2062 ColonProtectionRAIIObject X(*this);
2064 // Parse the first declarator.
2065 ParseDeclarator(DeclaratorInfo);
2066 // Error parsing the declarator?
2067 if (!DeclaratorInfo.hasName()) {
2068 // If so, skip until the semi-colon or a }.
2069 SkipUntil(tok::r_brace, true, true);
2070 if (Tok.is(tok::semi))
2075 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface);
2077 // If attributes exist after the declarator, but before an '{', parse them.
2078 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2080 // MSVC permits pure specifier on inline functions declared at class scope.
2081 // Hence check for =0 before checking for function definition.
2082 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
2083 DeclaratorInfo.isFunctionDeclarator() &&
2084 NextToken().is(tok::numeric_constant)) {
2085 EqualLoc = ConsumeToken();
2086 Init = ParseInitializer();
2087 if (Init.isInvalid())
2088 SkipUntil(tok::comma, true, true);
2090 HasInitializer = true;
2093 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2094 // function-definition:
2096 // In C++11, a non-function declarator followed by an open brace is a
2097 // braced-init-list for an in-class member initialization, not an
2098 // erroneous function definition.
2099 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2100 DefinitionKind = FDK_Definition;
2101 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2102 if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
2103 DefinitionKind = FDK_Definition;
2104 } else if (Tok.is(tok::equal)) {
2105 const Token &KW = NextToken();
2106 if (KW.is(tok::kw_default))
2107 DefinitionKind = FDK_Defaulted;
2108 else if (KW.is(tok::kw_delete))
2109 DefinitionKind = FDK_Deleted;
2113 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2114 // to a friend declaration, that declaration shall be a definition.
2115 if (DeclaratorInfo.isFunctionDeclarator() &&
2116 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2117 // Diagnose attributes that appear before decl specifier:
2118 // [[]] friend int foo();
2119 ProhibitAttributes(FnAttrs);
2122 if (DefinitionKind) {
2123 if (!DeclaratorInfo.isFunctionDeclarator()) {
2124 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2126 SkipUntil(tok::r_brace, /*StopAtSemi*/false);
2128 // Consume the optional ';'
2129 if (Tok.is(tok::semi))
2134 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2135 Diag(DeclaratorInfo.getIdentifierLoc(),
2136 diag::err_function_declared_typedef);
2138 // Recover by treating the 'typedef' as spurious.
2139 DS.ClearStorageClassSpecs();
2143 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2144 VS, DefinitionKind, Init);
2146 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2147 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2149 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2150 LateParsedAttrs[i]->addDecl(FunDecl);
2152 LateParsedAttrs.clear();
2154 // Consume the ';' - it's optional unless we have a delete or default
2155 if (Tok.is(tok::semi))
2156 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2162 // member-declarator-list:
2163 // member-declarator
2164 // member-declarator-list ',' member-declarator
2166 SmallVector<Decl *, 8> DeclsInGroup;
2167 ExprResult BitfieldSize;
2168 bool ExpectSemi = true;
2171 // member-declarator:
2172 // declarator pure-specifier[opt]
2173 // declarator brace-or-equal-initializer[opt]
2174 // identifier[opt] ':' constant-expression
2175 if (Tok.is(tok::colon)) {
2177 BitfieldSize = ParseConstantExpression();
2178 if (BitfieldSize.isInvalid())
2179 SkipUntil(tok::comma, true, true);
2182 // If a simple-asm-expr is present, parse it.
2183 if (Tok.is(tok::kw_asm)) {
2185 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2186 if (AsmLabel.isInvalid())
2187 SkipUntil(tok::comma, true, true);
2189 DeclaratorInfo.setAsmLabel(AsmLabel.release());
2190 DeclaratorInfo.SetRangeEnd(Loc);
2193 // If attributes exist after the declarator, parse them.
2194 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2196 // FIXME: When g++ adds support for this, we'll need to check whether it
2197 // goes before or after the GNU attributes and __asm__.
2198 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface);
2200 InClassInitStyle HasInClassInit = ICIS_NoInit;
2201 if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
2202 if (BitfieldSize.get()) {
2203 Diag(Tok, diag::err_bitfield_member_init);
2204 SkipUntil(tok::comma, true, true);
2206 HasInitializer = true;
2207 if (!DeclaratorInfo.isDeclarationOfFunction() &&
2208 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2209 != DeclSpec::SCS_typedef)
2210 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2214 // NOTE: If Sema is the Action module and declarator is an instance field,
2215 // this call will *not* return the created decl; It will return null.
2216 // See Sema::ActOnCXXMemberDeclarator for details.
2218 NamedDecl *ThisDecl = 0;
2219 if (DS.isFriendSpecified()) {
2220 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2221 // to a friend declaration, that declaration shall be a definition.
2223 // Diagnose attributes appear after friend member function declarator:
2225 SmallVector<SourceRange, 4> Ranges;
2226 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2227 if (!Ranges.empty()) {
2228 for (SmallVector<SourceRange, 4>::iterator I = Ranges.begin(),
2229 E = Ranges.end(); I != E; ++I) {
2230 Diag((*I).getBegin(), diag::err_attributes_not_allowed)
2235 // TODO: handle initializers, bitfields, 'delete'
2236 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2239 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2242 BitfieldSize.release(),
2243 VS, HasInClassInit);
2245 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs,
2249 // Set the Decl for any late parsed attributes
2250 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2251 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2253 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2254 LateParsedAttrs[i]->addDecl(ThisDecl);
2256 LateParsedAttrs.clear();
2258 // Handle the initializer.
2259 if (HasInClassInit != ICIS_NoInit &&
2260 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2261 DeclSpec::SCS_static) {
2262 // The initializer was deferred; parse it and cache the tokens.
2263 Diag(Tok, getLangOpts().CPlusPlus11 ?
2264 diag::warn_cxx98_compat_nonstatic_member_init :
2265 diag::ext_nonstatic_member_init);
2267 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2268 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2269 // declarator is followed by an initializer.
2271 // A brace-or-equal-initializer for a member-declarator is not an
2272 // initializer in the grammar, so this is ill-formed.
2273 Diag(Tok, diag::err_incomplete_array_member_init);
2274 SkipUntil(tok::comma, true, true);
2276 // Avoid later warnings about a class member of incomplete type.
2277 ThisDecl->setInvalidDecl();
2279 ParseCXXNonStaticMemberInitializer(ThisDecl);
2280 } else if (HasInitializer) {
2281 // Normal initializer.
2282 if (!Init.isUsable())
2283 Init = ParseCXXMemberInitializer(ThisDecl,
2284 DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2286 if (Init.isInvalid())
2287 SkipUntil(tok::comma, true, true);
2289 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2290 DS.containsPlaceholderType());
2291 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2293 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
2297 Actions.FinalizeDeclaration(ThisDecl);
2298 DeclsInGroup.push_back(ThisDecl);
2301 if (ThisDecl && DeclaratorInfo.isFunctionDeclarator() &&
2302 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2303 != DeclSpec::SCS_typedef) {
2304 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2307 DeclaratorInfo.complete(ThisDecl);
2309 // If we don't have a comma, it is either the end of the list (a ';')
2310 // or an error, bail out.
2311 if (Tok.isNot(tok::comma))
2314 // Consume the comma.
2315 SourceLocation CommaLoc = ConsumeToken();
2317 if (Tok.isAtStartOfLine() &&
2318 !MightBeDeclarator(Declarator::MemberContext)) {
2319 // This comma was followed by a line-break and something which can't be
2320 // the start of a declarator. The comma was probably a typo for a
2322 Diag(CommaLoc, diag::err_expected_semi_declaration)
2323 << FixItHint::CreateReplacement(CommaLoc, ";");
2328 // Parse the next declarator.
2329 DeclaratorInfo.clear();
2331 BitfieldSize = true;
2333 HasInitializer = false;
2334 DeclaratorInfo.setCommaLoc(CommaLoc);
2336 // Attributes are only allowed on the second declarator.
2337 MaybeParseGNUAttributes(DeclaratorInfo);
2339 if (Tok.isNot(tok::colon))
2340 ParseDeclarator(DeclaratorInfo);
2344 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2345 // Skip to end of block or statement.
2346 SkipUntil(tok::r_brace, true, true);
2347 // If we stopped at a ';', eat it.
2348 if (Tok.is(tok::semi)) ConsumeToken();
2352 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(),
2353 DeclsInGroup.size());
2356 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
2357 /// pure-specifier. Also detect and reject any attempted defaulted/deleted
2358 /// function definition. The location of the '=', if any, will be placed in
2364 /// brace-or-equal-initializer:
2365 /// '=' initializer-expression
2366 /// braced-init-list
2368 /// initializer-clause:
2369 /// assignment-expression
2370 /// braced-init-list
2372 /// defaulted/deleted function-definition:
2376 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2377 /// be a constant-expression.
2378 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2379 SourceLocation &EqualLoc) {
2380 assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
2381 && "Data member initializer not starting with '=' or '{'");
2383 EnterExpressionEvaluationContext Context(Actions,
2384 Sema::PotentiallyEvaluated,
2386 if (Tok.is(tok::equal)) {
2387 EqualLoc = ConsumeToken();
2388 if (Tok.is(tok::kw_delete)) {
2389 // In principle, an initializer of '= delete p;' is legal, but it will
2390 // never type-check. It's better to diagnose it as an ill-formed expression
2391 // than as an ill-formed deleted non-function member.
2392 // An initializer of '= delete p, foo' will never be parsed, because
2393 // a top-level comma always ends the initializer expression.
2394 const Token &Next = NextToken();
2395 if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) ||
2396 Next.is(tok::eof)) {
2398 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2401 Diag(ConsumeToken(), diag::err_deleted_non_function);
2402 return ExprResult();
2404 } else if (Tok.is(tok::kw_default)) {
2406 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2409 Diag(ConsumeToken(), diag::err_default_special_members);
2410 return ExprResult();
2414 return ParseInitializer();
2417 /// ParseCXXMemberSpecification - Parse the class definition.
2419 /// member-specification:
2420 /// member-declaration member-specification[opt]
2421 /// access-specifier ':' member-specification[opt]
2423 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2424 SourceLocation AttrFixitLoc,
2425 ParsedAttributesWithRange &Attrs,
2426 unsigned TagType, Decl *TagDecl) {
2427 assert((TagType == DeclSpec::TST_struct ||
2428 TagType == DeclSpec::TST_interface ||
2429 TagType == DeclSpec::TST_union ||
2430 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2432 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2433 "parsing struct/union/class body");
2435 // Determine whether this is a non-nested class. Note that local
2436 // classes are *not* considered to be nested classes.
2437 bool NonNestedClass = true;
2438 if (!ClassStack.empty()) {
2439 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2440 if (S->isClassScope()) {
2441 // We're inside a class scope, so this is a nested class.
2442 NonNestedClass = false;
2444 // The Microsoft extension __interface does not permit nested classes.
2445 if (getCurrentClass().IsInterface) {
2446 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2448 << (isa<NamedDecl>(TagDecl)
2449 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2455 if ((S->getFlags() & Scope::FnScope)) {
2456 // If we're in a function or function template declared in the
2457 // body of a class, then this is a local class rather than a
2459 const Scope *Parent = S->getParent();
2460 if (Parent->isTemplateParamScope())
2461 Parent = Parent->getParent();
2462 if (Parent->isClassScope())
2468 // Enter a scope for the class.
2469 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2471 // Note that we are parsing a new (potentially-nested) class definition.
2472 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2473 TagType == DeclSpec::TST_interface);
2476 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2478 SourceLocation FinalLoc;
2480 // Parse the optional 'final' keyword.
2481 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2482 assert(isCXX11FinalKeyword() && "not a class definition");
2483 FinalLoc = ConsumeToken();
2485 if (TagType == DeclSpec::TST_interface) {
2486 Diag(FinalLoc, diag::err_override_control_interface)
2489 Diag(FinalLoc, getLangOpts().CPlusPlus11 ?
2490 diag::warn_cxx98_compat_override_control_keyword :
2491 diag::ext_override_control_keyword) << "final";
2494 // Parse any C++11 attributes after 'final' keyword.
2495 // These attributes are not allowed to appear here,
2496 // and the only possible place for them to appertain
2497 // to the class would be between class-key and class-name.
2498 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2501 if (Tok.is(tok::colon)) {
2502 ParseBaseClause(TagDecl);
2504 if (!Tok.is(tok::l_brace)) {
2505 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
2508 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2513 assert(Tok.is(tok::l_brace));
2514 BalancedDelimiterTracker T(*this, tok::l_brace);
2518 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2519 T.getOpenLocation());
2521 // C++ 11p3: Members of a class defined with the keyword class are private
2522 // by default. Members of a class defined with the keywords struct or union
2523 // are public by default.
2524 AccessSpecifier CurAS;
2525 if (TagType == DeclSpec::TST_class)
2529 ParsedAttributes AccessAttrs(AttrFactory);
2532 // While we still have something to read, read the member-declarations.
2533 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2534 // Each iteration of this loop reads one member-declaration.
2536 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
2537 Tok.is(tok::kw___if_not_exists))) {
2538 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2542 // Check for extraneous top-level semicolon.
2543 if (Tok.is(tok::semi)) {
2544 ConsumeExtraSemi(InsideStruct, TagType);
2548 if (Tok.is(tok::annot_pragma_vis)) {
2549 HandlePragmaVisibility();
2553 if (Tok.is(tok::annot_pragma_pack)) {
2558 if (Tok.is(tok::annot_pragma_align)) {
2559 HandlePragmaAlign();
2563 if (Tok.is(tok::annot_pragma_openmp)) {
2564 ParseOpenMPDeclarativeDirective();
2568 AccessSpecifier AS = getAccessSpecifierIfPresent();
2569 if (AS != AS_none) {
2570 // Current token is a C++ access specifier.
2572 SourceLocation ASLoc = Tok.getLocation();
2573 unsigned TokLength = Tok.getLength();
2575 AccessAttrs.clear();
2576 MaybeParseGNUAttributes(AccessAttrs);
2578 SourceLocation EndLoc;
2579 if (Tok.is(tok::colon)) {
2580 EndLoc = Tok.getLocation();
2582 } else if (Tok.is(tok::semi)) {
2583 EndLoc = Tok.getLocation();
2585 Diag(EndLoc, diag::err_expected_colon)
2586 << FixItHint::CreateReplacement(EndLoc, ":");
2588 EndLoc = ASLoc.getLocWithOffset(TokLength);
2589 Diag(EndLoc, diag::err_expected_colon)
2590 << FixItHint::CreateInsertion(EndLoc, ":");
2593 // The Microsoft extension __interface does not permit non-public
2594 // access specifiers.
2595 if (TagType == DeclSpec::TST_interface && CurAS != AS_public) {
2596 Diag(ASLoc, diag::err_access_specifier_interface)
2597 << (CurAS == AS_protected);
2600 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
2601 AccessAttrs.getList())) {
2602 // found another attribute than only annotations
2603 AccessAttrs.clear();
2609 // FIXME: Make sure we don't have a template here.
2611 // Parse all the comma separated declarators.
2612 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
2617 SkipUntil(tok::r_brace, false, false);
2620 // If attributes exist after class contents, parse them.
2621 ParsedAttributes attrs(AttrFactory);
2622 MaybeParseGNUAttributes(attrs);
2625 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
2626 T.getOpenLocation(),
2627 T.getCloseLocation(),
2630 // C++11 [class.mem]p2:
2631 // Within the class member-specification, the class is regarded as complete
2632 // within function bodies, default arguments, and
2633 // brace-or-equal-initializers for non-static data members (including such
2634 // things in nested classes).
2635 if (TagDecl && NonNestedClass) {
2636 // We are not inside a nested class. This class and its nested classes
2637 // are complete and we can parse the delayed portions of method
2638 // declarations and the lexed inline method definitions, along with any
2639 // delayed attributes.
2640 SourceLocation SavedPrevTokLocation = PrevTokLocation;
2641 ParseLexedAttributes(getCurrentClass());
2642 ParseLexedMethodDeclarations(getCurrentClass());
2644 // We've finished with all pending member declarations.
2645 Actions.ActOnFinishCXXMemberDecls();
2647 ParseLexedMemberInitializers(getCurrentClass());
2648 ParseLexedMethodDefs(getCurrentClass());
2649 PrevTokLocation = SavedPrevTokLocation;
2653 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
2654 T.getCloseLocation());
2656 // Leave the class scope.
2661 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
2662 /// which explicitly initializes the members or base classes of a
2663 /// class (C++ [class.base.init]). For example, the three initializers
2664 /// after the ':' in the Derived constructor below:
2668 /// class Derived : Base {
2672 /// Derived(float f) : Base(), x(17), f(f) { }
2676 /// [C++] ctor-initializer:
2677 /// ':' mem-initializer-list
2679 /// [C++] mem-initializer-list:
2680 /// mem-initializer ...[opt]
2681 /// mem-initializer ...[opt] , mem-initializer-list
2682 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
2683 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
2685 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers
2686 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
2687 SourceLocation ColonLoc = ConsumeToken();
2689 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
2690 bool AnyErrors = false;
2693 if (Tok.is(tok::code_completion)) {
2694 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
2695 MemInitializers.data(),
2696 MemInitializers.size());
2697 return cutOffParsing();
2699 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
2700 if (!MemInit.isInvalid())
2701 MemInitializers.push_back(MemInit.get());
2706 if (Tok.is(tok::comma))
2708 else if (Tok.is(tok::l_brace))
2710 // If the next token looks like a base or member initializer, assume that
2711 // we're just missing a comma.
2712 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
2713 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2714 Diag(Loc, diag::err_ctor_init_missing_comma)
2715 << FixItHint::CreateInsertion(Loc, ", ");
2717 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2718 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
2719 SkipUntil(tok::l_brace, true, true);
2724 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
2728 /// ParseMemInitializer - Parse a C++ member initializer, which is
2729 /// part of a constructor initializer that explicitly initializes one
2730 /// member or base class (C++ [class.base.init]). See
2731 /// ParseConstructorInitializer for an example.
2733 /// [C++] mem-initializer:
2734 /// mem-initializer-id '(' expression-list[opt] ')'
2735 /// [C++0x] mem-initializer-id braced-init-list
2737 /// [C++] mem-initializer-id:
2738 /// '::'[opt] nested-name-specifier[opt] class-name
2740 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
2741 // parse '::'[opt] nested-name-specifier[opt]
2743 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
2744 ParsedType TemplateTypeTy;
2745 if (Tok.is(tok::annot_template_id)) {
2746 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2747 if (TemplateId->Kind == TNK_Type_template ||
2748 TemplateId->Kind == TNK_Dependent_template_name) {
2749 AnnotateTemplateIdTokenAsType();
2750 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
2751 TemplateTypeTy = getTypeAnnotation(Tok);
2754 // Uses of decltype will already have been converted to annot_decltype by
2755 // ParseOptionalCXXScopeSpecifier at this point.
2756 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
2757 && Tok.isNot(tok::annot_decltype)) {
2758 Diag(Tok, diag::err_expected_member_or_base_name);
2762 IdentifierInfo *II = 0;
2763 DeclSpec DS(AttrFactory);
2764 SourceLocation IdLoc = Tok.getLocation();
2765 if (Tok.is(tok::annot_decltype)) {
2766 // Get the decltype expression, if there is one.
2767 ParseDecltypeSpecifier(DS);
2769 if (Tok.is(tok::identifier))
2770 // Get the identifier. This may be a member name or a class name,
2771 // but we'll let the semantic analysis determine which it is.
2772 II = Tok.getIdentifierInfo();
2778 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2779 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2781 ExprResult InitList = ParseBraceInitializer();
2782 if (InitList.isInvalid())
2785 SourceLocation EllipsisLoc;
2786 if (Tok.is(tok::ellipsis))
2787 EllipsisLoc = ConsumeToken();
2789 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2790 TemplateTypeTy, DS, IdLoc,
2791 InitList.take(), EllipsisLoc);
2792 } else if(Tok.is(tok::l_paren)) {
2793 BalancedDelimiterTracker T(*this, tok::l_paren);
2796 // Parse the optional expression-list.
2797 ExprVector ArgExprs;
2798 CommaLocsTy CommaLocs;
2799 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
2800 SkipUntil(tok::r_paren);
2806 SourceLocation EllipsisLoc;
2807 if (Tok.is(tok::ellipsis))
2808 EllipsisLoc = ConsumeToken();
2810 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2811 TemplateTypeTy, DS, IdLoc,
2812 T.getOpenLocation(), ArgExprs.data(),
2813 ArgExprs.size(), T.getCloseLocation(),
2817 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::err_expected_lparen_or_lbrace
2818 : diag::err_expected_lparen);
2822 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
2824 /// exception-specification:
2825 /// dynamic-exception-specification
2826 /// noexcept-specification
2828 /// noexcept-specification:
2830 /// 'noexcept' '(' constant-expression ')'
2831 ExceptionSpecificationType
2832 Parser::tryParseExceptionSpecification(
2833 SourceRange &SpecificationRange,
2834 SmallVectorImpl<ParsedType> &DynamicExceptions,
2835 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2836 ExprResult &NoexceptExpr) {
2837 ExceptionSpecificationType Result = EST_None;
2839 // See if there's a dynamic specification.
2840 if (Tok.is(tok::kw_throw)) {
2841 Result = ParseDynamicExceptionSpecification(SpecificationRange,
2843 DynamicExceptionRanges);
2844 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
2845 "Produced different number of exception types and ranges.");
2848 // If there's no noexcept specification, we're done.
2849 if (Tok.isNot(tok::kw_noexcept))
2852 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
2854 // If we already had a dynamic specification, parse the noexcept for,
2855 // recovery, but emit a diagnostic and don't store the results.
2856 SourceRange NoexceptRange;
2857 ExceptionSpecificationType NoexceptType = EST_None;
2859 SourceLocation KeywordLoc = ConsumeToken();
2860 if (Tok.is(tok::l_paren)) {
2861 // There is an argument.
2862 BalancedDelimiterTracker T(*this, tok::l_paren);
2864 NoexceptType = EST_ComputedNoexcept;
2865 NoexceptExpr = ParseConstantExpression();
2866 // The argument must be contextually convertible to bool. We use
2867 // ActOnBooleanCondition for this purpose.
2868 if (!NoexceptExpr.isInvalid())
2869 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
2870 NoexceptExpr.get());
2872 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
2874 // There is no argument.
2875 NoexceptType = EST_BasicNoexcept;
2876 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
2879 if (Result == EST_None) {
2880 SpecificationRange = NoexceptRange;
2881 Result = NoexceptType;
2883 // If there's a dynamic specification after a noexcept specification,
2884 // parse that and ignore the results.
2885 if (Tok.is(tok::kw_throw)) {
2886 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2887 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
2888 DynamicExceptionRanges);
2891 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2897 /// ParseDynamicExceptionSpecification - Parse a C++
2898 /// dynamic-exception-specification (C++ [except.spec]).
2900 /// dynamic-exception-specification:
2901 /// 'throw' '(' type-id-list [opt] ')'
2902 /// [MS] 'throw' '(' '...' ')'
2905 /// type-id ... [opt]
2906 /// type-id-list ',' type-id ... [opt]
2908 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
2909 SourceRange &SpecificationRange,
2910 SmallVectorImpl<ParsedType> &Exceptions,
2911 SmallVectorImpl<SourceRange> &Ranges) {
2912 assert(Tok.is(tok::kw_throw) && "expected throw");
2914 SpecificationRange.setBegin(ConsumeToken());
2915 BalancedDelimiterTracker T(*this, tok::l_paren);
2916 if (T.consumeOpen()) {
2917 Diag(Tok, diag::err_expected_lparen_after) << "throw";
2918 SpecificationRange.setEnd(SpecificationRange.getBegin());
2919 return EST_DynamicNone;
2922 // Parse throw(...), a Microsoft extension that means "this function
2923 // can throw anything".
2924 if (Tok.is(tok::ellipsis)) {
2925 SourceLocation EllipsisLoc = ConsumeToken();
2926 if (!getLangOpts().MicrosoftExt)
2927 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
2929 SpecificationRange.setEnd(T.getCloseLocation());
2933 // Parse the sequence of type-ids.
2935 while (Tok.isNot(tok::r_paren)) {
2936 TypeResult Res(ParseTypeName(&Range));
2938 if (Tok.is(tok::ellipsis)) {
2939 // C++0x [temp.variadic]p5:
2940 // - In a dynamic-exception-specification (15.4); the pattern is a
2942 SourceLocation Ellipsis = ConsumeToken();
2943 Range.setEnd(Ellipsis);
2944 if (!Res.isInvalid())
2945 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
2948 if (!Res.isInvalid()) {
2949 Exceptions.push_back(Res.get());
2950 Ranges.push_back(Range);
2953 if (Tok.is(tok::comma))
2960 SpecificationRange.setEnd(T.getCloseLocation());
2961 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
2964 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
2965 /// function declaration.
2966 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
2967 assert(Tok.is(tok::arrow) && "expected arrow");
2971 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
2974 /// \brief We have just started parsing the definition of a new class,
2975 /// so push that class onto our stack of classes that is currently
2977 Sema::ParsingClassState
2978 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
2980 assert((NonNestedClass || !ClassStack.empty()) &&
2981 "Nested class without outer class");
2982 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
2983 return Actions.PushParsingClass();
2986 /// \brief Deallocate the given parsed class and all of its nested
2988 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
2989 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
2990 delete Class->LateParsedDeclarations[I];
2994 /// \brief Pop the top class of the stack of classes that are
2995 /// currently being parsed.
2997 /// This routine should be called when we have finished parsing the
2998 /// definition of a class, but have not yet popped the Scope
2999 /// associated with the class's definition.
3000 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3001 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3003 Actions.PopParsingClass(state);
3005 ParsingClass *Victim = ClassStack.top();
3007 if (Victim->TopLevelClass) {
3008 // Deallocate all of the nested classes of this class,
3009 // recursively: we don't need to keep any of this information.
3010 DeallocateParsedClasses(Victim);
3013 assert(!ClassStack.empty() && "Missing top-level class?");
3015 if (Victim->LateParsedDeclarations.empty()) {
3016 // The victim is a nested class, but we will not need to perform
3017 // any processing after the definition of this class since it has
3018 // no members whose handling was delayed. Therefore, we can just
3019 // remove this nested class.
3020 DeallocateParsedClasses(Victim);
3024 // This nested class has some members that will need to be processed
3025 // after the top-level class is completely defined. Therefore, add
3026 // it to the list of nested classes within its parent.
3027 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3028 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3029 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3032 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3034 /// \return the parsed identifier on success, and 0 if the next token is not an
3035 /// attribute-token.
3037 /// C++11 [dcl.attr.grammar]p3:
3038 /// If a keyword or an alternative token that satisfies the syntactic
3039 /// requirements of an identifier is contained in an attribute-token,
3040 /// it is considered an identifier.
3041 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3042 switch (Tok.getKind()) {
3044 // Identifiers and keywords have identifier info attached.
3045 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3046 Loc = ConsumeToken();
3051 case tok::ampamp: // 'and'
3052 case tok::pipe: // 'bitor'
3053 case tok::pipepipe: // 'or'
3054 case tok::caret: // 'xor'
3055 case tok::tilde: // 'compl'
3056 case tok::amp: // 'bitand'
3057 case tok::ampequal: // 'and_eq'
3058 case tok::pipeequal: // 'or_eq'
3059 case tok::caretequal: // 'xor_eq'
3060 case tok::exclaim: // 'not'
3061 case tok::exclaimequal: // 'not_eq'
3062 // Alternative tokens do not have identifier info, but their spelling
3063 // starts with an alphabetical character.
3064 SmallString<8> SpellingBuf;
3065 StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf);
3066 if (isLetter(Spelling[0])) {
3067 Loc = ConsumeToken();
3068 return &PP.getIdentifierTable().get(Spelling);
3074 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3075 IdentifierInfo *ScopeName) {
3076 switch (AttributeList::getKind(AttrName, ScopeName,
3077 AttributeList::AS_CXX11)) {
3078 case AttributeList::AT_CarriesDependency:
3079 case AttributeList::AT_FallThrough:
3080 case AttributeList::AT_CXX11NoReturn: {
3089 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Currently
3090 /// only parses standard attributes.
3092 /// [C++11] attribute-specifier:
3093 /// '[' '[' attribute-list ']' ']'
3094 /// alignment-specifier
3096 /// [C++11] attribute-list:
3098 /// attribute-list ',' attribute[opt]
3100 /// attribute-list ',' attribute '...'
3102 /// [C++11] attribute:
3103 /// attribute-token attribute-argument-clause[opt]
3105 /// [C++11] attribute-token:
3107 /// attribute-scoped-token
3109 /// [C++11] attribute-scoped-token:
3110 /// attribute-namespace '::' identifier
3112 /// [C++11] attribute-namespace:
3115 /// [C++11] attribute-argument-clause:
3116 /// '(' balanced-token-seq ')'
3118 /// [C++11] balanced-token-seq:
3120 /// balanced-token-seq balanced-token
3122 /// [C++11] balanced-token:
3123 /// '(' balanced-token-seq ')'
3124 /// '[' balanced-token-seq ']'
3125 /// '{' balanced-token-seq '}'
3126 /// any token but '(', ')', '[', ']', '{', or '}'
3127 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3128 SourceLocation *endLoc) {
3129 if (Tok.is(tok::kw_alignas)) {
3130 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3131 ParseAlignmentSpecifier(attrs, endLoc);
3135 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3136 && "Not a C++11 attribute list");
3138 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3143 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3145 while (Tok.isNot(tok::r_square)) {
3146 // attribute not present
3147 if (Tok.is(tok::comma)) {
3152 SourceLocation ScopeLoc, AttrLoc;
3153 IdentifierInfo *ScopeName = 0, *AttrName = 0;
3155 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3157 // Break out to the "expected ']'" diagnostic.
3161 if (Tok.is(tok::coloncolon)) {
3164 ScopeName = AttrName;
3167 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3169 Diag(Tok.getLocation(), diag::err_expected_ident);
3170 SkipUntil(tok::r_square, tok::comma, true, true);
3175 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName,ScopeName);
3176 bool AttrParsed = false;
3179 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3180 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
3181 << AttrName << SourceRange(SeenAttrs[AttrName]);
3183 // Parse attribute arguments
3184 if (Tok.is(tok::l_paren)) {
3185 if (ScopeName && ScopeName->getName() == "gnu") {
3186 ParseGNUAttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3187 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3191 Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_arguments)
3192 << AttrName->getName();
3194 // FIXME: handle other formats of c++11 attribute arguments
3196 SkipUntil(tok::r_paren, false);
3201 attrs.addNew(AttrName,
3202 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3204 ScopeName, ScopeLoc, 0,
3205 SourceLocation(), 0, 0, AttributeList::AS_CXX11);
3207 if (Tok.is(tok::ellipsis)) {
3210 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3211 << AttrName->getName();
3215 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
3216 SkipUntil(tok::r_square, false);
3218 *endLoc = Tok.getLocation();
3219 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
3220 SkipUntil(tok::r_square, false);
3223 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3225 /// attribute-specifier-seq:
3226 /// attribute-specifier-seq[opt] attribute-specifier
3227 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3228 SourceLocation *endLoc) {
3229 assert(getLangOpts().CPlusPlus11);
3231 SourceLocation StartLoc = Tok.getLocation(), Loc;
3236 ParseCXX11AttributeSpecifier(attrs, endLoc);
3237 } while (isCXX11AttributeSpecifier());
3239 attrs.Range = SourceRange(StartLoc, *endLoc);
3242 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
3244 /// [MS] ms-attribute:
3245 /// '[' token-seq ']'
3247 /// [MS] ms-attribute-seq:
3248 /// ms-attribute[opt]
3249 /// ms-attribute ms-attribute-seq
3250 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3251 SourceLocation *endLoc) {
3252 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3254 while (Tok.is(tok::l_square)) {
3255 // FIXME: If this is actually a C++11 attribute, parse it as one.
3257 SkipUntil(tok::r_square, true, true);
3258 if (endLoc) *endLoc = Tok.getLocation();
3259 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare);
3263 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3264 AccessSpecifier& CurAS) {
3265 IfExistsCondition Result;
3266 if (ParseMicrosoftIfExistsCondition(Result))
3269 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3270 if (Braces.consumeOpen()) {
3271 Diag(Tok, diag::err_expected_lbrace);
3275 switch (Result.Behavior) {
3277 // Parse the declarations below.
3281 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3282 << Result.IsIfExists;
3283 // Fall through to skip.
3290 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
3291 // __if_exists, __if_not_exists can nest.
3292 if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
3293 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3297 // Check for extraneous top-level semicolon.
3298 if (Tok.is(tok::semi)) {
3299 ConsumeExtraSemi(InsideStruct, TagType);
3303 AccessSpecifier AS = getAccessSpecifierIfPresent();
3304 if (AS != AS_none) {
3305 // Current token is a C++ access specifier.
3307 SourceLocation ASLoc = Tok.getLocation();
3309 if (Tok.is(tok::colon))
3310 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3312 Diag(Tok, diag::err_expected_colon);
3317 // Parse all the comma separated declarators.
3318 ParseCXXClassMemberDeclaration(CurAS, 0);
3321 Braces.consumeClose();