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/AST/DeclTemplate.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/PrettyDeclStackTrace.h"
23 #include "clang/Sema/Scope.h"
24 #include "clang/Sema/SemaDiagnostic.h"
25 #include "llvm/ADT/SmallString.h"
26 using namespace clang;
28 /// ParseNamespace - We know that the current token is a namespace keyword. This
29 /// may either be a top level namespace or a block-level namespace alias. If
30 /// there was an inline keyword, it has already been parsed.
32 /// namespace-definition: [C++ 7.3: basic.namespace]
33 /// named-namespace-definition
34 /// unnamed-namespace-definition
36 /// unnamed-namespace-definition:
37 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
39 /// named-namespace-definition:
40 /// original-namespace-definition
41 /// extension-namespace-definition
43 /// original-namespace-definition:
44 /// 'inline'[opt] 'namespace' identifier attributes[opt]
45 /// '{' namespace-body '}'
47 /// extension-namespace-definition:
48 /// 'inline'[opt] 'namespace' original-namespace-name
49 /// '{' namespace-body '}'
51 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
52 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
54 Decl *Parser::ParseNamespace(unsigned Context,
55 SourceLocation &DeclEnd,
56 SourceLocation InlineLoc) {
57 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
58 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
59 ObjCDeclContextSwitch ObjCDC(*this);
61 if (Tok.is(tok::code_completion)) {
62 Actions.CodeCompleteNamespaceDecl(getCurScope());
67 SourceLocation IdentLoc;
68 IdentifierInfo *Ident = 0;
69 std::vector<SourceLocation> ExtraIdentLoc;
70 std::vector<IdentifierInfo*> ExtraIdent;
71 std::vector<SourceLocation> ExtraNamespaceLoc;
75 if (Tok.is(tok::identifier)) {
76 Ident = Tok.getIdentifierInfo();
77 IdentLoc = ConsumeToken(); // eat the identifier.
78 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
79 ExtraNamespaceLoc.push_back(ConsumeToken());
80 ExtraIdent.push_back(Tok.getIdentifierInfo());
81 ExtraIdentLoc.push_back(ConsumeToken());
85 // Read label attributes, if present.
86 ParsedAttributes attrs(AttrFactory);
87 if (Tok.is(tok::kw___attribute)) {
89 ParseGNUAttributes(attrs);
92 if (Tok.is(tok::equal)) {
94 Diag(Tok, diag::err_expected_ident);
95 // Skip to end of the definition and eat the ';'.
100 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
101 if (InlineLoc.isValid())
102 Diag(InlineLoc, diag::err_inline_namespace_alias)
103 << FixItHint::CreateRemoval(InlineLoc);
104 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
108 BalancedDelimiterTracker T(*this, tok::l_brace);
109 if (T.consumeOpen()) {
110 if (!ExtraIdent.empty()) {
111 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
112 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
114 Diag(Tok, Ident ? diag::err_expected_lbrace :
115 diag::err_expected_ident_lbrace);
119 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
120 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
121 getCurScope()->getFnParent()) {
122 if (!ExtraIdent.empty()) {
123 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
124 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
126 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
127 SkipUntil(tok::r_brace);
131 if (!ExtraIdent.empty()) {
132 TentativeParsingAction TPA(*this);
133 SkipUntil(tok::r_brace, StopBeforeMatch);
134 Token rBraceToken = Tok;
137 if (!rBraceToken.is(tok::r_brace)) {
138 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
139 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
141 std::string NamespaceFix;
142 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
143 E = ExtraIdent.end(); I != E; ++I) {
144 NamespaceFix += " { namespace ";
145 NamespaceFix += (*I)->getName();
149 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
152 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
153 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
154 ExtraIdentLoc.back()),
156 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
160 // If we're still good, complain about inline namespaces in non-C++0x now.
161 if (InlineLoc.isValid())
162 Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
163 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
165 // Enter a scope for the namespace.
166 ParseScope NamespaceScope(this, Scope::DeclScope);
169 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
170 IdentLoc, Ident, T.getOpenLocation(),
173 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
174 "parsing namespace");
176 // Parse the contents of the namespace. This includes parsing recovery on
177 // any improperly nested namespaces.
178 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
179 InlineLoc, attrs, T);
181 // Leave the namespace scope.
182 NamespaceScope.Exit();
184 DeclEnd = T.getCloseLocation();
185 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
190 /// ParseInnerNamespace - Parse the contents of a namespace.
191 void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
192 std::vector<IdentifierInfo*>& Ident,
193 std::vector<SourceLocation>& NamespaceLoc,
194 unsigned int index, SourceLocation& InlineLoc,
195 ParsedAttributes& attrs,
196 BalancedDelimiterTracker &Tracker) {
197 if (index == Ident.size()) {
198 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
199 ParsedAttributesWithRange attrs(AttrFactory);
200 MaybeParseCXX11Attributes(attrs);
201 MaybeParseMicrosoftAttributes(attrs);
202 ParseExternalDeclaration(attrs);
205 // The caller is what called check -- we are simply calling
207 Tracker.consumeClose();
212 // Parse improperly nested namespaces.
213 ParseScope NamespaceScope(this, Scope::DeclScope);
215 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
216 NamespaceLoc[index], IdentLoc[index],
217 Ident[index], Tracker.getOpenLocation(),
220 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
223 NamespaceScope.Exit();
225 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
228 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
229 /// alias definition.
231 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
232 SourceLocation AliasLoc,
233 IdentifierInfo *Alias,
234 SourceLocation &DeclEnd) {
235 assert(Tok.is(tok::equal) && "Not equal token");
237 ConsumeToken(); // eat the '='.
239 if (Tok.is(tok::code_completion)) {
240 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
246 // Parse (optional) nested-name-specifier.
247 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
249 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
250 Diag(Tok, diag::err_expected_namespace_name);
251 // Skip to end of the definition and eat the ';'.
252 SkipUntil(tok::semi);
257 IdentifierInfo *Ident = Tok.getIdentifierInfo();
258 SourceLocation IdentLoc = ConsumeToken();
261 DeclEnd = Tok.getLocation();
262 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
265 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
266 SS, IdentLoc, Ident);
269 /// ParseLinkage - We know that the current token is a string_literal
270 /// and just before that, that extern was seen.
272 /// linkage-specification: [C++ 7.5p2: dcl.link]
273 /// 'extern' string-literal '{' declaration-seq[opt] '}'
274 /// 'extern' string-literal declaration
276 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
277 assert(Tok.is(tok::string_literal) && "Not a string literal!");
278 SmallString<8> LangBuffer;
279 bool Invalid = false;
280 StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid);
284 // FIXME: This is incorrect: linkage-specifiers are parsed in translation
285 // phase 7, so string-literal concatenation is supposed to occur.
286 // extern "" "C" "" "+" "+" { } is legal.
287 if (Tok.hasUDSuffix())
288 Diag(Tok, diag::err_invalid_string_udl);
289 SourceLocation Loc = ConsumeStringToken();
291 ParseScope LinkageScope(this, Scope::DeclScope);
293 = Actions.ActOnStartLinkageSpecification(getCurScope(),
294 DS.getSourceRange().getBegin(),
296 Tok.is(tok::l_brace) ? Tok.getLocation()
299 ParsedAttributesWithRange attrs(AttrFactory);
300 MaybeParseCXX11Attributes(attrs);
301 MaybeParseMicrosoftAttributes(attrs);
303 if (Tok.isNot(tok::l_brace)) {
304 // Reset the source range in DS, as the leading "extern"
305 // does not really belong to the inner declaration ...
306 DS.SetRangeStart(SourceLocation());
307 DS.SetRangeEnd(SourceLocation());
308 // ... but anyway remember that such an "extern" was seen.
309 DS.setExternInLinkageSpec(true);
310 ParseExternalDeclaration(attrs, &DS);
311 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
317 ProhibitAttributes(attrs);
319 BalancedDelimiterTracker T(*this, tok::l_brace);
321 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
322 ParsedAttributesWithRange attrs(AttrFactory);
323 MaybeParseCXX11Attributes(attrs);
324 MaybeParseMicrosoftAttributes(attrs);
325 ParseExternalDeclaration(attrs);
329 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
330 T.getCloseLocation());
333 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
334 /// using-directive. Assumes that current token is 'using'.
335 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
336 const ParsedTemplateInfo &TemplateInfo,
337 SourceLocation &DeclEnd,
338 ParsedAttributesWithRange &attrs,
340 assert(Tok.is(tok::kw_using) && "Not using token");
341 ObjCDeclContextSwitch ObjCDC(*this);
344 SourceLocation UsingLoc = ConsumeToken();
346 if (Tok.is(tok::code_completion)) {
347 Actions.CodeCompleteUsing(getCurScope());
352 // 'using namespace' means this is a using-directive.
353 if (Tok.is(tok::kw_namespace)) {
354 // Template parameters are always an error here.
355 if (TemplateInfo.Kind) {
356 SourceRange R = TemplateInfo.getSourceRange();
357 Diag(UsingLoc, diag::err_templated_using_directive)
358 << R << FixItHint::CreateRemoval(R);
361 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
364 // Otherwise, it must be a using-declaration or an alias-declaration.
366 // Using declarations can't have attributes.
367 ProhibitAttributes(attrs);
369 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
373 /// ParseUsingDirective - Parse C++ using-directive, assumes
374 /// that current token is 'namespace' and 'using' was already parsed.
376 /// using-directive: [C++ 7.3.p4: namespace.udir]
377 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
379 /// [GNU] using-directive:
380 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
381 /// namespace-name attributes[opt] ;
383 Decl *Parser::ParseUsingDirective(unsigned Context,
384 SourceLocation UsingLoc,
385 SourceLocation &DeclEnd,
386 ParsedAttributes &attrs) {
387 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
390 SourceLocation NamespcLoc = ConsumeToken();
392 if (Tok.is(tok::code_completion)) {
393 Actions.CodeCompleteUsingDirective(getCurScope());
399 // Parse (optional) nested-name-specifier.
400 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
402 IdentifierInfo *NamespcName = 0;
403 SourceLocation IdentLoc = SourceLocation();
405 // Parse namespace-name.
406 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
407 Diag(Tok, diag::err_expected_namespace_name);
408 // If there was invalid namespace name, skip to end of decl, and eat ';'.
409 SkipUntil(tok::semi);
410 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
415 NamespcName = Tok.getIdentifierInfo();
416 IdentLoc = ConsumeToken();
418 // Parse (optional) attributes (most likely GNU strong-using extension).
419 bool GNUAttr = false;
420 if (Tok.is(tok::kw___attribute)) {
422 ParseGNUAttributes(attrs);
426 DeclEnd = Tok.getLocation();
427 ExpectAndConsume(tok::semi,
428 GNUAttr ? diag::err_expected_semi_after_attribute_list
429 : diag::err_expected_semi_after_namespace_name,
432 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
433 IdentLoc, NamespcName, attrs.getList());
436 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
437 /// Assumes that 'using' was already seen.
439 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
440 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
442 /// 'using' :: unqualified-id
444 /// alias-declaration: C++11 [dcl.dcl]p1
445 /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
447 Decl *Parser::ParseUsingDeclaration(unsigned Context,
448 const ParsedTemplateInfo &TemplateInfo,
449 SourceLocation UsingLoc,
450 SourceLocation &DeclEnd,
454 SourceLocation TypenameLoc;
455 bool HasTypenameKeyword = false;
457 // Check for misplaced attributes before the identifier in an
458 // alias-declaration.
459 ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
460 MaybeParseCXX11Attributes(MisplacedAttrs);
462 // Ignore optional 'typename'.
463 // FIXME: This is wrong; we should parse this as a typename-specifier.
464 if (Tok.is(tok::kw_typename)) {
465 TypenameLoc = ConsumeToken();
466 HasTypenameKeyword = true;
469 // Parse nested-name-specifier.
470 IdentifierInfo *LastII = 0;
471 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false,
472 /*MayBePseudoDtor=*/0, /*IsTypename=*/false,
475 // Check nested-name specifier.
476 if (SS.isInvalid()) {
477 SkipUntil(tok::semi);
481 SourceLocation TemplateKWLoc;
484 // Parse the unqualified-id. We allow parsing of both constructor and
485 // destructor names and allow the action module to diagnose any semantic
488 // C++11 [class.qual]p2:
489 // [...] in a using-declaration that is a member-declaration, if the name
490 // specified after the nested-name-specifier is the same as the identifier
491 // or the simple-template-id's template-name in the last component of the
492 // nested-name-specifier, the name is [...] considered to name the
494 if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext &&
495 Tok.is(tok::identifier) && NextToken().is(tok::semi) &&
496 SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
497 !SS.getScopeRep()->getAsNamespace() &&
498 !SS.getScopeRep()->getAsNamespaceAlias()) {
499 SourceLocation IdLoc = ConsumeToken();
500 ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII);
501 Name.setConstructorName(Type, IdLoc, IdLoc);
502 } else if (ParseUnqualifiedId(SS, /*EnteringContext=*/ false,
503 /*AllowDestructorName=*/ true,
504 /*AllowConstructorName=*/ true, ParsedType(),
505 TemplateKWLoc, Name)) {
506 SkipUntil(tok::semi);
510 ParsedAttributesWithRange Attrs(AttrFactory);
511 MaybeParseGNUAttributes(Attrs);
512 MaybeParseCXX11Attributes(Attrs);
514 // Maybe this is an alias-declaration.
515 TypeResult TypeAlias;
516 bool IsAliasDecl = Tok.is(tok::equal);
518 // If we had any misplaced attributes from earlier, this is where they
519 // should have been written.
520 if (MisplacedAttrs.Range.isValid()) {
521 Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
522 << FixItHint::CreateInsertionFromRange(
524 CharSourceRange::getTokenRange(MisplacedAttrs.Range))
525 << FixItHint::CreateRemoval(MisplacedAttrs.Range);
526 Attrs.takeAllFrom(MisplacedAttrs);
531 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
532 diag::warn_cxx98_compat_alias_declaration :
533 diag::ext_alias_declaration);
535 // Type alias templates cannot be specialized.
537 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
538 Name.getKind() == UnqualifiedId::IK_TemplateId)
540 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
542 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
544 if (SpecKind != -1) {
547 Range = SourceRange(Name.TemplateId->LAngleLoc,
548 Name.TemplateId->RAngleLoc);
550 Range = TemplateInfo.getSourceRange();
551 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
552 << SpecKind << Range;
553 SkipUntil(tok::semi);
557 // Name must be an identifier.
558 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
559 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
560 // No removal fixit: can't recover from this.
561 SkipUntil(tok::semi);
563 } else if (HasTypenameKeyword)
564 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
565 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
566 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
567 else if (SS.isNotEmpty())
568 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
569 << FixItHint::CreateRemoval(SS.getRange());
571 TypeAlias = ParseTypeName(0, TemplateInfo.Kind ?
572 Declarator::AliasTemplateContext :
573 Declarator::AliasDeclContext, AS, OwnedType,
576 // C++11 attributes are not allowed on a using-declaration, but GNU ones
578 ProhibitAttributes(MisplacedAttrs);
579 ProhibitAttributes(Attrs);
581 // Parse (optional) attributes (most likely GNU strong-using extension).
582 MaybeParseGNUAttributes(Attrs);
586 DeclEnd = Tok.getLocation();
587 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
588 !Attrs.empty() ? "attributes list" :
589 IsAliasDecl ? "alias declaration" : "using declaration",
592 // Diagnose an attempt to declare a templated using-declaration.
593 // In C++11, alias-declarations can be templates:
594 // template <...> using id = type;
595 if (TemplateInfo.Kind && !IsAliasDecl) {
596 SourceRange R = TemplateInfo.getSourceRange();
597 Diag(UsingLoc, diag::err_templated_using_declaration)
598 << R << FixItHint::CreateRemoval(R);
600 // Unfortunately, we have to bail out instead of recovering by
601 // ignoring the parameters, just in case the nested name specifier
602 // depends on the parameters.
606 // "typename" keyword is allowed for identifiers only,
607 // because it may be a type definition.
608 if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) {
609 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
610 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
611 // Proceed parsing, but reset the HasTypenameKeyword flag.
612 HasTypenameKeyword = false;
616 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
617 MultiTemplateParamsArg TemplateParamsArg(
618 TemplateParams ? TemplateParams->data() : 0,
619 TemplateParams ? TemplateParams->size() : 0);
620 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
621 UsingLoc, Name, Attrs.getList(),
625 return Actions.ActOnUsingDeclaration(getCurScope(), AS,
626 /* HasUsingKeyword */ true, UsingLoc,
627 SS, Name, Attrs.getList(),
628 HasTypenameKeyword, TypenameLoc);
631 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
633 /// [C++0x] static_assert-declaration:
634 /// static_assert ( constant-expression , string-literal ) ;
636 /// [C11] static_assert-declaration:
637 /// _Static_assert ( constant-expression , string-literal ) ;
639 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
640 assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) &&
641 "Not a static_assert declaration");
643 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
644 Diag(Tok, diag::ext_c11_static_assert);
645 if (Tok.is(tok::kw_static_assert))
646 Diag(Tok, diag::warn_cxx98_compat_static_assert);
648 SourceLocation StaticAssertLoc = ConsumeToken();
650 BalancedDelimiterTracker T(*this, tok::l_paren);
651 if (T.consumeOpen()) {
652 Diag(Tok, diag::err_expected_lparen);
657 ExprResult AssertExpr(ParseConstantExpression());
658 if (AssertExpr.isInvalid()) {
663 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
666 if (!isTokenStringLiteral()) {
667 Diag(Tok, diag::err_expected_string_literal)
668 << /*Source='static_assert'*/1;
673 ExprResult AssertMessage(ParseStringLiteralExpression());
674 if (AssertMessage.isInvalid()) {
681 DeclEnd = Tok.getLocation();
682 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
684 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
686 AssertMessage.take(),
687 T.getCloseLocation());
690 /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
692 /// 'decltype' ( expression )
693 /// 'decltype' ( 'auto' ) [C++1y]
695 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
696 assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
697 && "Not a decltype specifier");
700 SourceLocation StartLoc = Tok.getLocation();
701 SourceLocation EndLoc;
703 if (Tok.is(tok::annot_decltype)) {
704 Result = getExprAnnotation(Tok);
705 EndLoc = Tok.getAnnotationEndLoc();
707 if (Result.isInvalid()) {
708 DS.SetTypeSpecError();
712 if (Tok.getIdentifierInfo()->isStr("decltype"))
713 Diag(Tok, diag::warn_cxx98_compat_decltype);
717 BalancedDelimiterTracker T(*this, tok::l_paren);
718 if (T.expectAndConsume(diag::err_expected_lparen_after,
719 "decltype", tok::r_paren)) {
720 DS.SetTypeSpecError();
721 return T.getOpenLocation() == Tok.getLocation() ?
722 StartLoc : T.getOpenLocation();
725 // Check for C++1y 'decltype(auto)'.
726 if (Tok.is(tok::kw_auto)) {
727 // No need to disambiguate here: an expression can't start with 'auto',
728 // because the typename-specifier in a function-style cast operation can't
730 Diag(Tok.getLocation(),
731 getLangOpts().CPlusPlus1y
732 ? diag::warn_cxx11_compat_decltype_auto_type_specifier
733 : diag::ext_decltype_auto_type_specifier);
736 // Parse the expression
738 // C++11 [dcl.type.simple]p4:
739 // The operand of the decltype specifier is an unevaluated operand.
740 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
741 0, /*IsDecltype=*/true);
742 Result = ParseExpression();
743 if (Result.isInvalid()) {
744 DS.SetTypeSpecError();
745 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
746 EndLoc = ConsumeParen();
748 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
749 // Backtrack to get the location of the last token before the semi.
750 PP.RevertCachedTokens(2);
751 ConsumeToken(); // the semi.
752 EndLoc = ConsumeAnyToken();
753 assert(Tok.is(tok::semi));
755 EndLoc = Tok.getLocation();
761 Result = Actions.ActOnDecltypeExpression(Result.take());
766 if (T.getCloseLocation().isInvalid()) {
767 DS.SetTypeSpecError();
768 // FIXME: this should return the location of the last token
769 // that was consumed (by "consumeClose()")
770 return T.getCloseLocation();
773 if (Result.isInvalid()) {
774 DS.SetTypeSpecError();
775 return T.getCloseLocation();
778 EndLoc = T.getCloseLocation();
780 assert(!Result.isInvalid());
782 const char *PrevSpec = 0;
784 // Check for duplicate type specifiers (e.g. "int decltype(a)").
786 ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
787 DiagID, Result.release())
788 : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
790 Diag(StartLoc, DiagID) << PrevSpec;
791 DS.SetTypeSpecError();
796 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
797 SourceLocation StartLoc,
798 SourceLocation EndLoc) {
799 // make sure we have a token we can turn into an annotation token
800 if (PP.isBacktrackEnabled())
801 PP.RevertCachedTokens(1);
805 Tok.setKind(tok::annot_decltype);
806 setExprAnnotation(Tok,
807 DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
808 DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
810 Tok.setAnnotationEndLoc(EndLoc);
811 Tok.setLocation(StartLoc);
812 PP.AnnotateCachedTokens(Tok);
815 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
816 assert(Tok.is(tok::kw___underlying_type) &&
817 "Not an underlying type specifier");
819 SourceLocation StartLoc = ConsumeToken();
820 BalancedDelimiterTracker T(*this, tok::l_paren);
821 if (T.expectAndConsume(diag::err_expected_lparen_after,
822 "__underlying_type", tok::r_paren)) {
826 TypeResult Result = ParseTypeName();
827 if (Result.isInvalid()) {
828 SkipUntil(tok::r_paren, StopAtSemi);
834 if (T.getCloseLocation().isInvalid())
837 const char *PrevSpec = 0;
839 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
840 DiagID, Result.release()))
841 Diag(StartLoc, DiagID) << PrevSpec;
842 DS.setTypeofParensRange(T.getRange());
845 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
846 /// class name or decltype-specifier. Note that we only check that the result
847 /// names a type; semantic analysis will need to verify that the type names a
848 /// class. The result is either a type or null, depending on whether a type
851 /// base-type-specifier: [C++11 class.derived]
852 /// class-or-decltype
853 /// class-or-decltype: [C++11 class.derived]
854 /// nested-name-specifier[opt] class-name
855 /// decltype-specifier
856 /// class-name: [C++ class.name]
858 /// simple-template-id
860 /// In C++98, instead of base-type-specifier, we have:
862 /// ::[opt] nested-name-specifier[opt] class-name
863 Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
864 SourceLocation &EndLocation) {
865 // Ignore attempts to use typename
866 if (Tok.is(tok::kw_typename)) {
867 Diag(Tok, diag::err_expected_class_name_not_template)
868 << FixItHint::CreateRemoval(Tok.getLocation());
872 // Parse optional nested-name-specifier
874 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
876 BaseLoc = Tok.getLocation();
878 // Parse decltype-specifier
879 // tok == kw_decltype is just error recovery, it can only happen when SS
881 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
883 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
884 << FixItHint::CreateRemoval(SS.getRange());
885 // Fake up a Declarator to use with ActOnTypeName.
886 DeclSpec DS(AttrFactory);
888 EndLocation = ParseDecltypeSpecifier(DS);
890 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
891 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
894 // Check whether we have a template-id that names a type.
895 if (Tok.is(tok::annot_template_id)) {
896 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
897 if (TemplateId->Kind == TNK_Type_template ||
898 TemplateId->Kind == TNK_Dependent_template_name) {
899 AnnotateTemplateIdTokenAsType();
901 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
902 ParsedType Type = getTypeAnnotation(Tok);
903 EndLocation = Tok.getAnnotationEndLoc();
911 // Fall through to produce an error below.
914 if (Tok.isNot(tok::identifier)) {
915 Diag(Tok, diag::err_expected_class_name);
919 IdentifierInfo *Id = Tok.getIdentifierInfo();
920 SourceLocation IdLoc = ConsumeToken();
922 if (Tok.is(tok::less)) {
923 // It looks the user intended to write a template-id here, but the
924 // template-name was wrong. Try to fix that.
925 TemplateNameKind TNK = TNK_Type_template;
927 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
928 &SS, Template, TNK)) {
929 Diag(IdLoc, diag::err_unknown_template_name)
934 TemplateArgList TemplateArgs;
935 SourceLocation LAngleLoc, RAngleLoc;
936 ParseTemplateIdAfterTemplateName(TemplateTy(), IdLoc, SS,
937 true, LAngleLoc, TemplateArgs, RAngleLoc);
941 // Form the template name
942 UnqualifiedId TemplateName;
943 TemplateName.setIdentifier(Id, IdLoc);
945 // Parse the full template-id, then turn it into a type.
946 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
949 if (TNK == TNK_Dependent_template_name)
950 AnnotateTemplateIdTokenAsType();
952 // If we didn't end up with a typename token, there's nothing more we
954 if (Tok.isNot(tok::annot_typename))
957 // Retrieve the type from the annotation token, consume that token, and
959 EndLocation = Tok.getAnnotationEndLoc();
960 ParsedType Type = getTypeAnnotation(Tok);
965 // We have an identifier; check whether it is actually a type.
966 IdentifierInfo *CorrectedII = 0;
967 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
969 /*IsCtorOrDtorName=*/false,
970 /*NonTrivialTypeSourceInfo=*/true,
973 Diag(IdLoc, diag::err_expected_class_name);
977 // Consume the identifier.
980 // Fake up a Declarator to use with ActOnTypeName.
981 DeclSpec DS(AttrFactory);
982 DS.SetRangeStart(IdLoc);
983 DS.SetRangeEnd(EndLocation);
984 DS.getTypeSpecScope() = SS;
986 const char *PrevSpec = 0;
988 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type);
990 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
991 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
994 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
995 while (Tok.is(tok::kw___single_inheritance) ||
996 Tok.is(tok::kw___multiple_inheritance) ||
997 Tok.is(tok::kw___virtual_inheritance)) {
998 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
999 SourceLocation AttrNameLoc = ConsumeToken();
1000 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, 0,
1001 AttributeList::AS_GNU);
1005 /// Determine whether the following tokens are valid after a type-specifier
1006 /// which could be a standalone declaration. This will conservatively return
1007 /// true if there's any doubt, and is appropriate for insert-';' fixits.
1008 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
1009 // This switch enumerates the valid "follow" set for type-specifiers.
1010 switch (Tok.getKind()) {
1012 case tok::semi: // struct foo {...} ;
1013 case tok::star: // struct foo {...} * P;
1014 case tok::amp: // struct foo {...} & R = ...
1015 case tok::ampamp: // struct foo {...} && R = ...
1016 case tok::identifier: // struct foo {...} V ;
1017 case tok::r_paren: //(struct foo {...} ) {4}
1018 case tok::annot_cxxscope: // struct foo {...} a:: b;
1019 case tok::annot_typename: // struct foo {...} a ::b;
1020 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1021 case tok::l_paren: // struct foo {...} ( x);
1022 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1023 case tok::kw_operator: // struct foo operator ++() {...}
1026 return CouldBeBitfield; // enum E { ... } : 2;
1028 case tok::kw_const: // struct foo {...} const x;
1029 case tok::kw_volatile: // struct foo {...} volatile x;
1030 case tok::kw_restrict: // struct foo {...} restrict x;
1031 // Function specifiers
1032 // Note, no 'explicit'. An explicit function must be either a conversion
1033 // operator or a constructor. Either way, it can't have a return type.
1034 case tok::kw_inline: // struct foo inline f();
1035 case tok::kw_virtual: // struct foo virtual f();
1036 case tok::kw_friend: // struct foo friend f();
1037 // Storage-class specifiers
1038 case tok::kw_static: // struct foo {...} static x;
1039 case tok::kw_extern: // struct foo {...} extern x;
1040 case tok::kw_typedef: // struct foo {...} typedef x;
1041 case tok::kw_register: // struct foo {...} register x;
1042 case tok::kw_auto: // struct foo {...} auto x;
1043 case tok::kw_mutable: // struct foo {...} mutable x;
1044 case tok::kw_thread_local: // struct foo {...} thread_local x;
1045 case tok::kw_constexpr: // struct foo {...} constexpr x;
1046 // As shown above, type qualifiers and storage class specifiers absolutely
1047 // can occur after class specifiers according to the grammar. However,
1048 // almost no one actually writes code like this. If we see one of these,
1049 // it is much more likely that someone missed a semi colon and the
1050 // type/storage class specifier we're seeing is part of the *next*
1051 // intended declaration, as in:
1053 // struct foo { ... }
1056 // We'd really like to emit a missing semicolon error instead of emitting
1057 // an error on the 'int' saying that you can't have two type specifiers in
1058 // the same declaration of X. Because of this, we look ahead past this
1059 // token to see if it's a type specifier. If so, we know the code is
1060 // otherwise invalid, so we can produce the expected semi error.
1061 if (!isKnownToBeTypeSpecifier(NextToken()))
1064 case tok::r_brace: // struct bar { struct foo {...} }
1065 // Missing ';' at end of struct is accepted as an extension in C mode.
1066 if (!getLangOpts().CPlusPlus)
1070 case tok::l_square: // enum E [[]] x
1071 // Note, no tok::kw_alignas here; alignas cannot appertain to a type.
1072 return getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1074 // template<class T = class X>
1075 return getLangOpts().CPlusPlus;
1080 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1081 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1082 /// until we reach the start of a definition or see a token that
1083 /// cannot start a definition.
1085 /// class-specifier: [C++ class]
1086 /// class-head '{' member-specification[opt] '}'
1087 /// class-head '{' member-specification[opt] '}' attributes[opt]
1089 /// class-key identifier[opt] base-clause[opt]
1090 /// class-key nested-name-specifier identifier base-clause[opt]
1091 /// class-key nested-name-specifier[opt] simple-template-id
1092 /// base-clause[opt]
1093 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1094 /// [GNU] class-key attributes[opt] nested-name-specifier
1095 /// identifier base-clause[opt]
1096 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1097 /// simple-template-id base-clause[opt]
1103 /// elaborated-type-specifier: [C++ dcl.type.elab]
1104 /// class-key ::[opt] nested-name-specifier[opt] identifier
1105 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1106 /// simple-template-id
1108 /// Note that the C++ class-specifier and elaborated-type-specifier,
1109 /// together, subsume the C99 struct-or-union-specifier:
1111 /// struct-or-union-specifier: [C99 6.7.2.1]
1112 /// struct-or-union identifier[opt] '{' struct-contents '}'
1113 /// struct-or-union identifier
1114 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1115 /// '}' attributes[opt]
1116 /// [GNU] struct-or-union attributes[opt] identifier
1117 /// struct-or-union:
1120 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1121 SourceLocation StartLoc, DeclSpec &DS,
1122 const ParsedTemplateInfo &TemplateInfo,
1124 bool EnteringContext, DeclSpecContext DSC,
1125 ParsedAttributesWithRange &Attributes) {
1126 DeclSpec::TST TagType;
1127 if (TagTokKind == tok::kw_struct)
1128 TagType = DeclSpec::TST_struct;
1129 else if (TagTokKind == tok::kw___interface)
1130 TagType = DeclSpec::TST_interface;
1131 else if (TagTokKind == tok::kw_class)
1132 TagType = DeclSpec::TST_class;
1134 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1135 TagType = DeclSpec::TST_union;
1138 if (Tok.is(tok::code_completion)) {
1139 // Code completion for a struct, class, or union name.
1140 Actions.CodeCompleteTag(getCurScope(), TagType);
1141 return cutOffParsing();
1144 // C++03 [temp.explicit] 14.7.2/8:
1145 // The usual access checking rules do not apply to names used to specify
1146 // explicit instantiations.
1148 // As an extension we do not perform access checking on the names used to
1149 // specify explicit specializations either. This is important to allow
1150 // specializing traits classes for private types.
1152 // Note that we don't suppress if this turns out to be an elaborated
1154 bool shouldDelayDiagsInTag =
1155 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1156 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1157 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1159 ParsedAttributesWithRange attrs(AttrFactory);
1160 // If attributes exist after tag, parse them.
1161 MaybeParseGNUAttributes(attrs);
1163 // If declspecs exist after tag, parse them.
1164 while (Tok.is(tok::kw___declspec))
1165 ParseMicrosoftDeclSpec(attrs);
1167 // Parse inheritance specifiers.
1168 if (Tok.is(tok::kw___single_inheritance) ||
1169 Tok.is(tok::kw___multiple_inheritance) ||
1170 Tok.is(tok::kw___virtual_inheritance))
1171 ParseMicrosoftInheritanceClassAttributes(attrs);
1173 // If C++0x attributes exist here, parse them.
1174 // FIXME: Are we consistent with the ordering of parsing of different
1175 // styles of attributes?
1176 MaybeParseCXX11Attributes(attrs);
1178 // Source location used by FIXIT to insert misplaced
1180 SourceLocation AttrFixitLoc = Tok.getLocation();
1182 if (TagType == DeclSpec::TST_struct &&
1183 !Tok.is(tok::identifier) &&
1184 Tok.getIdentifierInfo() &&
1185 (Tok.is(tok::kw___is_arithmetic) ||
1186 Tok.is(tok::kw___is_convertible) ||
1187 Tok.is(tok::kw___is_empty) ||
1188 Tok.is(tok::kw___is_floating_point) ||
1189 Tok.is(tok::kw___is_function) ||
1190 Tok.is(tok::kw___is_fundamental) ||
1191 Tok.is(tok::kw___is_integral) ||
1192 Tok.is(tok::kw___is_member_function_pointer) ||
1193 Tok.is(tok::kw___is_member_pointer) ||
1194 Tok.is(tok::kw___is_pod) ||
1195 Tok.is(tok::kw___is_pointer) ||
1196 Tok.is(tok::kw___is_same) ||
1197 Tok.is(tok::kw___is_scalar) ||
1198 Tok.is(tok::kw___is_signed) ||
1199 Tok.is(tok::kw___is_unsigned) ||
1200 Tok.is(tok::kw___is_void)))
1201 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1202 // name of struct templates, but some are keywords in GCC >= 4.3
1203 // and Clang. Therefore, when we see the token sequence "struct
1204 // X", make X into a normal identifier rather than a keyword, to
1205 // allow libstdc++ 4.2 and libc++ to work properly.
1206 TryKeywordIdentFallback(true);
1208 // Parse the (optional) nested-name-specifier.
1209 CXXScopeSpec &SS = DS.getTypeSpecScope();
1210 if (getLangOpts().CPlusPlus) {
1211 // "FOO : BAR" is not a potential typo for "FOO::BAR".
1212 ColonProtectionRAIIObject X(*this);
1214 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1215 DS.SetTypeSpecError();
1217 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
1218 Diag(Tok, diag::err_expected_ident);
1221 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1223 // Parse the (optional) class name or simple-template-id.
1224 IdentifierInfo *Name = 0;
1225 SourceLocation NameLoc;
1226 TemplateIdAnnotation *TemplateId = 0;
1227 if (Tok.is(tok::identifier)) {
1228 Name = Tok.getIdentifierInfo();
1229 NameLoc = ConsumeToken();
1231 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1232 // The name was supposed to refer to a template, but didn't.
1233 // Eat the template argument list and try to continue parsing this as
1234 // a class (or template thereof).
1235 TemplateArgList TemplateArgs;
1236 SourceLocation LAngleLoc, RAngleLoc;
1237 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1239 TemplateArgs, RAngleLoc)) {
1240 // We couldn't parse the template argument list at all, so don't
1241 // try to give any location information for the list.
1242 LAngleLoc = RAngleLoc = SourceLocation();
1245 Diag(NameLoc, diag::err_explicit_spec_non_template)
1246 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1247 << (TagType == DeclSpec::TST_class? 0
1248 : TagType == DeclSpec::TST_struct? 1
1249 : TagType == DeclSpec::TST_union? 2
1252 << SourceRange(LAngleLoc, RAngleLoc);
1254 // Strip off the last template parameter list if it was empty, since
1255 // we've removed its template argument list.
1256 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1257 if (TemplateParams && TemplateParams->size() > 1) {
1258 TemplateParams->pop_back();
1261 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1262 = ParsedTemplateInfo::NonTemplate;
1264 } else if (TemplateInfo.Kind
1265 == ParsedTemplateInfo::ExplicitInstantiation) {
1266 // Pretend this is just a forward declaration.
1268 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1269 = ParsedTemplateInfo::NonTemplate;
1270 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1272 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1276 } else if (Tok.is(tok::annot_template_id)) {
1277 TemplateId = takeTemplateIdAnnotation(Tok);
1278 NameLoc = ConsumeToken();
1280 if (TemplateId->Kind != TNK_Type_template &&
1281 TemplateId->Kind != TNK_Dependent_template_name) {
1282 // The template-name in the simple-template-id refers to
1283 // something other than a class template. Give an appropriate
1284 // error message and skip to the ';'.
1285 SourceRange Range(NameLoc);
1286 if (SS.isNotEmpty())
1287 Range.setBegin(SS.getBeginLoc());
1289 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1290 << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
1292 DS.SetTypeSpecError();
1293 SkipUntil(tok::semi, StopBeforeMatch);
1298 // There are four options here.
1299 // - If we are in a trailing return type, this is always just a reference,
1300 // and we must not try to parse a definition. For instance,
1301 // [] () -> struct S { };
1302 // does not define a type.
1303 // - If we have 'struct foo {...', 'struct foo :...',
1304 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1305 // - If we have 'struct foo;', then this is either a forward declaration
1306 // or a friend declaration, which have to be treated differently.
1307 // - Otherwise we have something like 'struct foo xyz', a reference.
1309 // We also detect these erroneous cases to provide better diagnostic for
1310 // C++11 attributes parsing.
1311 // - attributes follow class name:
1312 // struct foo [[]] {};
1313 // - attributes appear before or after 'final':
1314 // struct foo [[]] final [[]] {};
1316 // However, in type-specifier-seq's, things look like declarations but are
1317 // just references, e.g.
1320 // &T::operator struct s;
1321 // For these, DSC is DSC_type_specifier.
1323 // If there are attributes after class name, parse them.
1324 MaybeParseCXX11Attributes(Attributes);
1326 Sema::TagUseKind TUK;
1327 if (DSC == DSC_trailing)
1328 TUK = Sema::TUK_Reference;
1329 else if (Tok.is(tok::l_brace) ||
1330 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1331 (isCXX11FinalKeyword() &&
1332 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1333 if (DS.isFriendSpecified()) {
1334 // C++ [class.friend]p2:
1335 // A class shall not be defined in a friend declaration.
1336 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1337 << SourceRange(DS.getFriendSpecLoc());
1339 // Skip everything up to the semicolon, so that this looks like a proper
1340 // friend class (or template thereof) declaration.
1341 SkipUntil(tok::semi, StopBeforeMatch);
1342 TUK = Sema::TUK_Friend;
1344 // Okay, this is a class definition.
1345 TUK = Sema::TUK_Definition;
1347 } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
1348 NextToken().is(tok::kw_alignas))) {
1349 // We can't tell if this is a definition or reference
1350 // until we skipped the 'final' and C++11 attribute specifiers.
1351 TentativeParsingAction PA(*this);
1353 // Skip the 'final' keyword.
1356 // Skip C++11 attribute specifiers.
1358 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1360 if (!SkipUntil(tok::r_square, StopAtSemi))
1362 } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
1365 if (!SkipUntil(tok::r_paren, StopAtSemi))
1372 if (Tok.is(tok::l_brace) || Tok.is(tok::colon))
1373 TUK = Sema::TUK_Definition;
1375 TUK = Sema::TUK_Reference;
1378 } else if (DSC != DSC_type_specifier &&
1379 (Tok.is(tok::semi) ||
1380 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1381 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1382 if (Tok.isNot(tok::semi)) {
1383 // A semicolon was missing after this declaration. Diagnose and recover.
1384 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1385 DeclSpec::getSpecifierName(TagType));
1387 Tok.setKind(tok::semi);
1390 TUK = Sema::TUK_Reference;
1392 // Forbid misplaced attributes. In cases of a reference, we pass attributes
1393 // to caller to handle.
1394 if (TUK != Sema::TUK_Reference) {
1395 // If this is not a reference, then the only possible
1396 // valid place for C++11 attributes to appear here
1397 // is between class-key and class-name. If there are
1398 // any attributes after class-name, we try a fixit to move
1399 // them to the right place.
1400 SourceRange AttrRange = Attributes.Range;
1401 if (AttrRange.isValid()) {
1402 Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
1404 << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
1405 CharSourceRange(AttrRange, true))
1406 << FixItHint::CreateRemoval(AttrRange);
1408 // Recover by adding misplaced attributes to the attribute list
1409 // of the class so they can be applied on the class later.
1410 attrs.takeAllFrom(Attributes);
1414 // If this is an elaborated type specifier, and we delayed
1415 // diagnostics before, just merge them into the current pool.
1416 if (shouldDelayDiagsInTag) {
1417 diagsFromTag.done();
1418 if (TUK == Sema::TUK_Reference)
1419 diagsFromTag.redelay();
1422 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1423 TUK != Sema::TUK_Definition)) {
1424 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1425 // We have a declaration or reference to an anonymous class.
1426 Diag(StartLoc, diag::err_anon_type_definition)
1427 << DeclSpec::getSpecifierName(TagType);
1430 // If we are parsing a definition and stop at a base-clause, continue on
1431 // until the semicolon. Continuing from the comma will just trick us into
1432 // thinking we are seeing a variable declaration.
1433 if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
1434 SkipUntil(tok::semi, StopBeforeMatch);
1436 SkipUntil(tok::comma, StopAtSemi);
1440 // Create the tag portion of the class or class template.
1441 DeclResult TagOrTempResult = true; // invalid
1442 TypeResult TypeResult = true; // invalid
1446 // Explicit specialization, class template partial specialization,
1447 // or explicit instantiation.
1448 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1449 TemplateId->NumArgs);
1450 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1451 TUK == Sema::TUK_Declaration) {
1452 // This is an explicit instantiation of a class template.
1453 ProhibitAttributes(attrs);
1456 = Actions.ActOnExplicitInstantiation(getCurScope(),
1457 TemplateInfo.ExternLoc,
1458 TemplateInfo.TemplateLoc,
1462 TemplateId->Template,
1463 TemplateId->TemplateNameLoc,
1464 TemplateId->LAngleLoc,
1466 TemplateId->RAngleLoc,
1469 // Friend template-ids are treated as references unless
1470 // they have template headers, in which case they're ill-formed
1471 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1472 // We diagnose this error in ActOnClassTemplateSpecialization.
1473 } else if (TUK == Sema::TUK_Reference ||
1474 (TUK == Sema::TUK_Friend &&
1475 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1476 ProhibitAttributes(attrs);
1477 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1479 TemplateId->TemplateKWLoc,
1480 TemplateId->Template,
1481 TemplateId->TemplateNameLoc,
1482 TemplateId->LAngleLoc,
1484 TemplateId->RAngleLoc);
1486 // This is an explicit specialization or a class template
1487 // partial specialization.
1488 TemplateParameterLists FakedParamLists;
1489 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1490 // This looks like an explicit instantiation, because we have
1493 // template class Foo<X>
1495 // but it actually has a definition. Most likely, this was
1496 // meant to be an explicit specialization, but the user forgot
1497 // the '<>' after 'template'.
1498 // It this is friend declaration however, since it cannot have a
1499 // template header, it is most likely that the user meant to
1500 // remove the 'template' keyword.
1501 assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
1502 "Expected a definition here");
1504 if (TUK == Sema::TUK_Friend) {
1505 Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
1508 SourceLocation LAngleLoc =
1509 PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1510 Diag(TemplateId->TemplateNameLoc,
1511 diag::err_explicit_instantiation_with_definition)
1512 << SourceRange(TemplateInfo.TemplateLoc)
1513 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1515 // Create a fake template parameter list that contains only
1516 // "template<>", so that we treat this construct as a class
1517 // template specialization.
1518 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
1519 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, 0, 0,
1521 TemplateParams = &FakedParamLists;
1525 // Build the class template specialization.
1527 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK,
1528 StartLoc, DS.getModulePrivateSpecLoc(), SS,
1529 TemplateId->Template,
1530 TemplateId->TemplateNameLoc,
1531 TemplateId->LAngleLoc,
1533 TemplateId->RAngleLoc,
1535 MultiTemplateParamsArg(
1536 TemplateParams? &(*TemplateParams)[0] : 0,
1537 TemplateParams? TemplateParams->size() : 0));
1539 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1540 TUK == Sema::TUK_Declaration) {
1541 // Explicit instantiation of a member of a class template
1542 // specialization, e.g.,
1544 // template struct Outer<int>::Inner;
1546 ProhibitAttributes(attrs);
1549 = Actions.ActOnExplicitInstantiation(getCurScope(),
1550 TemplateInfo.ExternLoc,
1551 TemplateInfo.TemplateLoc,
1552 TagType, StartLoc, SS, Name,
1553 NameLoc, attrs.getList());
1554 } else if (TUK == Sema::TUK_Friend &&
1555 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1556 ProhibitAttributes(attrs);
1559 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1560 TagType, StartLoc, SS,
1561 Name, NameLoc, attrs.getList(),
1562 MultiTemplateParamsArg(
1563 TemplateParams? &(*TemplateParams)[0] : 0,
1564 TemplateParams? TemplateParams->size() : 0));
1566 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1567 ProhibitAttributes(attrs);
1569 if (TUK == Sema::TUK_Definition &&
1570 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1571 // If the declarator-id is not a template-id, issue a diagnostic and
1572 // recover by ignoring the 'template' keyword.
1573 Diag(Tok, diag::err_template_defn_explicit_instantiation)
1574 << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
1578 bool IsDependent = false;
1580 // Don't pass down template parameter lists if this is just a tag
1581 // reference. For example, we don't need the template parameters here:
1582 // template <class T> class A *makeA(T t);
1583 MultiTemplateParamsArg TParams;
1584 if (TUK != Sema::TUK_Reference && TemplateParams)
1586 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1588 // Declaration or definition of a class type
1589 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1590 SS, Name, NameLoc, attrs.getList(), AS,
1591 DS.getModulePrivateSpecLoc(),
1592 TParams, Owned, IsDependent,
1593 SourceLocation(), false,
1594 clang::TypeResult());
1596 // If ActOnTag said the type was dependent, try again with the
1597 // less common call.
1599 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1600 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1601 SS, Name, StartLoc, NameLoc);
1605 // If there is a body, parse it and inform the actions module.
1606 if (TUK == Sema::TUK_Definition) {
1607 assert(Tok.is(tok::l_brace) ||
1608 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1609 isCXX11FinalKeyword());
1610 if (getLangOpts().CPlusPlus)
1611 ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
1612 TagOrTempResult.get());
1614 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1617 const char *PrevSpec = 0;
1620 if (!TypeResult.isInvalid()) {
1621 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1622 NameLoc.isValid() ? NameLoc : StartLoc,
1623 PrevSpec, DiagID, TypeResult.get());
1624 } else if (!TagOrTempResult.isInvalid()) {
1625 Result = DS.SetTypeSpecType(TagType, StartLoc,
1626 NameLoc.isValid() ? NameLoc : StartLoc,
1627 PrevSpec, DiagID, TagOrTempResult.get(), Owned);
1629 DS.SetTypeSpecError();
1634 Diag(StartLoc, DiagID) << PrevSpec;
1636 // At this point, we've successfully parsed a class-specifier in 'definition'
1637 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1638 // going to look at what comes after it to improve error recovery. If an
1639 // impossible token occurs next, we assume that the programmer forgot a ; at
1640 // the end of the declaration and recover that way.
1642 // Also enforce C++ [temp]p3:
1643 // In a template-declaration which defines a class, no declarator
1645 if (TUK == Sema::TUK_Definition &&
1646 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1647 if (Tok.isNot(tok::semi)) {
1648 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1649 DeclSpec::getSpecifierName(TagType));
1650 // Push this token back into the preprocessor and change our current token
1651 // to ';' so that the rest of the code recovers as though there were an
1652 // ';' after the definition.
1654 Tok.setKind(tok::semi);
1659 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1661 /// base-clause : [C++ class.derived]
1662 /// ':' base-specifier-list
1663 /// base-specifier-list:
1664 /// base-specifier '...'[opt]
1665 /// base-specifier-list ',' base-specifier '...'[opt]
1666 void Parser::ParseBaseClause(Decl *ClassDecl) {
1667 assert(Tok.is(tok::colon) && "Not a base clause");
1670 // Build up an array of parsed base specifiers.
1671 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1674 // Parse a base-specifier.
1675 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1676 if (Result.isInvalid()) {
1677 // Skip the rest of this base specifier, up until the comma or
1679 SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
1681 // Add this to our array of base specifiers.
1682 BaseInfo.push_back(Result.get());
1685 // If the next token is a comma, consume it and keep reading
1687 if (Tok.isNot(tok::comma)) break;
1689 // Consume the comma.
1693 // Attach the base specifiers
1694 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1697 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1698 /// one entry in the base class list of a class specifier, for example:
1699 /// class foo : public bar, virtual private baz {
1700 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1702 /// base-specifier: [C++ class.derived]
1703 /// attribute-specifier-seq[opt] base-type-specifier
1704 /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
1705 /// base-type-specifier
1706 /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
1707 /// base-type-specifier
1708 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1709 bool IsVirtual = false;
1710 SourceLocation StartLoc = Tok.getLocation();
1712 ParsedAttributesWithRange Attributes(AttrFactory);
1713 MaybeParseCXX11Attributes(Attributes);
1715 // Parse the 'virtual' keyword.
1716 if (Tok.is(tok::kw_virtual)) {
1721 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1723 // Parse an (optional) access specifier.
1724 AccessSpecifier Access = getAccessSpecifierIfPresent();
1725 if (Access != AS_none)
1728 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1730 // Parse the 'virtual' keyword (again!), in case it came after the
1731 // access specifier.
1732 if (Tok.is(tok::kw_virtual)) {
1733 SourceLocation VirtualLoc = ConsumeToken();
1735 // Complain about duplicate 'virtual'
1736 Diag(VirtualLoc, diag::err_dup_virtual)
1737 << FixItHint::CreateRemoval(VirtualLoc);
1743 CheckMisplacedCXX11Attribute(Attributes, StartLoc);
1745 // Parse the class-name.
1746 SourceLocation EndLocation;
1747 SourceLocation BaseLoc;
1748 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1749 if (BaseType.isInvalid())
1752 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1753 // actually part of the base-specifier-list grammar productions, but we
1754 // parse it here for convenience.
1755 SourceLocation EllipsisLoc;
1756 if (Tok.is(tok::ellipsis))
1757 EllipsisLoc = ConsumeToken();
1759 // Find the complete source range for the base-specifier.
1760 SourceRange Range(StartLoc, EndLocation);
1762 // Notify semantic analysis that we have parsed a complete
1764 return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
1765 Access, BaseType.get(), BaseLoc,
1769 /// getAccessSpecifierIfPresent - Determine whether the next token is
1770 /// a C++ access-specifier.
1772 /// access-specifier: [C++ class.derived]
1776 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1777 switch (Tok.getKind()) {
1778 default: return AS_none;
1779 case tok::kw_private: return AS_private;
1780 case tok::kw_protected: return AS_protected;
1781 case tok::kw_public: return AS_public;
1785 /// \brief If the given declarator has any parts for which parsing has to be
1786 /// delayed, e.g., default arguments, create a late-parsed method declaration
1787 /// record to handle the parsing at the end of the class definition.
1788 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1790 // We just declared a member function. If this member function
1791 // has any default arguments, we'll need to parse them later.
1792 LateParsedMethodDeclaration *LateMethod = 0;
1793 DeclaratorChunk::FunctionTypeInfo &FTI
1794 = DeclaratorInfo.getFunctionTypeInfo();
1796 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1797 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1799 // Push this method onto the stack of late-parsed method
1801 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1802 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1803 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1805 // Add all of the parameters prior to this one (they don't
1806 // have default arguments).
1807 LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1808 for (unsigned I = 0; I < ParamIdx; ++I)
1809 LateMethod->DefaultArgs.push_back(
1810 LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
1813 // Add this parameter to the list of parameters (it may or may
1814 // not have a default argument).
1815 LateMethod->DefaultArgs.push_back(
1816 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1817 FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1822 /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
1828 VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
1829 if (!getLangOpts().CPlusPlus)
1830 return VirtSpecifiers::VS_None;
1832 if (Tok.is(tok::identifier)) {
1833 IdentifierInfo *II = Tok.getIdentifierInfo();
1835 // Initialize the contextual keywords.
1837 Ident_final = &PP.getIdentifierTable().get("final");
1838 if (getLangOpts().MicrosoftExt)
1839 Ident_sealed = &PP.getIdentifierTable().get("sealed");
1840 Ident_override = &PP.getIdentifierTable().get("override");
1843 if (II == Ident_override)
1844 return VirtSpecifiers::VS_Override;
1846 if (II == Ident_sealed)
1847 return VirtSpecifiers::VS_Sealed;
1849 if (II == Ident_final)
1850 return VirtSpecifiers::VS_Final;
1853 return VirtSpecifiers::VS_None;
1856 /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
1858 /// virt-specifier-seq:
1860 /// virt-specifier-seq virt-specifier
1861 void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
1864 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
1865 if (Specifier == VirtSpecifiers::VS_None)
1868 // C++ [class.mem]p8:
1869 // A virt-specifier-seq shall contain at most one of each virt-specifier.
1870 const char *PrevSpec = 0;
1871 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
1872 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
1874 << FixItHint::CreateRemoval(Tok.getLocation());
1876 if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
1877 Specifier == VirtSpecifiers::VS_Sealed)) {
1878 Diag(Tok.getLocation(), diag::err_override_control_interface)
1879 << VirtSpecifiers::getSpecifierName(Specifier);
1880 } else if (Specifier == VirtSpecifiers::VS_Sealed) {
1881 Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
1883 Diag(Tok.getLocation(),
1884 getLangOpts().CPlusPlus11
1885 ? diag::warn_cxx98_compat_override_control_keyword
1886 : diag::ext_override_control_keyword)
1887 << VirtSpecifiers::getSpecifierName(Specifier);
1893 /// isCXX11FinalKeyword - Determine whether the next token is a C++11
1894 /// contextual 'final' keyword.
1895 bool Parser::isCXX11FinalKeyword() const {
1896 if (!getLangOpts().CPlusPlus)
1899 if (!Tok.is(tok::identifier))
1902 // Initialize the contextual keywords.
1904 Ident_final = &PP.getIdentifierTable().get("final");
1905 if (getLangOpts().MicrosoftExt)
1906 Ident_sealed = &PP.getIdentifierTable().get("sealed");
1907 Ident_override = &PP.getIdentifierTable().get("override");
1910 return Tok.getIdentifierInfo() == Ident_final ||
1911 Tok.getIdentifierInfo() == Ident_sealed;
1914 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1916 /// member-declaration:
1917 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
1918 /// function-definition ';'[opt]
1919 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1920 /// using-declaration [TODO]
1921 /// [C++0x] static_assert-declaration
1922 /// template-declaration
1923 /// [GNU] '__extension__' member-declaration
1925 /// member-declarator-list:
1926 /// member-declarator
1927 /// member-declarator-list ',' member-declarator
1929 /// member-declarator:
1930 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
1931 /// declarator constant-initializer[opt]
1932 /// [C++11] declarator brace-or-equal-initializer[opt]
1933 /// identifier[opt] ':' constant-expression
1935 /// virt-specifier-seq:
1937 /// virt-specifier-seq virt-specifier
1947 /// constant-initializer:
1948 /// '=' constant-expression
1950 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1951 AttributeList *AccessAttrs,
1952 const ParsedTemplateInfo &TemplateInfo,
1953 ParsingDeclRAIIObject *TemplateDiags) {
1954 if (Tok.is(tok::at)) {
1955 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
1956 Diag(Tok, diag::err_at_defs_cxx);
1958 Diag(Tok, diag::err_at_in_class);
1961 SkipUntil(tok::r_brace, StopAtSemi);
1965 // Access declarations.
1966 bool MalformedTypeSpec = false;
1967 if (!TemplateInfo.Kind &&
1968 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) {
1969 if (TryAnnotateCXXScopeToken())
1970 MalformedTypeSpec = true;
1973 if (Tok.isNot(tok::annot_cxxscope))
1974 isAccessDecl = false;
1975 else if (NextToken().is(tok::identifier))
1976 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
1978 isAccessDecl = NextToken().is(tok::kw_operator);
1981 // Collect the scope specifier token we annotated earlier.
1983 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1984 /*EnteringContext=*/false);
1986 // Try to parse an unqualified-id.
1987 SourceLocation TemplateKWLoc;
1989 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
1990 TemplateKWLoc, Name)) {
1991 SkipUntil(tok::semi);
1995 // TODO: recover from mistakenly-qualified operator declarations.
1996 if (ExpectAndConsume(tok::semi,
1997 diag::err_expected_semi_after,
1998 "access declaration",
2002 Actions.ActOnUsingDeclaration(getCurScope(), AS,
2003 /* HasUsingKeyword */ false,
2007 /* HasTypenameKeyword */ false,
2013 // static_assert-declaration
2014 if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) {
2015 // FIXME: Check for templates
2016 SourceLocation DeclEnd;
2017 ParseStaticAssertDeclaration(DeclEnd);
2021 if (Tok.is(tok::kw_template)) {
2022 assert(!TemplateInfo.TemplateParams &&
2023 "Nested template improperly parsed?");
2024 SourceLocation DeclEnd;
2025 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
2030 // Handle: member-declaration ::= '__extension__' member-declaration
2031 if (Tok.is(tok::kw___extension__)) {
2032 // __extension__ silences extension warnings in the subexpression.
2033 ExtensionRAIIObject O(Diags); // Use RAII to do this.
2035 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
2036 TemplateInfo, TemplateDiags);
2039 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
2041 ColonProtectionRAIIObject X(*this);
2043 ParsedAttributesWithRange attrs(AttrFactory);
2044 ParsedAttributesWithRange FnAttrs(AttrFactory);
2045 // Optional C++11 attribute-specifier
2046 MaybeParseCXX11Attributes(attrs);
2047 // We need to keep these attributes for future diagnostic
2048 // before they are taken over by declaration specifier.
2049 FnAttrs.addAll(attrs.getList());
2050 FnAttrs.Range = attrs.Range;
2052 MaybeParseMicrosoftAttributes(attrs);
2054 if (Tok.is(tok::kw_using)) {
2055 ProhibitAttributes(attrs);
2058 SourceLocation UsingLoc = ConsumeToken();
2060 if (Tok.is(tok::kw_namespace)) {
2061 Diag(UsingLoc, diag::err_using_namespace_in_class);
2062 SkipUntil(tok::semi, StopBeforeMatch);
2064 SourceLocation DeclEnd;
2065 // Otherwise, it must be a using-declaration or an alias-declaration.
2066 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
2067 UsingLoc, DeclEnd, AS);
2072 // Hold late-parsed attributes so we can attach a Decl to them later.
2073 LateParsedAttrList CommonLateParsedAttrs;
2075 // decl-specifier-seq:
2076 // Parse the common declaration-specifiers piece.
2077 ParsingDeclSpec DS(*this, TemplateDiags);
2078 DS.takeAttributesFrom(attrs);
2079 if (MalformedTypeSpec)
2080 DS.SetTypeSpecError();
2081 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
2082 &CommonLateParsedAttrs);
2084 // If we had a free-standing type definition with a missing semicolon, we
2085 // may get this far before the problem becomes obvious.
2086 if (DS.hasTagDefinition() &&
2087 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
2088 DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class,
2089 &CommonLateParsedAttrs))
2092 MultiTemplateParamsArg TemplateParams(
2093 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
2094 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
2096 if (Tok.is(tok::semi)) {
2099 if (DS.isFriendSpecified())
2100 ProhibitAttributes(FnAttrs);
2103 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
2104 DS.complete(TheDecl);
2108 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
2111 // Hold late-parsed attributes so we can attach a Decl to them later.
2112 LateParsedAttrList LateParsedAttrs;
2114 SourceLocation EqualLoc;
2115 bool HasInitializer = false;
2117 if (Tok.isNot(tok::colon)) {
2118 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2119 ColonProtectionRAIIObject X(*this);
2121 // Parse the first declarator.
2122 ParseDeclarator(DeclaratorInfo);
2123 // Error parsing the declarator?
2124 if (!DeclaratorInfo.hasName()) {
2125 // If so, skip until the semi-colon or a }.
2126 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2127 if (Tok.is(tok::semi))
2132 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface);
2134 // If attributes exist after the declarator, but before an '{', parse them.
2135 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2137 // MSVC permits pure specifier on inline functions declared at class scope.
2138 // Hence check for =0 before checking for function definition.
2139 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
2140 DeclaratorInfo.isFunctionDeclarator() &&
2141 NextToken().is(tok::numeric_constant)) {
2142 EqualLoc = ConsumeToken();
2143 Init = ParseInitializer();
2144 if (Init.isInvalid())
2145 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2147 HasInitializer = true;
2150 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
2151 // function-definition:
2153 // In C++11, a non-function declarator followed by an open brace is a
2154 // braced-init-list for an in-class member initialization, not an
2155 // erroneous function definition.
2156 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
2157 DefinitionKind = FDK_Definition;
2158 } else if (DeclaratorInfo.isFunctionDeclarator()) {
2159 if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
2160 DefinitionKind = FDK_Definition;
2161 } else if (Tok.is(tok::equal)) {
2162 const Token &KW = NextToken();
2163 if (KW.is(tok::kw_default))
2164 DefinitionKind = FDK_Defaulted;
2165 else if (KW.is(tok::kw_delete))
2166 DefinitionKind = FDK_Deleted;
2170 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2171 // to a friend declaration, that declaration shall be a definition.
2172 if (DeclaratorInfo.isFunctionDeclarator() &&
2173 DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
2174 // Diagnose attributes that appear before decl specifier:
2175 // [[]] friend int foo();
2176 ProhibitAttributes(FnAttrs);
2179 if (DefinitionKind) {
2180 if (!DeclaratorInfo.isFunctionDeclarator()) {
2181 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
2183 SkipUntil(tok::r_brace);
2185 // Consume the optional ';'
2186 if (Tok.is(tok::semi))
2191 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2192 Diag(DeclaratorInfo.getIdentifierLoc(),
2193 diag::err_function_declared_typedef);
2195 // Recover by treating the 'typedef' as spurious.
2196 DS.ClearStorageClassSpecs();
2200 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2201 VS, DefinitionKind, Init);
2204 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2205 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2207 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2208 LateParsedAttrs[i]->addDecl(FunDecl);
2211 LateParsedAttrs.clear();
2213 // Consume the ';' - it's optional unless we have a delete or default
2214 if (Tok.is(tok::semi))
2215 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2221 // member-declarator-list:
2222 // member-declarator
2223 // member-declarator-list ',' member-declarator
2225 SmallVector<Decl *, 8> DeclsInGroup;
2226 ExprResult BitfieldSize;
2227 bool ExpectSemi = true;
2230 // member-declarator:
2231 // declarator pure-specifier[opt]
2232 // declarator brace-or-equal-initializer[opt]
2233 // identifier[opt] ':' constant-expression
2234 if (Tok.is(tok::colon)) {
2236 BitfieldSize = ParseConstantExpression();
2237 if (BitfieldSize.isInvalid())
2238 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2241 // If a simple-asm-expr is present, parse it.
2242 if (Tok.is(tok::kw_asm)) {
2244 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2245 if (AsmLabel.isInvalid())
2246 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2248 DeclaratorInfo.setAsmLabel(AsmLabel.release());
2249 DeclaratorInfo.SetRangeEnd(Loc);
2252 // If attributes exist after the declarator, parse them.
2253 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2255 // FIXME: When g++ adds support for this, we'll need to check whether it
2256 // goes before or after the GNU attributes and __asm__.
2257 ParseOptionalCXX11VirtSpecifierSeq(VS, getCurrentClass().IsInterface);
2259 InClassInitStyle HasInClassInit = ICIS_NoInit;
2260 if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
2261 if (BitfieldSize.get()) {
2262 Diag(Tok, diag::err_bitfield_member_init);
2263 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2265 HasInitializer = true;
2266 if (!DeclaratorInfo.isDeclarationOfFunction() &&
2267 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2268 != DeclSpec::SCS_typedef)
2269 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2273 // NOTE: If Sema is the Action module and declarator is an instance field,
2274 // this call will *not* return the created decl; It will return null.
2275 // See Sema::ActOnCXXMemberDeclarator for details.
2277 NamedDecl *ThisDecl = 0;
2278 if (DS.isFriendSpecified()) {
2279 // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
2280 // to a friend declaration, that declaration shall be a definition.
2282 // Diagnose attributes appear after friend member function declarator:
2284 SmallVector<SourceRange, 4> Ranges;
2285 DeclaratorInfo.getCXX11AttributeRanges(Ranges);
2286 if (!Ranges.empty()) {
2287 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
2288 E = Ranges.end(); I != E; ++I) {
2289 Diag((*I).getBegin(), diag::err_attributes_not_allowed)
2294 // TODO: handle initializers, bitfields, 'delete'
2295 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2298 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2301 BitfieldSize.release(),
2302 VS, HasInClassInit);
2304 if (VarTemplateDecl *VT =
2305 ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : 0)
2306 // Re-direct this decl to refer to the templated decl so that we can
2308 ThisDecl = VT->getTemplatedDecl();
2310 if (ThisDecl && AccessAttrs)
2311 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
2314 // Handle the initializer.
2315 if (HasInClassInit != ICIS_NoInit &&
2316 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2317 DeclSpec::SCS_static) {
2318 // The initializer was deferred; parse it and cache the tokens.
2319 Diag(Tok, getLangOpts().CPlusPlus11
2320 ? diag::warn_cxx98_compat_nonstatic_member_init
2321 : diag::ext_nonstatic_member_init);
2323 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2324 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2325 // declarator is followed by an initializer.
2327 // A brace-or-equal-initializer for a member-declarator is not an
2328 // initializer in the grammar, so this is ill-formed.
2329 Diag(Tok, diag::err_incomplete_array_member_init);
2330 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2332 // Avoid later warnings about a class member of incomplete type.
2334 ThisDecl->setInvalidDecl();
2336 ParseCXXNonStaticMemberInitializer(ThisDecl);
2337 } else if (HasInitializer) {
2338 // Normal initializer.
2339 if (!Init.isUsable())
2340 Init = ParseCXXMemberInitializer(
2341 ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2343 if (Init.isInvalid())
2344 SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
2346 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2347 DS.containsPlaceholderType());
2348 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
2350 Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType());
2353 if (!ThisDecl->isInvalidDecl()) {
2354 // Set the Decl for any late parsed attributes
2355 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
2356 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2358 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
2359 LateParsedAttrs[i]->addDecl(ThisDecl);
2361 Actions.FinalizeDeclaration(ThisDecl);
2362 DeclsInGroup.push_back(ThisDecl);
2364 if (DeclaratorInfo.isFunctionDeclarator() &&
2365 DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
2366 DeclSpec::SCS_typedef)
2367 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2369 LateParsedAttrs.clear();
2371 DeclaratorInfo.complete(ThisDecl);
2373 // If we don't have a comma, it is either the end of the list (a ';')
2374 // or an error, bail out.
2375 if (Tok.isNot(tok::comma))
2378 // Consume the comma.
2379 SourceLocation CommaLoc = ConsumeToken();
2381 if (Tok.isAtStartOfLine() &&
2382 !MightBeDeclarator(Declarator::MemberContext)) {
2383 // This comma was followed by a line-break and something which can't be
2384 // the start of a declarator. The comma was probably a typo for a
2386 Diag(CommaLoc, diag::err_expected_semi_declaration)
2387 << FixItHint::CreateReplacement(CommaLoc, ";");
2392 // Parse the next declarator.
2393 DeclaratorInfo.clear();
2395 BitfieldSize = true;
2397 HasInitializer = false;
2398 DeclaratorInfo.setCommaLoc(CommaLoc);
2400 // Attributes are only allowed on the second declarator.
2401 MaybeParseGNUAttributes(DeclaratorInfo);
2403 if (Tok.isNot(tok::colon))
2404 ParseDeclarator(DeclaratorInfo);
2408 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2409 // Skip to end of block or statement.
2410 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2411 // If we stopped at a ';', eat it.
2412 if (Tok.is(tok::semi)) ConsumeToken();
2416 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2419 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
2420 /// pure-specifier. Also detect and reject any attempted defaulted/deleted
2421 /// function definition. The location of the '=', if any, will be placed in
2427 /// brace-or-equal-initializer:
2428 /// '=' initializer-expression
2429 /// braced-init-list
2431 /// initializer-clause:
2432 /// assignment-expression
2433 /// braced-init-list
2435 /// defaulted/deleted function-definition:
2439 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2440 /// be a constant-expression.
2441 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2442 SourceLocation &EqualLoc) {
2443 assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
2444 && "Data member initializer not starting with '=' or '{'");
2446 EnterExpressionEvaluationContext Context(Actions,
2447 Sema::PotentiallyEvaluated,
2449 if (Tok.is(tok::equal)) {
2450 EqualLoc = ConsumeToken();
2451 if (Tok.is(tok::kw_delete)) {
2452 // In principle, an initializer of '= delete p;' is legal, but it will
2453 // never type-check. It's better to diagnose it as an ill-formed expression
2454 // than as an ill-formed deleted non-function member.
2455 // An initializer of '= delete p, foo' will never be parsed, because
2456 // a top-level comma always ends the initializer expression.
2457 const Token &Next = NextToken();
2458 if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) ||
2459 Next.is(tok::eof)) {
2461 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2464 Diag(ConsumeToken(), diag::err_deleted_non_function);
2465 return ExprResult();
2467 } else if (Tok.is(tok::kw_default)) {
2469 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2472 Diag(ConsumeToken(), diag::err_default_special_members);
2473 return ExprResult();
2477 return ParseInitializer();
2480 /// ParseCXXMemberSpecification - Parse the class definition.
2482 /// member-specification:
2483 /// member-declaration member-specification[opt]
2484 /// access-specifier ':' member-specification[opt]
2486 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2487 SourceLocation AttrFixitLoc,
2488 ParsedAttributesWithRange &Attrs,
2489 unsigned TagType, Decl *TagDecl) {
2490 assert((TagType == DeclSpec::TST_struct ||
2491 TagType == DeclSpec::TST_interface ||
2492 TagType == DeclSpec::TST_union ||
2493 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2495 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2496 "parsing struct/union/class body");
2498 // Determine whether this is a non-nested class. Note that local
2499 // classes are *not* considered to be nested classes.
2500 bool NonNestedClass = true;
2501 if (!ClassStack.empty()) {
2502 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2503 if (S->isClassScope()) {
2504 // We're inside a class scope, so this is a nested class.
2505 NonNestedClass = false;
2507 // The Microsoft extension __interface does not permit nested classes.
2508 if (getCurrentClass().IsInterface) {
2509 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2511 << (isa<NamedDecl>(TagDecl)
2512 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2518 if ((S->getFlags() & Scope::FnScope)) {
2519 // If we're in a function or function template declared in the
2520 // body of a class, then this is a local class rather than a
2522 const Scope *Parent = S->getParent();
2523 if (Parent->isTemplateParamScope())
2524 Parent = Parent->getParent();
2525 if (Parent->isClassScope())
2531 // Enter a scope for the class.
2532 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2534 // Note that we are parsing a new (potentially-nested) class definition.
2535 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2536 TagType == DeclSpec::TST_interface);
2539 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2541 SourceLocation FinalLoc;
2542 bool IsFinalSpelledSealed = false;
2544 // Parse the optional 'final' keyword.
2545 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2546 VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
2547 assert((Specifier == VirtSpecifiers::VS_Final ||
2548 Specifier == VirtSpecifiers::VS_Sealed) &&
2549 "not a class definition");
2550 FinalLoc = ConsumeToken();
2551 IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
2553 if (TagType == DeclSpec::TST_interface)
2554 Diag(FinalLoc, diag::err_override_control_interface)
2555 << VirtSpecifiers::getSpecifierName(Specifier);
2556 else if (Specifier == VirtSpecifiers::VS_Final)
2557 Diag(FinalLoc, getLangOpts().CPlusPlus11
2558 ? diag::warn_cxx98_compat_override_control_keyword
2559 : diag::ext_override_control_keyword)
2560 << VirtSpecifiers::getSpecifierName(Specifier);
2561 else if (Specifier == VirtSpecifiers::VS_Sealed)
2562 Diag(FinalLoc, diag::ext_ms_sealed_keyword);
2564 // Parse any C++11 attributes after 'final' keyword.
2565 // These attributes are not allowed to appear here,
2566 // and the only possible place for them to appertain
2567 // to the class would be between class-key and class-name.
2568 CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
2571 if (Tok.is(tok::colon)) {
2572 ParseBaseClause(TagDecl);
2574 if (!Tok.is(tok::l_brace)) {
2575 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
2578 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2583 assert(Tok.is(tok::l_brace));
2584 BalancedDelimiterTracker T(*this, tok::l_brace);
2588 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2589 IsFinalSpelledSealed,
2590 T.getOpenLocation());
2592 // C++ 11p3: Members of a class defined with the keyword class are private
2593 // by default. Members of a class defined with the keywords struct or union
2594 // are public by default.
2595 AccessSpecifier CurAS;
2596 if (TagType == DeclSpec::TST_class)
2600 ParsedAttributes AccessAttrs(AttrFactory);
2603 // While we still have something to read, read the member-declarations.
2604 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2605 // Each iteration of this loop reads one member-declaration.
2607 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
2608 Tok.is(tok::kw___if_not_exists))) {
2609 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2613 // Check for extraneous top-level semicolon.
2614 if (Tok.is(tok::semi)) {
2615 ConsumeExtraSemi(InsideStruct, TagType);
2619 if (Tok.is(tok::annot_pragma_vis)) {
2620 HandlePragmaVisibility();
2624 if (Tok.is(tok::annot_pragma_pack)) {
2629 if (Tok.is(tok::annot_pragma_align)) {
2630 HandlePragmaAlign();
2634 if (Tok.is(tok::annot_pragma_openmp)) {
2635 ParseOpenMPDeclarativeDirective();
2639 // If we see a namespace here, a close brace was missing somewhere.
2640 if (Tok.is(tok::kw_namespace)) {
2641 DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
2645 AccessSpecifier AS = getAccessSpecifierIfPresent();
2646 if (AS != AS_none) {
2647 // Current token is a C++ access specifier.
2649 SourceLocation ASLoc = Tok.getLocation();
2650 unsigned TokLength = Tok.getLength();
2652 AccessAttrs.clear();
2653 MaybeParseGNUAttributes(AccessAttrs);
2655 SourceLocation EndLoc;
2656 if (Tok.is(tok::colon)) {
2657 EndLoc = Tok.getLocation();
2659 } else if (Tok.is(tok::semi)) {
2660 EndLoc = Tok.getLocation();
2662 Diag(EndLoc, diag::err_expected_colon)
2663 << FixItHint::CreateReplacement(EndLoc, ":");
2665 EndLoc = ASLoc.getLocWithOffset(TokLength);
2666 Diag(EndLoc, diag::err_expected_colon)
2667 << FixItHint::CreateInsertion(EndLoc, ":");
2670 // The Microsoft extension __interface does not permit non-public
2671 // access specifiers.
2672 if (TagType == DeclSpec::TST_interface && CurAS != AS_public) {
2673 Diag(ASLoc, diag::err_access_specifier_interface)
2674 << (CurAS == AS_protected);
2677 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
2678 AccessAttrs.getList())) {
2679 // found another attribute than only annotations
2680 AccessAttrs.clear();
2686 // Parse all the comma separated declarators.
2687 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
2692 SkipUntil(tok::r_brace);
2695 // If attributes exist after class contents, parse them.
2696 ParsedAttributes attrs(AttrFactory);
2697 MaybeParseGNUAttributes(attrs);
2700 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
2701 T.getOpenLocation(),
2702 T.getCloseLocation(),
2705 // C++11 [class.mem]p2:
2706 // Within the class member-specification, the class is regarded as complete
2707 // within function bodies, default arguments, and
2708 // brace-or-equal-initializers for non-static data members (including such
2709 // things in nested classes).
2710 if (TagDecl && NonNestedClass) {
2711 // We are not inside a nested class. This class and its nested classes
2712 // are complete and we can parse the delayed portions of method
2713 // declarations and the lexed inline method definitions, along with any
2714 // delayed attributes.
2715 SourceLocation SavedPrevTokLocation = PrevTokLocation;
2716 ParseLexedAttributes(getCurrentClass());
2717 ParseLexedMethodDeclarations(getCurrentClass());
2719 // We've finished with all pending member declarations.
2720 Actions.ActOnFinishCXXMemberDecls();
2722 ParseLexedMemberInitializers(getCurrentClass());
2723 ParseLexedMethodDefs(getCurrentClass());
2724 PrevTokLocation = SavedPrevTokLocation;
2728 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
2729 T.getCloseLocation());
2731 // Leave the class scope.
2736 void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
2737 assert(Tok.is(tok::kw_namespace));
2739 // FIXME: Suggest where the close brace should have gone by looking
2740 // at indentation changes within the definition body.
2741 Diag(D->getLocation(),
2742 diag::err_missing_end_of_definition) << D;
2743 Diag(Tok.getLocation(),
2744 diag::note_missing_end_of_definition_before) << D;
2746 // Push '};' onto the token stream to recover.
2750 Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
2751 Tok.setKind(tok::semi);
2754 Tok.setKind(tok::r_brace);
2757 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
2758 /// which explicitly initializes the members or base classes of a
2759 /// class (C++ [class.base.init]). For example, the three initializers
2760 /// after the ':' in the Derived constructor below:
2764 /// class Derived : Base {
2768 /// Derived(float f) : Base(), x(17), f(f) { }
2772 /// [C++] ctor-initializer:
2773 /// ':' mem-initializer-list
2775 /// [C++] mem-initializer-list:
2776 /// mem-initializer ...[opt]
2777 /// mem-initializer ...[opt] , mem-initializer-list
2778 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
2779 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
2781 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers
2782 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
2783 SourceLocation ColonLoc = ConsumeToken();
2785 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
2786 bool AnyErrors = false;
2789 if (Tok.is(tok::code_completion)) {
2790 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
2792 return cutOffParsing();
2794 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
2795 if (!MemInit.isInvalid())
2796 MemInitializers.push_back(MemInit.get());
2801 if (Tok.is(tok::comma))
2803 else if (Tok.is(tok::l_brace))
2805 // If the next token looks like a base or member initializer, assume that
2806 // we're just missing a comma.
2807 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
2808 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2809 Diag(Loc, diag::err_ctor_init_missing_comma)
2810 << FixItHint::CreateInsertion(Loc, ", ");
2812 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2813 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
2814 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2819 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
2823 /// ParseMemInitializer - Parse a C++ member initializer, which is
2824 /// part of a constructor initializer that explicitly initializes one
2825 /// member or base class (C++ [class.base.init]). See
2826 /// ParseConstructorInitializer for an example.
2828 /// [C++] mem-initializer:
2829 /// mem-initializer-id '(' expression-list[opt] ')'
2830 /// [C++0x] mem-initializer-id braced-init-list
2832 /// [C++] mem-initializer-id:
2833 /// '::'[opt] nested-name-specifier[opt] class-name
2835 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
2836 // parse '::'[opt] nested-name-specifier[opt]
2838 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
2839 ParsedType TemplateTypeTy;
2840 if (Tok.is(tok::annot_template_id)) {
2841 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2842 if (TemplateId->Kind == TNK_Type_template ||
2843 TemplateId->Kind == TNK_Dependent_template_name) {
2844 AnnotateTemplateIdTokenAsType();
2845 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
2846 TemplateTypeTy = getTypeAnnotation(Tok);
2849 // Uses of decltype will already have been converted to annot_decltype by
2850 // ParseOptionalCXXScopeSpecifier at this point.
2851 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
2852 && Tok.isNot(tok::annot_decltype)) {
2853 Diag(Tok, diag::err_expected_member_or_base_name);
2857 IdentifierInfo *II = 0;
2858 DeclSpec DS(AttrFactory);
2859 SourceLocation IdLoc = Tok.getLocation();
2860 if (Tok.is(tok::annot_decltype)) {
2861 // Get the decltype expression, if there is one.
2862 ParseDecltypeSpecifier(DS);
2864 if (Tok.is(tok::identifier))
2865 // Get the identifier. This may be a member name or a class name,
2866 // but we'll let the semantic analysis determine which it is.
2867 II = Tok.getIdentifierInfo();
2873 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2874 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2876 ExprResult InitList = ParseBraceInitializer();
2877 if (InitList.isInvalid())
2880 SourceLocation EllipsisLoc;
2881 if (Tok.is(tok::ellipsis))
2882 EllipsisLoc = ConsumeToken();
2884 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2885 TemplateTypeTy, DS, IdLoc,
2886 InitList.take(), EllipsisLoc);
2887 } else if(Tok.is(tok::l_paren)) {
2888 BalancedDelimiterTracker T(*this, tok::l_paren);
2891 // Parse the optional expression-list.
2892 ExprVector ArgExprs;
2893 CommaLocsTy CommaLocs;
2894 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
2895 SkipUntil(tok::r_paren, StopAtSemi);
2901 SourceLocation EllipsisLoc;
2902 if (Tok.is(tok::ellipsis))
2903 EllipsisLoc = ConsumeToken();
2905 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2906 TemplateTypeTy, DS, IdLoc,
2907 T.getOpenLocation(), ArgExprs,
2908 T.getCloseLocation(), EllipsisLoc);
2911 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::err_expected_lparen_or_lbrace
2912 : diag::err_expected_lparen);
2916 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
2918 /// exception-specification:
2919 /// dynamic-exception-specification
2920 /// noexcept-specification
2922 /// noexcept-specification:
2924 /// 'noexcept' '(' constant-expression ')'
2925 ExceptionSpecificationType
2926 Parser::tryParseExceptionSpecification(
2927 SourceRange &SpecificationRange,
2928 SmallVectorImpl<ParsedType> &DynamicExceptions,
2929 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2930 ExprResult &NoexceptExpr) {
2931 ExceptionSpecificationType Result = EST_None;
2933 // See if there's a dynamic specification.
2934 if (Tok.is(tok::kw_throw)) {
2935 Result = ParseDynamicExceptionSpecification(SpecificationRange,
2937 DynamicExceptionRanges);
2938 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
2939 "Produced different number of exception types and ranges.");
2942 // If there's no noexcept specification, we're done.
2943 if (Tok.isNot(tok::kw_noexcept))
2946 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
2948 // If we already had a dynamic specification, parse the noexcept for,
2949 // recovery, but emit a diagnostic and don't store the results.
2950 SourceRange NoexceptRange;
2951 ExceptionSpecificationType NoexceptType = EST_None;
2953 SourceLocation KeywordLoc = ConsumeToken();
2954 if (Tok.is(tok::l_paren)) {
2955 // There is an argument.
2956 BalancedDelimiterTracker T(*this, tok::l_paren);
2958 NoexceptType = EST_ComputedNoexcept;
2959 NoexceptExpr = ParseConstantExpression();
2960 // The argument must be contextually convertible to bool. We use
2961 // ActOnBooleanCondition for this purpose.
2962 if (!NoexceptExpr.isInvalid())
2963 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
2964 NoexceptExpr.get());
2966 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
2968 // There is no argument.
2969 NoexceptType = EST_BasicNoexcept;
2970 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
2973 if (Result == EST_None) {
2974 SpecificationRange = NoexceptRange;
2975 Result = NoexceptType;
2977 // If there's a dynamic specification after a noexcept specification,
2978 // parse that and ignore the results.
2979 if (Tok.is(tok::kw_throw)) {
2980 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2981 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
2982 DynamicExceptionRanges);
2985 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2991 static void diagnoseDynamicExceptionSpecification(
2992 Parser &P, const SourceRange &Range, bool IsNoexcept) {
2993 if (P.getLangOpts().CPlusPlus11) {
2994 const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
2995 P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range;
2996 P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
2997 << Replacement << FixItHint::CreateReplacement(Range, Replacement);
3001 /// ParseDynamicExceptionSpecification - Parse a C++
3002 /// dynamic-exception-specification (C++ [except.spec]).
3004 /// dynamic-exception-specification:
3005 /// 'throw' '(' type-id-list [opt] ')'
3006 /// [MS] 'throw' '(' '...' ')'
3009 /// type-id ... [opt]
3010 /// type-id-list ',' type-id ... [opt]
3012 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
3013 SourceRange &SpecificationRange,
3014 SmallVectorImpl<ParsedType> &Exceptions,
3015 SmallVectorImpl<SourceRange> &Ranges) {
3016 assert(Tok.is(tok::kw_throw) && "expected throw");
3018 SpecificationRange.setBegin(ConsumeToken());
3019 BalancedDelimiterTracker T(*this, tok::l_paren);
3020 if (T.consumeOpen()) {
3021 Diag(Tok, diag::err_expected_lparen_after) << "throw";
3022 SpecificationRange.setEnd(SpecificationRange.getBegin());
3023 return EST_DynamicNone;
3026 // Parse throw(...), a Microsoft extension that means "this function
3027 // can throw anything".
3028 if (Tok.is(tok::ellipsis)) {
3029 SourceLocation EllipsisLoc = ConsumeToken();
3030 if (!getLangOpts().MicrosoftExt)
3031 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
3033 SpecificationRange.setEnd(T.getCloseLocation());
3034 diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
3038 // Parse the sequence of type-ids.
3040 while (Tok.isNot(tok::r_paren)) {
3041 TypeResult Res(ParseTypeName(&Range));
3043 if (Tok.is(tok::ellipsis)) {
3044 // C++0x [temp.variadic]p5:
3045 // - In a dynamic-exception-specification (15.4); the pattern is a
3047 SourceLocation Ellipsis = ConsumeToken();
3048 Range.setEnd(Ellipsis);
3049 if (!Res.isInvalid())
3050 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
3053 if (!Res.isInvalid()) {
3054 Exceptions.push_back(Res.get());
3055 Ranges.push_back(Range);
3058 if (Tok.is(tok::comma))
3065 SpecificationRange.setEnd(T.getCloseLocation());
3066 diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
3067 Exceptions.empty());
3068 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
3071 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
3072 /// function declaration.
3073 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
3074 assert(Tok.is(tok::arrow) && "expected arrow");
3078 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
3081 /// \brief We have just started parsing the definition of a new class,
3082 /// so push that class onto our stack of classes that is currently
3084 Sema::ParsingClassState
3085 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
3087 assert((NonNestedClass || !ClassStack.empty()) &&
3088 "Nested class without outer class");
3089 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
3090 return Actions.PushParsingClass();
3093 /// \brief Deallocate the given parsed class and all of its nested
3095 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
3096 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
3097 delete Class->LateParsedDeclarations[I];
3101 /// \brief Pop the top class of the stack of classes that are
3102 /// currently being parsed.
3104 /// This routine should be called when we have finished parsing the
3105 /// definition of a class, but have not yet popped the Scope
3106 /// associated with the class's definition.
3107 void Parser::PopParsingClass(Sema::ParsingClassState state) {
3108 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
3110 Actions.PopParsingClass(state);
3112 ParsingClass *Victim = ClassStack.top();
3114 if (Victim->TopLevelClass) {
3115 // Deallocate all of the nested classes of this class,
3116 // recursively: we don't need to keep any of this information.
3117 DeallocateParsedClasses(Victim);
3120 assert(!ClassStack.empty() && "Missing top-level class?");
3122 if (Victim->LateParsedDeclarations.empty()) {
3123 // The victim is a nested class, but we will not need to perform
3124 // any processing after the definition of this class since it has
3125 // no members whose handling was delayed. Therefore, we can just
3126 // remove this nested class.
3127 DeallocateParsedClasses(Victim);
3131 // This nested class has some members that will need to be processed
3132 // after the top-level class is completely defined. Therefore, add
3133 // it to the list of nested classes within its parent.
3134 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
3135 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
3136 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
3139 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
3141 /// \return the parsed identifier on success, and 0 if the next token is not an
3142 /// attribute-token.
3144 /// C++11 [dcl.attr.grammar]p3:
3145 /// If a keyword or an alternative token that satisfies the syntactic
3146 /// requirements of an identifier is contained in an attribute-token,
3147 /// it is considered an identifier.
3148 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
3149 switch (Tok.getKind()) {
3151 // Identifiers and keywords have identifier info attached.
3152 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
3153 Loc = ConsumeToken();
3158 case tok::ampamp: // 'and'
3159 case tok::pipe: // 'bitor'
3160 case tok::pipepipe: // 'or'
3161 case tok::caret: // 'xor'
3162 case tok::tilde: // 'compl'
3163 case tok::amp: // 'bitand'
3164 case tok::ampequal: // 'and_eq'
3165 case tok::pipeequal: // 'or_eq'
3166 case tok::caretequal: // 'xor_eq'
3167 case tok::exclaim: // 'not'
3168 case tok::exclaimequal: // 'not_eq'
3169 // Alternative tokens do not have identifier info, but their spelling
3170 // starts with an alphabetical character.
3171 SmallString<8> SpellingBuf;
3172 StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf);
3173 if (isLetter(Spelling[0])) {
3174 Loc = ConsumeToken();
3175 return &PP.getIdentifierTable().get(Spelling);
3181 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
3182 IdentifierInfo *ScopeName) {
3183 switch (AttributeList::getKind(AttrName, ScopeName,
3184 AttributeList::AS_CXX11)) {
3185 case AttributeList::AT_CarriesDependency:
3186 case AttributeList::AT_FallThrough:
3187 case AttributeList::AT_CXX11NoReturn: {
3196 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Currently
3197 /// only parses standard attributes.
3199 /// [C++11] attribute-specifier:
3200 /// '[' '[' attribute-list ']' ']'
3201 /// alignment-specifier
3203 /// [C++11] attribute-list:
3205 /// attribute-list ',' attribute[opt]
3207 /// attribute-list ',' attribute '...'
3209 /// [C++11] attribute:
3210 /// attribute-token attribute-argument-clause[opt]
3212 /// [C++11] attribute-token:
3214 /// attribute-scoped-token
3216 /// [C++11] attribute-scoped-token:
3217 /// attribute-namespace '::' identifier
3219 /// [C++11] attribute-namespace:
3222 /// [C++11] attribute-argument-clause:
3223 /// '(' balanced-token-seq ')'
3225 /// [C++11] balanced-token-seq:
3227 /// balanced-token-seq balanced-token
3229 /// [C++11] balanced-token:
3230 /// '(' balanced-token-seq ')'
3231 /// '[' balanced-token-seq ']'
3232 /// '{' balanced-token-seq '}'
3233 /// any token but '(', ')', '[', ']', '{', or '}'
3234 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
3235 SourceLocation *endLoc) {
3236 if (Tok.is(tok::kw_alignas)) {
3237 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
3238 ParseAlignmentSpecifier(attrs, endLoc);
3242 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
3243 && "Not a C++11 attribute list");
3245 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
3250 llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
3252 while (Tok.isNot(tok::r_square)) {
3253 // attribute not present
3254 if (Tok.is(tok::comma)) {
3259 SourceLocation ScopeLoc, AttrLoc;
3260 IdentifierInfo *ScopeName = 0, *AttrName = 0;
3262 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3264 // Break out to the "expected ']'" diagnostic.
3268 if (Tok.is(tok::coloncolon)) {
3271 ScopeName = AttrName;
3274 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
3276 Diag(Tok.getLocation(), diag::err_expected_ident);
3277 SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
3282 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName,ScopeName);
3283 bool AttrParsed = false;
3286 !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
3287 Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
3288 << AttrName << SourceRange(SeenAttrs[AttrName]);
3290 // Parse attribute arguments
3291 if (Tok.is(tok::l_paren)) {
3292 if (ScopeName && ScopeName->getName() == "gnu") {
3293 ParseGNUAttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3294 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3298 Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_arguments)
3299 << AttrName->getName();
3301 // FIXME: handle other formats of c++11 attribute arguments
3303 SkipUntil(tok::r_paren);
3308 attrs.addNew(AttrName,
3309 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3311 ScopeName, ScopeLoc, 0, 0, AttributeList::AS_CXX11);
3313 if (Tok.is(tok::ellipsis)) {
3316 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3317 << AttrName->getName();
3321 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
3322 SkipUntil(tok::r_square);
3324 *endLoc = Tok.getLocation();
3325 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
3326 SkipUntil(tok::r_square);
3329 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3331 /// attribute-specifier-seq:
3332 /// attribute-specifier-seq[opt] attribute-specifier
3333 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3334 SourceLocation *endLoc) {
3335 assert(getLangOpts().CPlusPlus11);
3337 SourceLocation StartLoc = Tok.getLocation(), Loc;
3342 ParseCXX11AttributeSpecifier(attrs, endLoc);
3343 } while (isCXX11AttributeSpecifier());
3345 attrs.Range = SourceRange(StartLoc, *endLoc);
3348 void Parser::DiagnoseAndSkipCXX11Attributes() {
3349 if (!isCXX11AttributeSpecifier())
3352 // Start and end location of an attribute or an attribute list.
3353 SourceLocation StartLoc = Tok.getLocation();
3354 SourceLocation EndLoc;
3357 if (Tok.is(tok::l_square)) {
3358 BalancedDelimiterTracker T(*this, tok::l_square);
3361 EndLoc = T.getCloseLocation();
3363 assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
3365 BalancedDelimiterTracker T(*this, tok::l_paren);
3366 if (!T.consumeOpen())
3368 EndLoc = T.getCloseLocation();
3370 } while (isCXX11AttributeSpecifier());
3372 if (EndLoc.isValid()) {
3373 SourceRange Range(StartLoc, EndLoc);
3374 Diag(StartLoc, diag::err_attributes_not_allowed)
3379 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
3381 /// [MS] ms-attribute:
3382 /// '[' token-seq ']'
3384 /// [MS] ms-attribute-seq:
3385 /// ms-attribute[opt]
3386 /// ms-attribute ms-attribute-seq
3387 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3388 SourceLocation *endLoc) {
3389 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3391 while (Tok.is(tok::l_square)) {
3392 // FIXME: If this is actually a C++11 attribute, parse it as one.
3394 SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
3395 if (endLoc) *endLoc = Tok.getLocation();
3396 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare);
3400 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3401 AccessSpecifier& CurAS) {
3402 IfExistsCondition Result;
3403 if (ParseMicrosoftIfExistsCondition(Result))
3406 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3407 if (Braces.consumeOpen()) {
3408 Diag(Tok, diag::err_expected_lbrace);
3412 switch (Result.Behavior) {
3414 // Parse the declarations below.
3418 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3419 << Result.IsIfExists;
3420 // Fall through to skip.
3427 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
3428 // __if_exists, __if_not_exists can nest.
3429 if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
3430 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3434 // Check for extraneous top-level semicolon.
3435 if (Tok.is(tok::semi)) {
3436 ConsumeExtraSemi(InsideStruct, TagType);
3440 AccessSpecifier AS = getAccessSpecifierIfPresent();
3441 if (AS != AS_none) {
3442 // Current token is a C++ access specifier.
3444 SourceLocation ASLoc = Tok.getLocation();
3446 if (Tok.is(tok::colon))
3447 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3449 Diag(Tok, diag::err_expected_colon);
3454 // Parse all the comma separated declarators.
3455 ParseCXXClassMemberDeclaration(CurAS, 0);
3458 Braces.consumeClose();