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/Basic/OperatorKinds.h"
15 #include "clang/Parse/Parser.h"
16 #include "clang/Parse/ParseDiagnostic.h"
17 #include "clang/Sema/DeclSpec.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ParsedTemplate.h"
20 #include "clang/Sema/PrettyDeclStackTrace.h"
21 #include "clang/Sema/SemaDiagnostic.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "RAIIObjectsForParser.h"
24 using namespace clang;
26 /// ParseNamespace - We know that the current token is a namespace keyword. This
27 /// may either be a top level namespace or a block-level namespace alias. If
28 /// there was an inline keyword, it has already been parsed.
30 /// namespace-definition: [C++ 7.3: basic.namespace]
31 /// named-namespace-definition
32 /// unnamed-namespace-definition
34 /// unnamed-namespace-definition:
35 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
37 /// named-namespace-definition:
38 /// original-namespace-definition
39 /// extension-namespace-definition
41 /// original-namespace-definition:
42 /// 'inline'[opt] 'namespace' identifier attributes[opt]
43 /// '{' namespace-body '}'
45 /// extension-namespace-definition:
46 /// 'inline'[opt] 'namespace' original-namespace-name
47 /// '{' namespace-body '}'
49 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
50 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
52 Decl *Parser::ParseNamespace(unsigned Context,
53 SourceLocation &DeclEnd,
54 SourceLocation InlineLoc) {
55 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
56 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
57 ObjCDeclContextSwitch ObjCDC(*this);
59 if (Tok.is(tok::code_completion)) {
60 Actions.CodeCompleteNamespaceDecl(getCurScope());
65 SourceLocation IdentLoc;
66 IdentifierInfo *Ident = 0;
67 std::vector<SourceLocation> ExtraIdentLoc;
68 std::vector<IdentifierInfo*> ExtraIdent;
69 std::vector<SourceLocation> ExtraNamespaceLoc;
73 if (Tok.is(tok::identifier)) {
74 Ident = Tok.getIdentifierInfo();
75 IdentLoc = ConsumeToken(); // eat the identifier.
76 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
77 ExtraNamespaceLoc.push_back(ConsumeToken());
78 ExtraIdent.push_back(Tok.getIdentifierInfo());
79 ExtraIdentLoc.push_back(ConsumeToken());
83 // Read label attributes, if present.
84 ParsedAttributes attrs(AttrFactory);
85 if (Tok.is(tok::kw___attribute)) {
87 ParseGNUAttributes(attrs);
90 if (Tok.is(tok::equal)) {
92 Diag(Tok, diag::err_expected_ident);
93 // Skip to end of the definition and eat the ';'.
98 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
99 if (InlineLoc.isValid())
100 Diag(InlineLoc, diag::err_inline_namespace_alias)
101 << FixItHint::CreateRemoval(InlineLoc);
102 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
106 BalancedDelimiterTracker T(*this, tok::l_brace);
107 if (T.consumeOpen()) {
108 if (!ExtraIdent.empty()) {
109 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
110 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
112 Diag(Tok, Ident ? diag::err_expected_lbrace :
113 diag::err_expected_ident_lbrace);
117 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
118 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
119 getCurScope()->getFnParent()) {
120 if (!ExtraIdent.empty()) {
121 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
122 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
124 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
125 SkipUntil(tok::r_brace, false);
129 if (!ExtraIdent.empty()) {
130 TentativeParsingAction TPA(*this);
131 SkipUntil(tok::r_brace, /*StopAtSemi*/false, /*DontConsume*/true);
132 Token rBraceToken = Tok;
135 if (!rBraceToken.is(tok::r_brace)) {
136 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
137 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
139 std::string NamespaceFix;
140 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
141 E = ExtraIdent.end(); I != E; ++I) {
142 NamespaceFix += " { namespace ";
143 NamespaceFix += (*I)->getName();
147 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
150 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
151 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
152 ExtraIdentLoc.back()),
154 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
158 // If we're still good, complain about inline namespaces in non-C++0x now.
159 if (InlineLoc.isValid())
160 Diag(InlineLoc, getLangOpts().CPlusPlus0x ?
161 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
163 // Enter a scope for the namespace.
164 ParseScope NamespaceScope(this, Scope::DeclScope);
167 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
168 IdentLoc, Ident, T.getOpenLocation(),
171 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
172 "parsing namespace");
174 // Parse the contents of the namespace. This includes parsing recovery on
175 // any improperly nested namespaces.
176 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
177 InlineLoc, attrs, T);
179 // Leave the namespace scope.
180 NamespaceScope.Exit();
182 DeclEnd = T.getCloseLocation();
183 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
188 /// ParseInnerNamespace - Parse the contents of a namespace.
189 void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
190 std::vector<IdentifierInfo*>& Ident,
191 std::vector<SourceLocation>& NamespaceLoc,
192 unsigned int index, SourceLocation& InlineLoc,
193 ParsedAttributes& attrs,
194 BalancedDelimiterTracker &Tracker) {
195 if (index == Ident.size()) {
196 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
197 ParsedAttributesWithRange attrs(AttrFactory);
198 MaybeParseCXX0XAttributes(attrs);
199 MaybeParseMicrosoftAttributes(attrs);
200 ParseExternalDeclaration(attrs);
203 // The caller is what called check -- we are simply calling
205 Tracker.consumeClose();
210 // Parse improperly nested namespaces.
211 ParseScope NamespaceScope(this, Scope::DeclScope);
213 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
214 NamespaceLoc[index], IdentLoc[index],
215 Ident[index], Tracker.getOpenLocation(),
218 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
221 NamespaceScope.Exit();
223 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
226 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
227 /// alias definition.
229 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
230 SourceLocation AliasLoc,
231 IdentifierInfo *Alias,
232 SourceLocation &DeclEnd) {
233 assert(Tok.is(tok::equal) && "Not equal token");
235 ConsumeToken(); // eat the '='.
237 if (Tok.is(tok::code_completion)) {
238 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
244 // Parse (optional) nested-name-specifier.
245 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
247 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
248 Diag(Tok, diag::err_expected_namespace_name);
249 // Skip to end of the definition and eat the ';'.
250 SkipUntil(tok::semi);
255 IdentifierInfo *Ident = Tok.getIdentifierInfo();
256 SourceLocation IdentLoc = ConsumeToken();
259 DeclEnd = Tok.getLocation();
260 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
263 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
264 SS, IdentLoc, Ident);
267 /// ParseLinkage - We know that the current token is a string_literal
268 /// and just before that, that extern was seen.
270 /// linkage-specification: [C++ 7.5p2: dcl.link]
271 /// 'extern' string-literal '{' declaration-seq[opt] '}'
272 /// 'extern' string-literal declaration
274 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
275 assert(Tok.is(tok::string_literal) && "Not a string literal!");
276 SmallString<8> LangBuffer;
277 bool Invalid = false;
278 StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid);
282 // FIXME: This is incorrect: linkage-specifiers are parsed in translation
283 // phase 7, so string-literal concatenation is supposed to occur.
284 // extern "" "C" "" "+" "+" { } is legal.
285 if (Tok.hasUDSuffix())
286 Diag(Tok, diag::err_invalid_string_udl);
287 SourceLocation Loc = ConsumeStringToken();
289 ParseScope LinkageScope(this, Scope::DeclScope);
291 = Actions.ActOnStartLinkageSpecification(getCurScope(),
292 DS.getSourceRange().getBegin(),
294 Tok.is(tok::l_brace) ? Tok.getLocation()
297 ParsedAttributesWithRange attrs(AttrFactory);
298 MaybeParseCXX0XAttributes(attrs);
299 MaybeParseMicrosoftAttributes(attrs);
301 if (Tok.isNot(tok::l_brace)) {
302 // Reset the source range in DS, as the leading "extern"
303 // does not really belong to the inner declaration ...
304 DS.SetRangeStart(SourceLocation());
305 DS.SetRangeEnd(SourceLocation());
306 // ... but anyway remember that such an "extern" was seen.
307 DS.setExternInLinkageSpec(true);
308 ParseExternalDeclaration(attrs, &DS);
309 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
315 ProhibitAttributes(attrs);
317 BalancedDelimiterTracker T(*this, tok::l_brace);
319 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
320 ParsedAttributesWithRange attrs(AttrFactory);
321 MaybeParseCXX0XAttributes(attrs);
322 MaybeParseMicrosoftAttributes(attrs);
323 ParseExternalDeclaration(attrs);
327 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
328 T.getCloseLocation());
331 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
332 /// using-directive. Assumes that current token is 'using'.
333 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
334 const ParsedTemplateInfo &TemplateInfo,
335 SourceLocation &DeclEnd,
336 ParsedAttributesWithRange &attrs,
338 assert(Tok.is(tok::kw_using) && "Not using token");
339 ObjCDeclContextSwitch ObjCDC(*this);
342 SourceLocation UsingLoc = ConsumeToken();
344 if (Tok.is(tok::code_completion)) {
345 Actions.CodeCompleteUsing(getCurScope());
350 // 'using namespace' means this is a using-directive.
351 if (Tok.is(tok::kw_namespace)) {
352 // Template parameters are always an error here.
353 if (TemplateInfo.Kind) {
354 SourceRange R = TemplateInfo.getSourceRange();
355 Diag(UsingLoc, diag::err_templated_using_directive)
356 << R << FixItHint::CreateRemoval(R);
359 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
362 // Otherwise, it must be a using-declaration or an alias-declaration.
364 // Using declarations can't have attributes.
365 ProhibitAttributes(attrs);
367 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
371 /// ParseUsingDirective - Parse C++ using-directive, assumes
372 /// that current token is 'namespace' and 'using' was already parsed.
374 /// using-directive: [C++ 7.3.p4: namespace.udir]
375 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
377 /// [GNU] using-directive:
378 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
379 /// namespace-name attributes[opt] ;
381 Decl *Parser::ParseUsingDirective(unsigned Context,
382 SourceLocation UsingLoc,
383 SourceLocation &DeclEnd,
384 ParsedAttributes &attrs) {
385 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
388 SourceLocation NamespcLoc = ConsumeToken();
390 if (Tok.is(tok::code_completion)) {
391 Actions.CodeCompleteUsingDirective(getCurScope());
397 // Parse (optional) nested-name-specifier.
398 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
400 IdentifierInfo *NamespcName = 0;
401 SourceLocation IdentLoc = SourceLocation();
403 // Parse namespace-name.
404 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
405 Diag(Tok, diag::err_expected_namespace_name);
406 // If there was invalid namespace name, skip to end of decl, and eat ';'.
407 SkipUntil(tok::semi);
408 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
413 NamespcName = Tok.getIdentifierInfo();
414 IdentLoc = ConsumeToken();
416 // Parse (optional) attributes (most likely GNU strong-using extension).
417 bool GNUAttr = false;
418 if (Tok.is(tok::kw___attribute)) {
420 ParseGNUAttributes(attrs);
424 DeclEnd = Tok.getLocation();
425 ExpectAndConsume(tok::semi,
426 GNUAttr ? diag::err_expected_semi_after_attribute_list
427 : diag::err_expected_semi_after_namespace_name,
430 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
431 IdentLoc, NamespcName, attrs.getList());
434 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
435 /// Assumes that 'using' was already seen.
437 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
438 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
440 /// 'using' :: unqualified-id
442 /// alias-declaration: C++0x [decl.typedef]p2
443 /// 'using' identifier = type-id ;
445 Decl *Parser::ParseUsingDeclaration(unsigned Context,
446 const ParsedTemplateInfo &TemplateInfo,
447 SourceLocation UsingLoc,
448 SourceLocation &DeclEnd,
452 SourceLocation TypenameLoc;
454 ParsedAttributesWithRange attrs(AttrFactory);
456 // FIXME: Simply skip the attributes and diagnose, don't bother parsing them.
457 MaybeParseCXX0XAttributes(attrs);
458 ProhibitAttributes(attrs);
460 attrs.Range = SourceRange();
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 = Tok.getLocation();
472 // Parse nested-name-specifier.
473 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
475 // Check nested-name specifier.
476 if (SS.isInvalid()) {
477 SkipUntil(tok::semi);
481 // Parse the unqualified-id. We allow parsing of both constructor and
482 // destructor names and allow the action module to diagnose any semantic
484 SourceLocation TemplateKWLoc;
486 if (ParseUnqualifiedId(SS,
487 /*EnteringContext=*/false,
488 /*AllowDestructorName=*/true,
489 /*AllowConstructorName=*/true,
493 SkipUntil(tok::semi);
497 MaybeParseCXX0XAttributes(attrs);
499 // Maybe this is an alias-declaration.
500 bool IsAliasDecl = Tok.is(tok::equal);
501 TypeResult TypeAlias;
503 // TODO: Attribute support. C++0x attributes may appear before the equals.
504 // Where can GNU attributes appear?
507 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
508 diag::warn_cxx98_compat_alias_declaration :
509 diag::ext_alias_declaration);
511 // Type alias templates cannot be specialized.
513 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
514 Name.getKind() == UnqualifiedId::IK_TemplateId)
516 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
518 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
520 if (SpecKind != -1) {
523 Range = SourceRange(Name.TemplateId->LAngleLoc,
524 Name.TemplateId->RAngleLoc);
526 Range = TemplateInfo.getSourceRange();
527 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
528 << SpecKind << Range;
529 SkipUntil(tok::semi);
533 // Name must be an identifier.
534 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
535 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
536 // No removal fixit: can't recover from this.
537 SkipUntil(tok::semi);
539 } else if (IsTypeName)
540 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
541 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
542 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
543 else if (SS.isNotEmpty())
544 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
545 << FixItHint::CreateRemoval(SS.getRange());
547 TypeAlias = ParseTypeName(0, TemplateInfo.Kind ?
548 Declarator::AliasTemplateContext :
549 Declarator::AliasDeclContext, AS, OwnedType);
551 // C++11 attributes are not allowed on a using-declaration, but GNU ones
553 ProhibitAttributes(attrs);
555 // Parse (optional) attributes (most likely GNU strong-using extension).
556 MaybeParseGNUAttributes(attrs);
560 DeclEnd = Tok.getLocation();
561 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
562 !attrs.empty() ? "attributes list" :
563 IsAliasDecl ? "alias declaration" : "using declaration",
566 // Diagnose an attempt to declare a templated using-declaration.
567 // In C++0x, alias-declarations can be templates:
568 // template <...> using id = type;
569 if (TemplateInfo.Kind && !IsAliasDecl) {
570 SourceRange R = TemplateInfo.getSourceRange();
571 Diag(UsingLoc, diag::err_templated_using_declaration)
572 << R << FixItHint::CreateRemoval(R);
574 // Unfortunately, we have to bail out instead of recovering by
575 // ignoring the parameters, just in case the nested name specifier
576 // depends on the parameters.
580 // "typename" keyword is allowed for identifiers only,
581 // because it may be a type definition.
582 if (IsTypeName && Name.getKind() != UnqualifiedId::IK_Identifier) {
583 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
584 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
585 // Proceed parsing, but reset the IsTypeName flag.
590 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
591 MultiTemplateParamsArg TemplateParamsArg(
592 TemplateParams ? TemplateParams->data() : 0,
593 TemplateParams ? TemplateParams->size() : 0);
594 // FIXME: Propagate attributes.
595 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
596 UsingLoc, Name, TypeAlias);
599 return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS,
600 Name, attrs.getList(),
601 IsTypeName, TypenameLoc);
604 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
606 /// [C++0x] static_assert-declaration:
607 /// static_assert ( constant-expression , string-literal ) ;
609 /// [C11] static_assert-declaration:
610 /// _Static_assert ( constant-expression , string-literal ) ;
612 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
613 assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) &&
614 "Not a static_assert declaration");
616 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
617 Diag(Tok, diag::ext_c11_static_assert);
618 if (Tok.is(tok::kw_static_assert))
619 Diag(Tok, diag::warn_cxx98_compat_static_assert);
621 SourceLocation StaticAssertLoc = ConsumeToken();
623 BalancedDelimiterTracker T(*this, tok::l_paren);
624 if (T.consumeOpen()) {
625 Diag(Tok, diag::err_expected_lparen);
630 ExprResult AssertExpr(ParseConstantExpression());
631 if (AssertExpr.isInvalid()) {
636 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
639 if (!isTokenStringLiteral()) {
640 Diag(Tok, diag::err_expected_string_literal);
645 ExprResult AssertMessage(ParseStringLiteralExpression());
646 if (AssertMessage.isInvalid()) {
653 DeclEnd = Tok.getLocation();
654 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
656 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
658 AssertMessage.take(),
659 T.getCloseLocation());
662 /// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
664 /// 'decltype' ( expression )
666 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
667 assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
668 && "Not a decltype specifier");
672 SourceLocation StartLoc = Tok.getLocation();
673 SourceLocation EndLoc;
675 if (Tok.is(tok::annot_decltype)) {
676 Result = getExprAnnotation(Tok);
677 EndLoc = Tok.getAnnotationEndLoc();
679 if (Result.isInvalid()) {
680 DS.SetTypeSpecError();
684 if (Tok.getIdentifierInfo()->isStr("decltype"))
685 Diag(Tok, diag::warn_cxx98_compat_decltype);
689 BalancedDelimiterTracker T(*this, tok::l_paren);
690 if (T.expectAndConsume(diag::err_expected_lparen_after,
691 "decltype", tok::r_paren)) {
692 DS.SetTypeSpecError();
693 return T.getOpenLocation() == Tok.getLocation() ?
694 StartLoc : T.getOpenLocation();
697 // Parse the expression
699 // C++0x [dcl.type.simple]p4:
700 // The operand of the decltype specifier is an unevaluated operand.
701 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
702 0, /*IsDecltype=*/true);
703 Result = ParseExpression();
704 if (Result.isInvalid()) {
705 DS.SetTypeSpecError();
706 if (SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true)) {
707 EndLoc = ConsumeParen();
709 if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
710 // Backtrack to get the location of the last token before the semi.
711 PP.RevertCachedTokens(2);
712 ConsumeToken(); // the semi.
713 EndLoc = ConsumeAnyToken();
714 assert(Tok.is(tok::semi));
716 EndLoc = Tok.getLocation();
724 if (T.getCloseLocation().isInvalid()) {
725 DS.SetTypeSpecError();
726 // FIXME: this should return the location of the last token
727 // that was consumed (by "consumeClose()")
728 return T.getCloseLocation();
731 Result = Actions.ActOnDecltypeExpression(Result.take());
732 if (Result.isInvalid()) {
733 DS.SetTypeSpecError();
734 return T.getCloseLocation();
737 EndLoc = T.getCloseLocation();
740 const char *PrevSpec = 0;
742 // Check for duplicate type specifiers (e.g. "int decltype(a)").
743 if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
744 DiagID, Result.release())) {
745 Diag(StartLoc, DiagID) << PrevSpec;
746 DS.SetTypeSpecError();
751 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
752 SourceLocation StartLoc,
753 SourceLocation EndLoc) {
754 // make sure we have a token we can turn into an annotation token
755 if (PP.isBacktrackEnabled())
756 PP.RevertCachedTokens(1);
760 Tok.setKind(tok::annot_decltype);
761 setExprAnnotation(Tok, DS.getTypeSpecType() == TST_decltype ?
762 DS.getRepAsExpr() : ExprResult());
763 Tok.setAnnotationEndLoc(EndLoc);
764 Tok.setLocation(StartLoc);
765 PP.AnnotateCachedTokens(Tok);
768 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
769 assert(Tok.is(tok::kw___underlying_type) &&
770 "Not an underlying type specifier");
772 SourceLocation StartLoc = ConsumeToken();
773 BalancedDelimiterTracker T(*this, tok::l_paren);
774 if (T.expectAndConsume(diag::err_expected_lparen_after,
775 "__underlying_type", tok::r_paren)) {
779 TypeResult Result = ParseTypeName();
780 if (Result.isInvalid()) {
781 SkipUntil(tok::r_paren);
787 if (T.getCloseLocation().isInvalid())
790 const char *PrevSpec = 0;
792 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
793 DiagID, Result.release()))
794 Diag(StartLoc, DiagID) << PrevSpec;
797 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
798 /// class name or decltype-specifier. Note that we only check that the result
799 /// names a type; semantic analysis will need to verify that the type names a
800 /// class. The result is either a type or null, depending on whether a type
803 /// base-type-specifier: [C++ 10.1]
804 /// class-or-decltype
805 /// class-or-decltype: [C++ 10.1]
806 /// nested-name-specifier[opt] class-name
807 /// decltype-specifier
808 /// class-name: [C++ 9.1]
810 /// simple-template-id
812 Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
813 SourceLocation &EndLocation) {
814 // Ignore attempts to use typename
815 if (Tok.is(tok::kw_typename)) {
816 Diag(Tok, diag::err_expected_class_name_not_template)
817 << FixItHint::CreateRemoval(Tok.getLocation());
821 // Parse optional nested-name-specifier
823 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
825 BaseLoc = Tok.getLocation();
827 // Parse decltype-specifier
828 // tok == kw_decltype is just error recovery, it can only happen when SS
830 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
832 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
833 << FixItHint::CreateRemoval(SS.getRange());
834 // Fake up a Declarator to use with ActOnTypeName.
835 DeclSpec DS(AttrFactory);
837 EndLocation = ParseDecltypeSpecifier(DS);
839 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
840 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
843 // Check whether we have a template-id that names a type.
844 if (Tok.is(tok::annot_template_id)) {
845 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
846 if (TemplateId->Kind == TNK_Type_template ||
847 TemplateId->Kind == TNK_Dependent_template_name) {
848 AnnotateTemplateIdTokenAsType();
850 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
851 ParsedType Type = getTypeAnnotation(Tok);
852 EndLocation = Tok.getAnnotationEndLoc();
860 // Fall through to produce an error below.
863 if (Tok.isNot(tok::identifier)) {
864 Diag(Tok, diag::err_expected_class_name);
868 IdentifierInfo *Id = Tok.getIdentifierInfo();
869 SourceLocation IdLoc = ConsumeToken();
871 if (Tok.is(tok::less)) {
872 // It looks the user intended to write a template-id here, but the
873 // template-name was wrong. Try to fix that.
874 TemplateNameKind TNK = TNK_Type_template;
876 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
877 &SS, Template, TNK)) {
878 Diag(IdLoc, diag::err_unknown_template_name)
885 // Form the template name
886 UnqualifiedId TemplateName;
887 TemplateName.setIdentifier(Id, IdLoc);
889 // Parse the full template-id, then turn it into a type.
890 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
893 if (TNK == TNK_Dependent_template_name)
894 AnnotateTemplateIdTokenAsType();
896 // If we didn't end up with a typename token, there's nothing more we
898 if (Tok.isNot(tok::annot_typename))
901 // Retrieve the type from the annotation token, consume that token, and
903 EndLocation = Tok.getAnnotationEndLoc();
904 ParsedType Type = getTypeAnnotation(Tok);
909 // We have an identifier; check whether it is actually a type.
910 IdentifierInfo *CorrectedII = 0;
911 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
913 /*IsCtorOrDtorName=*/false,
914 /*NonTrivialTypeSourceInfo=*/true,
917 Diag(IdLoc, diag::err_expected_class_name);
921 // Consume the identifier.
924 // Fake up a Declarator to use with ActOnTypeName.
925 DeclSpec DS(AttrFactory);
926 DS.SetRangeStart(IdLoc);
927 DS.SetRangeEnd(EndLocation);
928 DS.getTypeSpecScope() = SS;
930 const char *PrevSpec = 0;
932 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type);
934 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
935 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
938 void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
939 while (Tok.is(tok::kw___single_inheritance) ||
940 Tok.is(tok::kw___multiple_inheritance) ||
941 Tok.is(tok::kw___virtual_inheritance)) {
942 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
943 SourceLocation AttrNameLoc = ConsumeToken();
944 attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
945 SourceLocation(), 0, 0, AttributeList::AS_GNU);
949 /// Determine whether the following tokens are valid after a type-specifier
950 /// which could be a standalone declaration. This will conservatively return
951 /// true if there's any doubt, and is appropriate for insert-';' fixits.
952 bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
953 // This switch enumerates the valid "follow" set for type-specifiers.
954 switch (Tok.getKind()) {
956 case tok::semi: // struct foo {...} ;
957 case tok::star: // struct foo {...} * P;
958 case tok::amp: // struct foo {...} & R = ...
959 case tok::identifier: // struct foo {...} V ;
960 case tok::r_paren: //(struct foo {...} ) {4}
961 case tok::annot_cxxscope: // struct foo {...} a:: b;
962 case tok::annot_typename: // struct foo {...} a ::b;
963 case tok::annot_template_id: // struct foo {...} a<int> ::b;
964 case tok::l_paren: // struct foo {...} ( x);
965 case tok::comma: // __builtin_offsetof(struct foo{...} ,
968 return CouldBeBitfield; // enum E { ... } : 2;
970 case tok::kw_const: // struct foo {...} const x;
971 case tok::kw_volatile: // struct foo {...} volatile x;
972 case tok::kw_restrict: // struct foo {...} restrict x;
973 case tok::kw_inline: // struct foo {...} inline foo() {};
974 // Storage-class specifiers
975 case tok::kw_static: // struct foo {...} static x;
976 case tok::kw_extern: // struct foo {...} extern x;
977 case tok::kw_typedef: // struct foo {...} typedef x;
978 case tok::kw_register: // struct foo {...} register x;
979 case tok::kw_auto: // struct foo {...} auto x;
980 case tok::kw_mutable: // struct foo {...} mutable x;
981 case tok::kw_constexpr: // struct foo {...} constexpr x;
982 // As shown above, type qualifiers and storage class specifiers absolutely
983 // can occur after class specifiers according to the grammar. However,
984 // almost no one actually writes code like this. If we see one of these,
985 // it is much more likely that someone missed a semi colon and the
986 // type/storage class specifier we're seeing is part of the *next*
987 // intended declaration, as in:
989 // struct foo { ... }
992 // We'd really like to emit a missing semicolon error instead of emitting
993 // an error on the 'int' saying that you can't have two type specifiers in
994 // the same declaration of X. Because of this, we look ahead past this
995 // token to see if it's a type specifier. If so, we know the code is
996 // otherwise invalid, so we can produce the expected semi error.
997 if (!isKnownToBeTypeSpecifier(NextToken()))
1000 case tok::r_brace: // struct bar { struct foo {...} }
1001 // Missing ';' at end of struct is accepted as an extension in C mode.
1002 if (!getLangOpts().CPlusPlus)
1009 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
1010 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
1011 /// until we reach the start of a definition or see a token that
1012 /// cannot start a definition.
1014 /// class-specifier: [C++ class]
1015 /// class-head '{' member-specification[opt] '}'
1016 /// class-head '{' member-specification[opt] '}' attributes[opt]
1018 /// class-key identifier[opt] base-clause[opt]
1019 /// class-key nested-name-specifier identifier base-clause[opt]
1020 /// class-key nested-name-specifier[opt] simple-template-id
1021 /// base-clause[opt]
1022 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
1023 /// [GNU] class-key attributes[opt] nested-name-specifier
1024 /// identifier base-clause[opt]
1025 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
1026 /// simple-template-id base-clause[opt]
1032 /// elaborated-type-specifier: [C++ dcl.type.elab]
1033 /// class-key ::[opt] nested-name-specifier[opt] identifier
1034 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
1035 /// simple-template-id
1037 /// Note that the C++ class-specifier and elaborated-type-specifier,
1038 /// together, subsume the C99 struct-or-union-specifier:
1040 /// struct-or-union-specifier: [C99 6.7.2.1]
1041 /// struct-or-union identifier[opt] '{' struct-contents '}'
1042 /// struct-or-union identifier
1043 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
1044 /// '}' attributes[opt]
1045 /// [GNU] struct-or-union attributes[opt] identifier
1046 /// struct-or-union:
1049 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
1050 SourceLocation StartLoc, DeclSpec &DS,
1051 const ParsedTemplateInfo &TemplateInfo,
1053 bool EnteringContext, DeclSpecContext DSC) {
1054 DeclSpec::TST TagType;
1055 if (TagTokKind == tok::kw_struct)
1056 TagType = DeclSpec::TST_struct;
1057 else if (TagTokKind == tok::kw___interface)
1058 TagType = DeclSpec::TST_interface;
1059 else if (TagTokKind == tok::kw_class)
1060 TagType = DeclSpec::TST_class;
1062 assert(TagTokKind == tok::kw_union && "Not a class specifier");
1063 TagType = DeclSpec::TST_union;
1066 if (Tok.is(tok::code_completion)) {
1067 // Code completion for a struct, class, or union name.
1068 Actions.CodeCompleteTag(getCurScope(), TagType);
1069 return cutOffParsing();
1072 // C++03 [temp.explicit] 14.7.2/8:
1073 // The usual access checking rules do not apply to names used to specify
1074 // explicit instantiations.
1076 // As an extension we do not perform access checking on the names used to
1077 // specify explicit specializations either. This is important to allow
1078 // specializing traits classes for private types.
1080 // Note that we don't suppress if this turns out to be an elaborated
1082 bool shouldDelayDiagsInTag =
1083 (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
1084 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
1085 SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
1087 ParsedAttributesWithRange attrs(AttrFactory);
1088 // If attributes exist after tag, parse them.
1089 if (Tok.is(tok::kw___attribute))
1090 ParseGNUAttributes(attrs);
1092 // If declspecs exist after tag, parse them.
1093 while (Tok.is(tok::kw___declspec))
1094 ParseMicrosoftDeclSpec(attrs);
1096 // Parse inheritance specifiers.
1097 if (Tok.is(tok::kw___single_inheritance) ||
1098 Tok.is(tok::kw___multiple_inheritance) ||
1099 Tok.is(tok::kw___virtual_inheritance))
1100 ParseMicrosoftInheritanceClassAttributes(attrs);
1102 // If C++0x attributes exist here, parse them.
1103 // FIXME: Are we consistent with the ordering of parsing of different
1104 // styles of attributes?
1105 MaybeParseCXX0XAttributes(attrs);
1107 if (TagType == DeclSpec::TST_struct &&
1108 !Tok.is(tok::identifier) &&
1109 Tok.getIdentifierInfo() &&
1110 (Tok.is(tok::kw___is_arithmetic) ||
1111 Tok.is(tok::kw___is_convertible) ||
1112 Tok.is(tok::kw___is_empty) ||
1113 Tok.is(tok::kw___is_floating_point) ||
1114 Tok.is(tok::kw___is_function) ||
1115 Tok.is(tok::kw___is_fundamental) ||
1116 Tok.is(tok::kw___is_integral) ||
1117 Tok.is(tok::kw___is_member_function_pointer) ||
1118 Tok.is(tok::kw___is_member_pointer) ||
1119 Tok.is(tok::kw___is_pod) ||
1120 Tok.is(tok::kw___is_pointer) ||
1121 Tok.is(tok::kw___is_same) ||
1122 Tok.is(tok::kw___is_scalar) ||
1123 Tok.is(tok::kw___is_signed) ||
1124 Tok.is(tok::kw___is_unsigned) ||
1125 Tok.is(tok::kw___is_void))) {
1126 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1127 // name of struct templates, but some are keywords in GCC >= 4.3
1128 // and Clang. Therefore, when we see the token sequence "struct
1129 // X", make X into a normal identifier rather than a keyword, to
1130 // allow libstdc++ 4.2 and libc++ to work properly.
1131 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1132 Tok.setKind(tok::identifier);
1135 // Parse the (optional) nested-name-specifier.
1136 CXXScopeSpec &SS = DS.getTypeSpecScope();
1137 if (getLangOpts().CPlusPlus) {
1138 // "FOO : BAR" is not a potential typo for "FOO::BAR".
1139 ColonProtectionRAIIObject X(*this);
1141 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1142 DS.SetTypeSpecError();
1144 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
1145 Diag(Tok, diag::err_expected_ident);
1148 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1150 // Parse the (optional) class name or simple-template-id.
1151 IdentifierInfo *Name = 0;
1152 SourceLocation NameLoc;
1153 TemplateIdAnnotation *TemplateId = 0;
1154 if (Tok.is(tok::identifier)) {
1155 Name = Tok.getIdentifierInfo();
1156 NameLoc = ConsumeToken();
1158 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1159 // The name was supposed to refer to a template, but didn't.
1160 // Eat the template argument list and try to continue parsing this as
1161 // a class (or template thereof).
1162 TemplateArgList TemplateArgs;
1163 SourceLocation LAngleLoc, RAngleLoc;
1164 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1166 TemplateArgs, RAngleLoc)) {
1167 // We couldn't parse the template argument list at all, so don't
1168 // try to give any location information for the list.
1169 LAngleLoc = RAngleLoc = SourceLocation();
1172 Diag(NameLoc, diag::err_explicit_spec_non_template)
1173 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1174 << (TagType == DeclSpec::TST_class? 0
1175 : TagType == DeclSpec::TST_struct? 1
1176 : TagType == DeclSpec::TST_interface? 2
1179 << SourceRange(LAngleLoc, RAngleLoc);
1181 // Strip off the last template parameter list if it was empty, since
1182 // we've removed its template argument list.
1183 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1184 if (TemplateParams && TemplateParams->size() > 1) {
1185 TemplateParams->pop_back();
1188 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1189 = ParsedTemplateInfo::NonTemplate;
1191 } else if (TemplateInfo.Kind
1192 == ParsedTemplateInfo::ExplicitInstantiation) {
1193 // Pretend this is just a forward declaration.
1195 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1196 = ParsedTemplateInfo::NonTemplate;
1197 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1199 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1203 } else if (Tok.is(tok::annot_template_id)) {
1204 TemplateId = takeTemplateIdAnnotation(Tok);
1205 NameLoc = ConsumeToken();
1207 if (TemplateId->Kind != TNK_Type_template &&
1208 TemplateId->Kind != TNK_Dependent_template_name) {
1209 // The template-name in the simple-template-id refers to
1210 // something other than a class template. Give an appropriate
1211 // error message and skip to the ';'.
1212 SourceRange Range(NameLoc);
1213 if (SS.isNotEmpty())
1214 Range.setBegin(SS.getBeginLoc());
1216 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1217 << Name << static_cast<int>(TemplateId->Kind) << Range;
1219 DS.SetTypeSpecError();
1220 SkipUntil(tok::semi, false, true);
1225 // There are four options here.
1226 // - If we are in a trailing return type, this is always just a reference,
1227 // and we must not try to parse a definition. For instance,
1228 // [] () -> struct S { };
1229 // does not define a type.
1230 // - If we have 'struct foo {...', 'struct foo :...',
1231 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1232 // - If we have 'struct foo;', then this is either a forward declaration
1233 // or a friend declaration, which have to be treated differently.
1234 // - Otherwise we have something like 'struct foo xyz', a reference.
1235 // However, in type-specifier-seq's, things look like declarations but are
1236 // just references, e.g.
1239 // &T::operator struct s;
1240 // For these, DSC is DSC_type_specifier.
1241 Sema::TagUseKind TUK;
1242 if (DSC == DSC_trailing)
1243 TUK = Sema::TUK_Reference;
1244 else if (Tok.is(tok::l_brace) ||
1245 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1246 (isCXX0XFinalKeyword() &&
1247 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1248 if (DS.isFriendSpecified()) {
1249 // C++ [class.friend]p2:
1250 // A class shall not be defined in a friend declaration.
1251 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1252 << SourceRange(DS.getFriendSpecLoc());
1254 // Skip everything up to the semicolon, so that this looks like a proper
1255 // friend class (or template thereof) declaration.
1256 SkipUntil(tok::semi, true, true);
1257 TUK = Sema::TUK_Friend;
1259 // Okay, this is a class definition.
1260 TUK = Sema::TUK_Definition;
1262 } else if (DSC != DSC_type_specifier &&
1263 (Tok.is(tok::semi) ||
1264 (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
1265 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1266 if (Tok.isNot(tok::semi)) {
1267 // A semicolon was missing after this declaration. Diagnose and recover.
1268 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1269 DeclSpec::getSpecifierName(TagType));
1271 Tok.setKind(tok::semi);
1274 TUK = Sema::TUK_Reference;
1276 // If this is an elaborated type specifier, and we delayed
1277 // diagnostics before, just merge them into the current pool.
1278 if (shouldDelayDiagsInTag) {
1279 diagsFromTag.done();
1280 if (TUK == Sema::TUK_Reference)
1281 diagsFromTag.redelay();
1284 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1285 TUK != Sema::TUK_Definition)) {
1286 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1287 // We have a declaration or reference to an anonymous class.
1288 Diag(StartLoc, diag::err_anon_type_definition)
1289 << DeclSpec::getSpecifierName(TagType);
1292 SkipUntil(tok::comma, true);
1296 // Create the tag portion of the class or class template.
1297 DeclResult TagOrTempResult = true; // invalid
1298 TypeResult TypeResult = true; // invalid
1302 // Explicit specialization, class template partial specialization,
1303 // or explicit instantiation.
1304 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1305 TemplateId->NumArgs);
1306 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1307 TUK == Sema::TUK_Declaration) {
1308 // This is an explicit instantiation of a class template.
1309 ProhibitAttributes(attrs);
1312 = Actions.ActOnExplicitInstantiation(getCurScope(),
1313 TemplateInfo.ExternLoc,
1314 TemplateInfo.TemplateLoc,
1318 TemplateId->Template,
1319 TemplateId->TemplateNameLoc,
1320 TemplateId->LAngleLoc,
1322 TemplateId->RAngleLoc,
1325 // Friend template-ids are treated as references unless
1326 // they have template headers, in which case they're ill-formed
1327 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1328 // We diagnose this error in ActOnClassTemplateSpecialization.
1329 } else if (TUK == Sema::TUK_Reference ||
1330 (TUK == Sema::TUK_Friend &&
1331 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1332 ProhibitAttributes(attrs);
1333 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1335 TemplateId->TemplateKWLoc,
1336 TemplateId->Template,
1337 TemplateId->TemplateNameLoc,
1338 TemplateId->LAngleLoc,
1340 TemplateId->RAngleLoc);
1342 // This is an explicit specialization or a class template
1343 // partial specialization.
1344 TemplateParameterLists FakedParamLists;
1346 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1347 // This looks like an explicit instantiation, because we have
1350 // template class Foo<X>
1352 // but it actually has a definition. Most likely, this was
1353 // meant to be an explicit specialization, but the user forgot
1354 // the '<>' after 'template'.
1355 assert(TUK == Sema::TUK_Definition && "Expected a definition here");
1357 SourceLocation LAngleLoc
1358 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1359 Diag(TemplateId->TemplateNameLoc,
1360 diag::err_explicit_instantiation_with_definition)
1361 << SourceRange(TemplateInfo.TemplateLoc)
1362 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1364 // Create a fake template parameter list that contains only
1365 // "template<>", so that we treat this construct as a class
1366 // template specialization.
1367 FakedParamLists.push_back(
1368 Actions.ActOnTemplateParameterList(0, SourceLocation(),
1369 TemplateInfo.TemplateLoc,
1373 TemplateParams = &FakedParamLists;
1376 // Build the class template specialization.
1378 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK,
1379 StartLoc, DS.getModulePrivateSpecLoc(), SS,
1380 TemplateId->Template,
1381 TemplateId->TemplateNameLoc,
1382 TemplateId->LAngleLoc,
1384 TemplateId->RAngleLoc,
1386 MultiTemplateParamsArg(
1387 TemplateParams? &(*TemplateParams)[0] : 0,
1388 TemplateParams? TemplateParams->size() : 0));
1390 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1391 TUK == Sema::TUK_Declaration) {
1392 // Explicit instantiation of a member of a class template
1393 // specialization, e.g.,
1395 // template struct Outer<int>::Inner;
1397 ProhibitAttributes(attrs);
1400 = Actions.ActOnExplicitInstantiation(getCurScope(),
1401 TemplateInfo.ExternLoc,
1402 TemplateInfo.TemplateLoc,
1403 TagType, StartLoc, SS, Name,
1404 NameLoc, attrs.getList());
1405 } else if (TUK == Sema::TUK_Friend &&
1406 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1407 ProhibitAttributes(attrs);
1410 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1411 TagType, StartLoc, SS,
1412 Name, NameLoc, attrs.getList(),
1413 MultiTemplateParamsArg(
1414 TemplateParams? &(*TemplateParams)[0] : 0,
1415 TemplateParams? TemplateParams->size() : 0));
1417 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1418 TUK == Sema::TUK_Definition) {
1419 // FIXME: Diagnose this particular error.
1422 if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
1423 ProhibitAttributes(attrs);
1425 bool IsDependent = false;
1427 // Don't pass down template parameter lists if this is just a tag
1428 // reference. For example, we don't need the template parameters here:
1429 // template <class T> class A *makeA(T t);
1430 MultiTemplateParamsArg TParams;
1431 if (TUK != Sema::TUK_Reference && TemplateParams)
1433 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1435 // Declaration or definition of a class type
1436 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1437 SS, Name, NameLoc, attrs.getList(), AS,
1438 DS.getModulePrivateSpecLoc(),
1439 TParams, Owned, IsDependent,
1440 SourceLocation(), false,
1441 clang::TypeResult());
1443 // If ActOnTag said the type was dependent, try again with the
1444 // less common call.
1446 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1447 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1448 SS, Name, StartLoc, NameLoc);
1452 // If there is a body, parse it and inform the actions module.
1453 if (TUK == Sema::TUK_Definition) {
1454 assert(Tok.is(tok::l_brace) ||
1455 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1456 isCXX0XFinalKeyword());
1457 if (getLangOpts().CPlusPlus)
1458 ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
1460 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1463 const char *PrevSpec = 0;
1466 if (!TypeResult.isInvalid()) {
1467 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1468 NameLoc.isValid() ? NameLoc : StartLoc,
1469 PrevSpec, DiagID, TypeResult.get());
1470 } else if (!TagOrTempResult.isInvalid()) {
1471 Result = DS.SetTypeSpecType(TagType, StartLoc,
1472 NameLoc.isValid() ? NameLoc : StartLoc,
1473 PrevSpec, DiagID, TagOrTempResult.get(), Owned);
1475 DS.SetTypeSpecError();
1480 Diag(StartLoc, DiagID) << PrevSpec;
1482 // At this point, we've successfully parsed a class-specifier in 'definition'
1483 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1484 // going to look at what comes after it to improve error recovery. If an
1485 // impossible token occurs next, we assume that the programmer forgot a ; at
1486 // the end of the declaration and recover that way.
1488 // Also enforce C++ [temp]p3:
1489 // In a template-declaration which defines a class, no declarator
1491 if (TUK == Sema::TUK_Definition &&
1492 (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
1493 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1494 DeclSpec::getSpecifierName(TagType));
1495 // Push this token back into the preprocessor and change our current token
1496 // to ';' so that the rest of the code recovers as though there were an
1497 // ';' after the definition.
1499 Tok.setKind(tok::semi);
1503 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1505 /// base-clause : [C++ class.derived]
1506 /// ':' base-specifier-list
1507 /// base-specifier-list:
1508 /// base-specifier '...'[opt]
1509 /// base-specifier-list ',' base-specifier '...'[opt]
1510 void Parser::ParseBaseClause(Decl *ClassDecl) {
1511 assert(Tok.is(tok::colon) && "Not a base clause");
1514 // Build up an array of parsed base specifiers.
1515 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1518 // Parse a base-specifier.
1519 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1520 if (Result.isInvalid()) {
1521 // Skip the rest of this base specifier, up until the comma or
1523 SkipUntil(tok::comma, tok::l_brace, true, true);
1525 // Add this to our array of base specifiers.
1526 BaseInfo.push_back(Result.get());
1529 // If the next token is a comma, consume it and keep reading
1531 if (Tok.isNot(tok::comma)) break;
1533 // Consume the comma.
1537 // Attach the base specifiers
1538 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1541 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1542 /// one entry in the base class list of a class specifier, for example:
1543 /// class foo : public bar, virtual private baz {
1544 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1546 /// base-specifier: [C++ class.derived]
1547 /// ::[opt] nested-name-specifier[opt] class-name
1548 /// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
1549 /// base-type-specifier
1550 /// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
1551 /// base-type-specifier
1552 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1553 bool IsVirtual = false;
1554 SourceLocation StartLoc = Tok.getLocation();
1556 // Parse the 'virtual' keyword.
1557 if (Tok.is(tok::kw_virtual)) {
1562 // Parse an (optional) access specifier.
1563 AccessSpecifier Access = getAccessSpecifierIfPresent();
1564 if (Access != AS_none)
1567 // Parse the 'virtual' keyword (again!), in case it came after the
1568 // access specifier.
1569 if (Tok.is(tok::kw_virtual)) {
1570 SourceLocation VirtualLoc = ConsumeToken();
1572 // Complain about duplicate 'virtual'
1573 Diag(VirtualLoc, diag::err_dup_virtual)
1574 << FixItHint::CreateRemoval(VirtualLoc);
1580 // Parse the class-name.
1581 SourceLocation EndLocation;
1582 SourceLocation BaseLoc;
1583 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1584 if (BaseType.isInvalid())
1587 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1588 // actually part of the base-specifier-list grammar productions, but we
1589 // parse it here for convenience.
1590 SourceLocation EllipsisLoc;
1591 if (Tok.is(tok::ellipsis))
1592 EllipsisLoc = ConsumeToken();
1594 // Find the complete source range for the base-specifier.
1595 SourceRange Range(StartLoc, EndLocation);
1597 // Notify semantic analysis that we have parsed a complete
1599 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
1600 BaseType.get(), BaseLoc, EllipsisLoc);
1603 /// getAccessSpecifierIfPresent - Determine whether the next token is
1604 /// a C++ access-specifier.
1606 /// access-specifier: [C++ class.derived]
1610 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1611 switch (Tok.getKind()) {
1612 default: return AS_none;
1613 case tok::kw_private: return AS_private;
1614 case tok::kw_protected: return AS_protected;
1615 case tok::kw_public: return AS_public;
1619 /// \brief If the given declarator has any parts for which parsing has to be
1620 /// delayed, e.g., default arguments, create a late-parsed method declaration
1621 /// record to handle the parsing at the end of the class definition.
1622 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1624 // We just declared a member function. If this member function
1625 // has any default arguments, we'll need to parse them later.
1626 LateParsedMethodDeclaration *LateMethod = 0;
1627 DeclaratorChunk::FunctionTypeInfo &FTI
1628 = DeclaratorInfo.getFunctionTypeInfo();
1630 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1631 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1633 // Push this method onto the stack of late-parsed method
1635 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1636 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1637 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1639 // Add all of the parameters prior to this one (they don't
1640 // have default arguments).
1641 LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1642 for (unsigned I = 0; I < ParamIdx; ++I)
1643 LateMethod->DefaultArgs.push_back(
1644 LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
1647 // Add this parameter to the list of parameters (it may or may
1648 // not have a default argument).
1649 LateMethod->DefaultArgs.push_back(
1650 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1651 FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1656 /// isCXX0XVirtSpecifier - Determine whether the given token is a C++0x
1662 VirtSpecifiers::Specifier Parser::isCXX0XVirtSpecifier(const Token &Tok) const {
1663 if (!getLangOpts().CPlusPlus)
1664 return VirtSpecifiers::VS_None;
1666 if (Tok.is(tok::identifier)) {
1667 IdentifierInfo *II = Tok.getIdentifierInfo();
1669 // Initialize the contextual keywords.
1671 Ident_final = &PP.getIdentifierTable().get("final");
1672 Ident_override = &PP.getIdentifierTable().get("override");
1675 if (II == Ident_override)
1676 return VirtSpecifiers::VS_Override;
1678 if (II == Ident_final)
1679 return VirtSpecifiers::VS_Final;
1682 return VirtSpecifiers::VS_None;
1685 /// ParseOptionalCXX0XVirtSpecifierSeq - Parse a virt-specifier-seq.
1687 /// virt-specifier-seq:
1689 /// virt-specifier-seq virt-specifier
1690 void Parser::ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS,
1693 VirtSpecifiers::Specifier Specifier = isCXX0XVirtSpecifier();
1694 if (Specifier == VirtSpecifiers::VS_None)
1697 // C++ [class.mem]p8:
1698 // A virt-specifier-seq shall contain at most one of each virt-specifier.
1699 const char *PrevSpec = 0;
1700 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
1701 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
1703 << FixItHint::CreateRemoval(Tok.getLocation());
1705 if (IsInterface && Specifier == VirtSpecifiers::VS_Final) {
1706 Diag(Tok.getLocation(), diag::err_override_control_interface)
1707 << VirtSpecifiers::getSpecifierName(Specifier);
1709 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
1710 diag::warn_cxx98_compat_override_control_keyword :
1711 diag::ext_override_control_keyword)
1712 << VirtSpecifiers::getSpecifierName(Specifier);
1718 /// isCXX0XFinalKeyword - Determine whether the next token is a C++0x
1719 /// contextual 'final' keyword.
1720 bool Parser::isCXX0XFinalKeyword() const {
1721 if (!getLangOpts().CPlusPlus)
1724 if (!Tok.is(tok::identifier))
1727 // Initialize the contextual keywords.
1729 Ident_final = &PP.getIdentifierTable().get("final");
1730 Ident_override = &PP.getIdentifierTable().get("override");
1733 return Tok.getIdentifierInfo() == Ident_final;
1736 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1738 /// member-declaration:
1739 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
1740 /// function-definition ';'[opt]
1741 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1742 /// using-declaration [TODO]
1743 /// [C++0x] static_assert-declaration
1744 /// template-declaration
1745 /// [GNU] '__extension__' member-declaration
1747 /// member-declarator-list:
1748 /// member-declarator
1749 /// member-declarator-list ',' member-declarator
1751 /// member-declarator:
1752 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
1753 /// declarator constant-initializer[opt]
1754 /// [C++11] declarator brace-or-equal-initializer[opt]
1755 /// identifier[opt] ':' constant-expression
1757 /// virt-specifier-seq:
1759 /// virt-specifier-seq virt-specifier
1768 /// constant-initializer:
1769 /// '=' constant-expression
1771 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1772 AttributeList *AccessAttrs,
1773 const ParsedTemplateInfo &TemplateInfo,
1774 ParsingDeclRAIIObject *TemplateDiags) {
1775 if (Tok.is(tok::at)) {
1776 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
1777 Diag(Tok, diag::err_at_defs_cxx);
1779 Diag(Tok, diag::err_at_in_class);
1782 SkipUntil(tok::r_brace);
1786 // Access declarations.
1787 bool MalformedTypeSpec = false;
1788 if (!TemplateInfo.Kind &&
1789 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon))) {
1790 if (TryAnnotateCXXScopeToken())
1791 MalformedTypeSpec = true;
1794 if (Tok.isNot(tok::annot_cxxscope))
1795 isAccessDecl = false;
1796 else if (NextToken().is(tok::identifier))
1797 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
1799 isAccessDecl = NextToken().is(tok::kw_operator);
1802 // Collect the scope specifier token we annotated earlier.
1804 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1805 /*EnteringContext=*/false);
1807 // Try to parse an unqualified-id.
1808 SourceLocation TemplateKWLoc;
1810 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
1811 TemplateKWLoc, Name)) {
1812 SkipUntil(tok::semi);
1816 // TODO: recover from mistakenly-qualified operator declarations.
1817 if (ExpectAndConsume(tok::semi,
1818 diag::err_expected_semi_after,
1819 "access declaration",
1823 Actions.ActOnUsingDeclaration(getCurScope(), AS,
1824 false, SourceLocation(),
1827 /* IsTypeName */ false,
1833 // static_assert-declaration
1834 if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) {
1835 // FIXME: Check for templates
1836 SourceLocation DeclEnd;
1837 ParseStaticAssertDeclaration(DeclEnd);
1841 if (Tok.is(tok::kw_template)) {
1842 assert(!TemplateInfo.TemplateParams &&
1843 "Nested template improperly parsed?");
1844 SourceLocation DeclEnd;
1845 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
1850 // Handle: member-declaration ::= '__extension__' member-declaration
1851 if (Tok.is(tok::kw___extension__)) {
1852 // __extension__ silences extension warnings in the subexpression.
1853 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1855 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
1856 TemplateInfo, TemplateDiags);
1859 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1861 ColonProtectionRAIIObject X(*this);
1863 ParsedAttributesWithRange attrs(AttrFactory);
1864 // Optional C++0x attribute-specifier
1865 MaybeParseCXX0XAttributes(attrs);
1866 MaybeParseMicrosoftAttributes(attrs);
1868 if (Tok.is(tok::kw_using)) {
1869 ProhibitAttributes(attrs);
1872 SourceLocation UsingLoc = ConsumeToken();
1874 if (Tok.is(tok::kw_namespace)) {
1875 Diag(UsingLoc, diag::err_using_namespace_in_class);
1876 SkipUntil(tok::semi, true, true);
1878 SourceLocation DeclEnd;
1879 // Otherwise, it must be a using-declaration or an alias-declaration.
1880 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
1881 UsingLoc, DeclEnd, AS);
1886 // Hold late-parsed attributes so we can attach a Decl to them later.
1887 LateParsedAttrList CommonLateParsedAttrs;
1889 // decl-specifier-seq:
1890 // Parse the common declaration-specifiers piece.
1891 ParsingDeclSpec DS(*this, TemplateDiags);
1892 DS.takeAttributesFrom(attrs);
1893 if (MalformedTypeSpec)
1894 DS.SetTypeSpecError();
1895 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
1896 &CommonLateParsedAttrs);
1898 MultiTemplateParamsArg TemplateParams(
1899 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
1900 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
1902 if (Tok.is(tok::semi)) {
1905 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
1906 DS.complete(TheDecl);
1910 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
1913 // Hold late-parsed attributes so we can attach a Decl to them later.
1914 LateParsedAttrList LateParsedAttrs;
1916 SourceLocation EqualLoc;
1917 bool HasInitializer = false;
1919 if (Tok.isNot(tok::colon)) {
1920 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1921 ColonProtectionRAIIObject X(*this);
1923 // Parse the first declarator.
1924 ParseDeclarator(DeclaratorInfo);
1925 // Error parsing the declarator?
1926 if (!DeclaratorInfo.hasName()) {
1927 // If so, skip until the semi-colon or a }.
1928 SkipUntil(tok::r_brace, true, true);
1929 if (Tok.is(tok::semi))
1934 ParseOptionalCXX0XVirtSpecifierSeq(VS, getCurrentClass().IsInterface);
1936 // If attributes exist after the declarator, but before an '{', parse them.
1937 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
1939 // MSVC permits pure specifier on inline functions declared at class scope.
1940 // Hence check for =0 before checking for function definition.
1941 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
1942 DeclaratorInfo.isFunctionDeclarator() &&
1943 NextToken().is(tok::numeric_constant)) {
1944 EqualLoc = ConsumeToken();
1945 Init = ParseInitializer();
1946 if (Init.isInvalid())
1947 SkipUntil(tok::comma, true, true);
1949 HasInitializer = true;
1952 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
1953 // function-definition:
1955 // In C++11, a non-function declarator followed by an open brace is a
1956 // braced-init-list for an in-class member initialization, not an
1957 // erroneous function definition.
1958 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus0x) {
1959 DefinitionKind = FDK_Definition;
1960 } else if (DeclaratorInfo.isFunctionDeclarator()) {
1961 if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
1962 DefinitionKind = FDK_Definition;
1963 } else if (Tok.is(tok::equal)) {
1964 const Token &KW = NextToken();
1965 if (KW.is(tok::kw_default))
1966 DefinitionKind = FDK_Defaulted;
1967 else if (KW.is(tok::kw_delete))
1968 DefinitionKind = FDK_Deleted;
1972 if (DefinitionKind) {
1973 if (!DeclaratorInfo.isFunctionDeclarator()) {
1974 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
1976 SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1978 // Consume the optional ';'
1979 if (Tok.is(tok::semi))
1984 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1985 Diag(DeclaratorInfo.getIdentifierLoc(),
1986 diag::err_function_declared_typedef);
1987 // This recovery skips the entire function body. It would be nice
1988 // to simply call ParseCXXInlineMethodDef() below, however Sema
1989 // assumes the declarator represents a function, not a typedef.
1991 SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1993 // Consume the optional ';'
1994 if (Tok.is(tok::semi))
2000 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
2001 VS, DefinitionKind, Init);
2003 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2004 CommonLateParsedAttrs[i]->addDecl(FunDecl);
2006 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2007 LateParsedAttrs[i]->addDecl(FunDecl);
2009 LateParsedAttrs.clear();
2011 // Consume the ';' - it's optional unless we have a delete or default
2012 if (Tok.is(tok::semi))
2013 ConsumeExtraSemi(AfterMemberFunctionDefinition);
2019 // member-declarator-list:
2020 // member-declarator
2021 // member-declarator-list ',' member-declarator
2023 SmallVector<Decl *, 8> DeclsInGroup;
2024 ExprResult BitfieldSize;
2025 bool ExpectSemi = true;
2028 // member-declarator:
2029 // declarator pure-specifier[opt]
2030 // declarator brace-or-equal-initializer[opt]
2031 // identifier[opt] ':' constant-expression
2032 if (Tok.is(tok::colon)) {
2034 BitfieldSize = ParseConstantExpression();
2035 if (BitfieldSize.isInvalid())
2036 SkipUntil(tok::comma, true, true);
2039 // If a simple-asm-expr is present, parse it.
2040 if (Tok.is(tok::kw_asm)) {
2042 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2043 if (AsmLabel.isInvalid())
2044 SkipUntil(tok::comma, true, true);
2046 DeclaratorInfo.setAsmLabel(AsmLabel.release());
2047 DeclaratorInfo.SetRangeEnd(Loc);
2050 // If attributes exist after the declarator, parse them.
2051 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
2053 // FIXME: When g++ adds support for this, we'll need to check whether it
2054 // goes before or after the GNU attributes and __asm__.
2055 ParseOptionalCXX0XVirtSpecifierSeq(VS, getCurrentClass().IsInterface);
2057 InClassInitStyle HasInClassInit = ICIS_NoInit;
2058 if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
2059 if (BitfieldSize.get()) {
2060 Diag(Tok, diag::err_bitfield_member_init);
2061 SkipUntil(tok::comma, true, true);
2063 HasInitializer = true;
2064 if (!DeclaratorInfo.isDeclarationOfFunction() &&
2065 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2066 != DeclSpec::SCS_static &&
2067 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2068 != DeclSpec::SCS_typedef)
2069 HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
2073 // NOTE: If Sema is the Action module and declarator is an instance field,
2074 // this call will *not* return the created decl; It will return null.
2075 // See Sema::ActOnCXXMemberDeclarator for details.
2078 if (DS.isFriendSpecified()) {
2079 // TODO: handle initializers, bitfields, 'delete'
2080 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2083 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2086 BitfieldSize.release(),
2087 VS, HasInClassInit);
2089 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs,
2093 // Set the Decl for any late parsed attributes
2094 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2095 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2097 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2098 LateParsedAttrs[i]->addDecl(ThisDecl);
2100 LateParsedAttrs.clear();
2102 // Handle the initializer.
2103 if (HasInClassInit != ICIS_NoInit) {
2104 // The initializer was deferred; parse it and cache the tokens.
2105 Diag(Tok, getLangOpts().CPlusPlus0x ?
2106 diag::warn_cxx98_compat_nonstatic_member_init :
2107 diag::ext_nonstatic_member_init);
2109 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2110 // C++11 [dcl.array]p3: An array bound may also be omitted when the
2111 // declarator is followed by an initializer.
2113 // A brace-or-equal-initializer for a member-declarator is not an
2114 // initializer in the grammar, so this is ill-formed.
2115 Diag(Tok, diag::err_incomplete_array_member_init);
2116 SkipUntil(tok::comma, true, true);
2118 // Avoid later warnings about a class member of incomplete type.
2119 ThisDecl->setInvalidDecl();
2121 ParseCXXNonStaticMemberInitializer(ThisDecl);
2122 } else if (HasInitializer) {
2123 // Normal initializer.
2124 if (!Init.isUsable())
2125 Init = ParseCXXMemberInitializer(ThisDecl,
2126 DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2128 if (Init.isInvalid())
2129 SkipUntil(tok::comma, true, true);
2131 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2132 DS.getTypeSpecType() == DeclSpec::TST_auto);
2133 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2135 Actions.ActOnUninitializedDecl(ThisDecl,
2136 DS.getTypeSpecType() == DeclSpec::TST_auto);
2140 Actions.FinalizeDeclaration(ThisDecl);
2141 DeclsInGroup.push_back(ThisDecl);
2144 if (ThisDecl && DeclaratorInfo.isFunctionDeclarator() &&
2145 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2146 != DeclSpec::SCS_typedef) {
2147 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2150 DeclaratorInfo.complete(ThisDecl);
2152 // If we don't have a comma, it is either the end of the list (a ';')
2153 // or an error, bail out.
2154 if (Tok.isNot(tok::comma))
2157 // Consume the comma.
2158 SourceLocation CommaLoc = ConsumeToken();
2160 if (Tok.isAtStartOfLine() &&
2161 !MightBeDeclarator(Declarator::MemberContext)) {
2162 // This comma was followed by a line-break and something which can't be
2163 // the start of a declarator. The comma was probably a typo for a
2165 Diag(CommaLoc, diag::err_expected_semi_declaration)
2166 << FixItHint::CreateReplacement(CommaLoc, ";");
2171 // Parse the next declarator.
2172 DeclaratorInfo.clear();
2174 BitfieldSize = true;
2176 HasInitializer = false;
2177 DeclaratorInfo.setCommaLoc(CommaLoc);
2179 // Attributes are only allowed on the second declarator.
2180 MaybeParseGNUAttributes(DeclaratorInfo);
2182 if (Tok.isNot(tok::colon))
2183 ParseDeclarator(DeclaratorInfo);
2187 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2188 // Skip to end of block or statement.
2189 SkipUntil(tok::r_brace, true, true);
2190 // If we stopped at a ';', eat it.
2191 if (Tok.is(tok::semi)) ConsumeToken();
2195 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(),
2196 DeclsInGroup.size());
2199 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
2200 /// pure-specifier. Also detect and reject any attempted defaulted/deleted
2201 /// function definition. The location of the '=', if any, will be placed in
2207 /// brace-or-equal-initializer:
2208 /// '=' initializer-expression
2209 /// braced-init-list
2211 /// initializer-clause:
2212 /// assignment-expression
2213 /// braced-init-list
2215 /// defaulted/deleted function-definition:
2219 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2220 /// be a constant-expression.
2221 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2222 SourceLocation &EqualLoc) {
2223 assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
2224 && "Data member initializer not starting with '=' or '{'");
2226 EnterExpressionEvaluationContext Context(Actions,
2227 Sema::PotentiallyEvaluated,
2229 if (Tok.is(tok::equal)) {
2230 EqualLoc = ConsumeToken();
2231 if (Tok.is(tok::kw_delete)) {
2232 // In principle, an initializer of '= delete p;' is legal, but it will
2233 // never type-check. It's better to diagnose it as an ill-formed expression
2234 // than as an ill-formed deleted non-function member.
2235 // An initializer of '= delete p, foo' will never be parsed, because
2236 // a top-level comma always ends the initializer expression.
2237 const Token &Next = NextToken();
2238 if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) ||
2239 Next.is(tok::eof)) {
2241 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2244 Diag(ConsumeToken(), diag::err_deleted_non_function);
2245 return ExprResult();
2247 } else if (Tok.is(tok::kw_default)) {
2249 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2252 Diag(ConsumeToken(), diag::err_default_special_members);
2253 return ExprResult();
2257 return ParseInitializer();
2260 /// ParseCXXMemberSpecification - Parse the class definition.
2262 /// member-specification:
2263 /// member-declaration member-specification[opt]
2264 /// access-specifier ':' member-specification[opt]
2266 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2267 unsigned TagType, Decl *TagDecl) {
2268 assert((TagType == DeclSpec::TST_struct ||
2269 TagType == DeclSpec::TST_interface ||
2270 TagType == DeclSpec::TST_union ||
2271 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2273 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2274 "parsing struct/union/class body");
2276 // Determine whether this is a non-nested class. Note that local
2277 // classes are *not* considered to be nested classes.
2278 bool NonNestedClass = true;
2279 if (!ClassStack.empty()) {
2280 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2281 if (S->isClassScope()) {
2282 // We're inside a class scope, so this is a nested class.
2283 NonNestedClass = false;
2285 // The Microsoft extension __interface does not permit nested classes.
2286 if (getCurrentClass().IsInterface) {
2287 Diag(RecordLoc, diag::err_invalid_member_in_interface)
2289 << (isa<NamedDecl>(TagDecl)
2290 ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
2296 if ((S->getFlags() & Scope::FnScope)) {
2297 // If we're in a function or function template declared in the
2298 // body of a class, then this is a local class rather than a
2300 const Scope *Parent = S->getParent();
2301 if (Parent->isTemplateParamScope())
2302 Parent = Parent->getParent();
2303 if (Parent->isClassScope())
2309 // Enter a scope for the class.
2310 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2312 // Note that we are parsing a new (potentially-nested) class definition.
2313 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
2314 TagType == DeclSpec::TST_interface);
2317 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2319 SourceLocation FinalLoc;
2321 // Parse the optional 'final' keyword.
2322 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2323 assert(isCXX0XFinalKeyword() && "not a class definition");
2324 FinalLoc = ConsumeToken();
2326 if (TagType == DeclSpec::TST_interface) {
2327 Diag(FinalLoc, diag::err_override_control_interface)
2330 Diag(FinalLoc, getLangOpts().CPlusPlus0x ?
2331 diag::warn_cxx98_compat_override_control_keyword :
2332 diag::ext_override_control_keyword) << "final";
2336 if (Tok.is(tok::colon)) {
2337 ParseBaseClause(TagDecl);
2339 if (!Tok.is(tok::l_brace)) {
2340 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
2343 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2348 assert(Tok.is(tok::l_brace));
2349 BalancedDelimiterTracker T(*this, tok::l_brace);
2353 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2354 T.getOpenLocation());
2356 // C++ 11p3: Members of a class defined with the keyword class are private
2357 // by default. Members of a class defined with the keywords struct or union
2358 // are public by default.
2359 AccessSpecifier CurAS;
2360 if (TagType == DeclSpec::TST_class)
2364 ParsedAttributes AccessAttrs(AttrFactory);
2367 // While we still have something to read, read the member-declarations.
2368 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2369 // Each iteration of this loop reads one member-declaration.
2371 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
2372 Tok.is(tok::kw___if_not_exists))) {
2373 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2377 // Check for extraneous top-level semicolon.
2378 if (Tok.is(tok::semi)) {
2379 ConsumeExtraSemi(InsideStruct, TagType);
2383 if (Tok.is(tok::annot_pragma_vis)) {
2384 HandlePragmaVisibility();
2388 if (Tok.is(tok::annot_pragma_pack)) {
2393 if (Tok.is(tok::annot_pragma_align)) {
2394 HandlePragmaAlign();
2398 AccessSpecifier AS = getAccessSpecifierIfPresent();
2399 if (AS != AS_none) {
2400 // Current token is a C++ access specifier.
2402 SourceLocation ASLoc = Tok.getLocation();
2403 unsigned TokLength = Tok.getLength();
2405 AccessAttrs.clear();
2406 MaybeParseGNUAttributes(AccessAttrs);
2408 SourceLocation EndLoc;
2409 if (Tok.is(tok::colon)) {
2410 EndLoc = Tok.getLocation();
2412 } else if (Tok.is(tok::semi)) {
2413 EndLoc = Tok.getLocation();
2415 Diag(EndLoc, diag::err_expected_colon)
2416 << FixItHint::CreateReplacement(EndLoc, ":");
2418 EndLoc = ASLoc.getLocWithOffset(TokLength);
2419 Diag(EndLoc, diag::err_expected_colon)
2420 << FixItHint::CreateInsertion(EndLoc, ":");
2423 // The Microsoft extension __interface does not permit non-public
2424 // access specifiers.
2425 if (TagType == DeclSpec::TST_interface && CurAS != AS_public) {
2426 Diag(ASLoc, diag::err_access_specifier_interface)
2427 << (CurAS == AS_protected);
2430 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
2431 AccessAttrs.getList())) {
2432 // found another attribute than only annotations
2433 AccessAttrs.clear();
2439 // FIXME: Make sure we don't have a template here.
2441 // Parse all the comma separated declarators.
2442 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
2447 SkipUntil(tok::r_brace, false, false);
2450 // If attributes exist after class contents, parse them.
2451 ParsedAttributes attrs(AttrFactory);
2452 MaybeParseGNUAttributes(attrs);
2455 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
2456 T.getOpenLocation(),
2457 T.getCloseLocation(),
2460 // C++11 [class.mem]p2:
2461 // Within the class member-specification, the class is regarded as complete
2462 // within function bodies, default arguments, and
2463 // brace-or-equal-initializers for non-static data members (including such
2464 // things in nested classes).
2465 if (TagDecl && NonNestedClass) {
2466 // We are not inside a nested class. This class and its nested classes
2467 // are complete and we can parse the delayed portions of method
2468 // declarations and the lexed inline method definitions, along with any
2469 // delayed attributes.
2470 SourceLocation SavedPrevTokLocation = PrevTokLocation;
2471 ParseLexedAttributes(getCurrentClass());
2472 ParseLexedMethodDeclarations(getCurrentClass());
2474 // We've finished with all pending member declarations.
2475 Actions.ActOnFinishCXXMemberDecls();
2477 ParseLexedMemberInitializers(getCurrentClass());
2478 ParseLexedMethodDefs(getCurrentClass());
2479 PrevTokLocation = SavedPrevTokLocation;
2483 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
2484 T.getCloseLocation());
2486 // Leave the class scope.
2491 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
2492 /// which explicitly initializes the members or base classes of a
2493 /// class (C++ [class.base.init]). For example, the three initializers
2494 /// after the ':' in the Derived constructor below:
2498 /// class Derived : Base {
2502 /// Derived(float f) : Base(), x(17), f(f) { }
2506 /// [C++] ctor-initializer:
2507 /// ':' mem-initializer-list
2509 /// [C++] mem-initializer-list:
2510 /// mem-initializer ...[opt]
2511 /// mem-initializer ...[opt] , mem-initializer-list
2512 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
2513 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
2515 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers
2516 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
2517 SourceLocation ColonLoc = ConsumeToken();
2519 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
2520 bool AnyErrors = false;
2523 if (Tok.is(tok::code_completion)) {
2524 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
2525 MemInitializers.data(),
2526 MemInitializers.size());
2527 return cutOffParsing();
2529 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
2530 if (!MemInit.isInvalid())
2531 MemInitializers.push_back(MemInit.get());
2536 if (Tok.is(tok::comma))
2538 else if (Tok.is(tok::l_brace))
2540 // If the next token looks like a base or member initializer, assume that
2541 // we're just missing a comma.
2542 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
2543 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2544 Diag(Loc, diag::err_ctor_init_missing_comma)
2545 << FixItHint::CreateInsertion(Loc, ", ");
2547 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2548 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
2549 SkipUntil(tok::l_brace, true, true);
2554 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
2555 MemInitializers.data(), MemInitializers.size(),
2559 /// ParseMemInitializer - Parse a C++ member initializer, which is
2560 /// part of a constructor initializer that explicitly initializes one
2561 /// member or base class (C++ [class.base.init]). See
2562 /// ParseConstructorInitializer for an example.
2564 /// [C++] mem-initializer:
2565 /// mem-initializer-id '(' expression-list[opt] ')'
2566 /// [C++0x] mem-initializer-id braced-init-list
2568 /// [C++] mem-initializer-id:
2569 /// '::'[opt] nested-name-specifier[opt] class-name
2571 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
2572 // parse '::'[opt] nested-name-specifier[opt]
2574 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
2575 ParsedType TemplateTypeTy;
2576 if (Tok.is(tok::annot_template_id)) {
2577 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2578 if (TemplateId->Kind == TNK_Type_template ||
2579 TemplateId->Kind == TNK_Dependent_template_name) {
2580 AnnotateTemplateIdTokenAsType();
2581 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
2582 TemplateTypeTy = getTypeAnnotation(Tok);
2585 // Uses of decltype will already have been converted to annot_decltype by
2586 // ParseOptionalCXXScopeSpecifier at this point.
2587 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
2588 && Tok.isNot(tok::annot_decltype)) {
2589 Diag(Tok, diag::err_expected_member_or_base_name);
2593 IdentifierInfo *II = 0;
2594 DeclSpec DS(AttrFactory);
2595 SourceLocation IdLoc = Tok.getLocation();
2596 if (Tok.is(tok::annot_decltype)) {
2597 // Get the decltype expression, if there is one.
2598 ParseDecltypeSpecifier(DS);
2600 if (Tok.is(tok::identifier))
2601 // Get the identifier. This may be a member name or a class name,
2602 // but we'll let the semantic analysis determine which it is.
2603 II = Tok.getIdentifierInfo();
2609 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
2610 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2612 ExprResult InitList = ParseBraceInitializer();
2613 if (InitList.isInvalid())
2616 SourceLocation EllipsisLoc;
2617 if (Tok.is(tok::ellipsis))
2618 EllipsisLoc = ConsumeToken();
2620 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2621 TemplateTypeTy, DS, IdLoc,
2622 InitList.take(), EllipsisLoc);
2623 } else if(Tok.is(tok::l_paren)) {
2624 BalancedDelimiterTracker T(*this, tok::l_paren);
2627 // Parse the optional expression-list.
2628 ExprVector ArgExprs;
2629 CommaLocsTy CommaLocs;
2630 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
2631 SkipUntil(tok::r_paren);
2637 SourceLocation EllipsisLoc;
2638 if (Tok.is(tok::ellipsis))
2639 EllipsisLoc = ConsumeToken();
2641 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2642 TemplateTypeTy, DS, IdLoc,
2643 T.getOpenLocation(), ArgExprs.data(),
2644 ArgExprs.size(), T.getCloseLocation(),
2648 Diag(Tok, getLangOpts().CPlusPlus0x ? diag::err_expected_lparen_or_lbrace
2649 : diag::err_expected_lparen);
2653 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
2655 /// exception-specification:
2656 /// dynamic-exception-specification
2657 /// noexcept-specification
2659 /// noexcept-specification:
2661 /// 'noexcept' '(' constant-expression ')'
2662 ExceptionSpecificationType
2663 Parser::tryParseExceptionSpecification(
2664 SourceRange &SpecificationRange,
2665 SmallVectorImpl<ParsedType> &DynamicExceptions,
2666 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2667 ExprResult &NoexceptExpr) {
2668 ExceptionSpecificationType Result = EST_None;
2670 // See if there's a dynamic specification.
2671 if (Tok.is(tok::kw_throw)) {
2672 Result = ParseDynamicExceptionSpecification(SpecificationRange,
2674 DynamicExceptionRanges);
2675 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
2676 "Produced different number of exception types and ranges.");
2679 // If there's no noexcept specification, we're done.
2680 if (Tok.isNot(tok::kw_noexcept))
2683 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
2685 // If we already had a dynamic specification, parse the noexcept for,
2686 // recovery, but emit a diagnostic and don't store the results.
2687 SourceRange NoexceptRange;
2688 ExceptionSpecificationType NoexceptType = EST_None;
2690 SourceLocation KeywordLoc = ConsumeToken();
2691 if (Tok.is(tok::l_paren)) {
2692 // There is an argument.
2693 BalancedDelimiterTracker T(*this, tok::l_paren);
2695 NoexceptType = EST_ComputedNoexcept;
2696 NoexceptExpr = ParseConstantExpression();
2697 // The argument must be contextually convertible to bool. We use
2698 // ActOnBooleanCondition for this purpose.
2699 if (!NoexceptExpr.isInvalid())
2700 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
2701 NoexceptExpr.get());
2703 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
2705 // There is no argument.
2706 NoexceptType = EST_BasicNoexcept;
2707 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
2710 if (Result == EST_None) {
2711 SpecificationRange = NoexceptRange;
2712 Result = NoexceptType;
2714 // If there's a dynamic specification after a noexcept specification,
2715 // parse that and ignore the results.
2716 if (Tok.is(tok::kw_throw)) {
2717 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2718 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
2719 DynamicExceptionRanges);
2722 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2728 /// ParseDynamicExceptionSpecification - Parse a C++
2729 /// dynamic-exception-specification (C++ [except.spec]).
2731 /// dynamic-exception-specification:
2732 /// 'throw' '(' type-id-list [opt] ')'
2733 /// [MS] 'throw' '(' '...' ')'
2736 /// type-id ... [opt]
2737 /// type-id-list ',' type-id ... [opt]
2739 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
2740 SourceRange &SpecificationRange,
2741 SmallVectorImpl<ParsedType> &Exceptions,
2742 SmallVectorImpl<SourceRange> &Ranges) {
2743 assert(Tok.is(tok::kw_throw) && "expected throw");
2745 SpecificationRange.setBegin(ConsumeToken());
2746 BalancedDelimiterTracker T(*this, tok::l_paren);
2747 if (T.consumeOpen()) {
2748 Diag(Tok, diag::err_expected_lparen_after) << "throw";
2749 SpecificationRange.setEnd(SpecificationRange.getBegin());
2750 return EST_DynamicNone;
2753 // Parse throw(...), a Microsoft extension that means "this function
2754 // can throw anything".
2755 if (Tok.is(tok::ellipsis)) {
2756 SourceLocation EllipsisLoc = ConsumeToken();
2757 if (!getLangOpts().MicrosoftExt)
2758 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
2760 SpecificationRange.setEnd(T.getCloseLocation());
2764 // Parse the sequence of type-ids.
2766 while (Tok.isNot(tok::r_paren)) {
2767 TypeResult Res(ParseTypeName(&Range));
2769 if (Tok.is(tok::ellipsis)) {
2770 // C++0x [temp.variadic]p5:
2771 // - In a dynamic-exception-specification (15.4); the pattern is a
2773 SourceLocation Ellipsis = ConsumeToken();
2774 Range.setEnd(Ellipsis);
2775 if (!Res.isInvalid())
2776 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
2779 if (!Res.isInvalid()) {
2780 Exceptions.push_back(Res.get());
2781 Ranges.push_back(Range);
2784 if (Tok.is(tok::comma))
2791 SpecificationRange.setEnd(T.getCloseLocation());
2792 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
2795 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
2796 /// function declaration.
2797 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
2798 assert(Tok.is(tok::arrow) && "expected arrow");
2802 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
2805 /// \brief We have just started parsing the definition of a new class,
2806 /// so push that class onto our stack of classes that is currently
2808 Sema::ParsingClassState
2809 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
2811 assert((NonNestedClass || !ClassStack.empty()) &&
2812 "Nested class without outer class");
2813 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
2814 return Actions.PushParsingClass();
2817 /// \brief Deallocate the given parsed class and all of its nested
2819 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
2820 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
2821 delete Class->LateParsedDeclarations[I];
2825 /// \brief Pop the top class of the stack of classes that are
2826 /// currently being parsed.
2828 /// This routine should be called when we have finished parsing the
2829 /// definition of a class, but have not yet popped the Scope
2830 /// associated with the class's definition.
2831 void Parser::PopParsingClass(Sema::ParsingClassState state) {
2832 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
2834 Actions.PopParsingClass(state);
2836 ParsingClass *Victim = ClassStack.top();
2838 if (Victim->TopLevelClass) {
2839 // Deallocate all of the nested classes of this class,
2840 // recursively: we don't need to keep any of this information.
2841 DeallocateParsedClasses(Victim);
2844 assert(!ClassStack.empty() && "Missing top-level class?");
2846 if (Victim->LateParsedDeclarations.empty()) {
2847 // The victim is a nested class, but we will not need to perform
2848 // any processing after the definition of this class since it has
2849 // no members whose handling was delayed. Therefore, we can just
2850 // remove this nested class.
2851 DeallocateParsedClasses(Victim);
2855 // This nested class has some members that will need to be processed
2856 // after the top-level class is completely defined. Therefore, add
2857 // it to the list of nested classes within its parent.
2858 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
2859 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
2860 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
2863 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
2865 /// \return the parsed identifier on success, and 0 if the next token is not an
2866 /// attribute-token.
2868 /// C++11 [dcl.attr.grammar]p3:
2869 /// If a keyword or an alternative token that satisfies the syntactic
2870 /// requirements of an identifier is contained in an attribute-token,
2871 /// it is considered an identifier.
2872 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
2873 switch (Tok.getKind()) {
2875 // Identifiers and keywords have identifier info attached.
2876 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
2877 Loc = ConsumeToken();
2882 case tok::ampamp: // 'and'
2883 case tok::pipe: // 'bitor'
2884 case tok::pipepipe: // 'or'
2885 case tok::caret: // 'xor'
2886 case tok::tilde: // 'compl'
2887 case tok::amp: // 'bitand'
2888 case tok::ampequal: // 'and_eq'
2889 case tok::pipeequal: // 'or_eq'
2890 case tok::caretequal: // 'xor_eq'
2891 case tok::exclaim: // 'not'
2892 case tok::exclaimequal: // 'not_eq'
2893 // Alternative tokens do not have identifier info, but their spelling
2894 // starts with an alphabetical character.
2895 llvm::SmallString<8> SpellingBuf;
2896 StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf);
2897 if (std::isalpha(Spelling[0])) {
2898 Loc = ConsumeToken();
2899 return &PP.getIdentifierTable().get(Spelling);
2905 static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
2906 IdentifierInfo *ScopeName) {
2907 switch (AttributeList::getKind(AttrName, ScopeName,
2908 AttributeList::AS_CXX11)) {
2909 case AttributeList::AT_CarriesDependency:
2910 case AttributeList::AT_FallThrough:
2911 case AttributeList::AT_NoReturn: {
2920 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Currently
2921 /// only parses standard attributes.
2923 /// [C++11] attribute-specifier:
2924 /// '[' '[' attribute-list ']' ']'
2925 /// alignment-specifier
2927 /// [C++11] attribute-list:
2929 /// attribute-list ',' attribute[opt]
2931 /// attribute-list ',' attribute '...'
2933 /// [C++11] attribute:
2934 /// attribute-token attribute-argument-clause[opt]
2936 /// [C++11] attribute-token:
2938 /// attribute-scoped-token
2940 /// [C++11] attribute-scoped-token:
2941 /// attribute-namespace '::' identifier
2943 /// [C++11] attribute-namespace:
2946 /// [C++11] attribute-argument-clause:
2947 /// '(' balanced-token-seq ')'
2949 /// [C++11] balanced-token-seq:
2951 /// balanced-token-seq balanced-token
2953 /// [C++11] balanced-token:
2954 /// '(' balanced-token-seq ')'
2955 /// '[' balanced-token-seq ']'
2956 /// '{' balanced-token-seq '}'
2957 /// any token but '(', ')', '[', ']', '{', or '}'
2958 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2959 SourceLocation *endLoc) {
2960 if (Tok.is(tok::kw_alignas)) {
2961 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
2962 ParseAlignmentSpecifier(attrs, endLoc);
2966 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
2967 && "Not a C++11 attribute list");
2969 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
2974 while (Tok.isNot(tok::r_square)) {
2975 // attribute not present
2976 if (Tok.is(tok::comma)) {
2981 SourceLocation ScopeLoc, AttrLoc;
2982 IdentifierInfo *ScopeName = 0, *AttrName = 0;
2984 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
2986 // Break out to the "expected ']'" diagnostic.
2990 if (Tok.is(tok::coloncolon)) {
2993 ScopeName = AttrName;
2996 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
2998 Diag(Tok.getLocation(), diag::err_expected_ident);
2999 SkipUntil(tok::r_square, tok::comma, true, true);
3004 bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName,ScopeName);
3005 bool AttrParsed = false;
3007 // Parse attribute arguments
3008 if (Tok.is(tok::l_paren)) {
3009 if (ScopeName && ScopeName->getName() == "gnu") {
3010 ParseGNUAttributeArgs(AttrName, AttrLoc, attrs, endLoc,
3011 ScopeName, ScopeLoc, AttributeList::AS_CXX11);
3015 Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_arguments)
3016 << AttrName->getName();
3018 // FIXME: handle other formats of c++11 attribute arguments
3020 SkipUntil(tok::r_paren, false);
3025 attrs.addNew(AttrName,
3026 SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc,
3028 ScopeName, ScopeLoc, 0,
3029 SourceLocation(), 0, 0, AttributeList::AS_CXX11);
3031 if (Tok.is(tok::ellipsis)) {
3034 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
3035 << AttrName->getName();
3039 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
3040 SkipUntil(tok::r_square, false);
3042 *endLoc = Tok.getLocation();
3043 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
3044 SkipUntil(tok::r_square, false);
3047 /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq.
3049 /// attribute-specifier-seq:
3050 /// attribute-specifier-seq[opt] attribute-specifier
3051 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
3052 SourceLocation *endLoc) {
3053 SourceLocation StartLoc = Tok.getLocation(), Loc;
3058 ParseCXX11AttributeSpecifier(attrs, endLoc);
3059 } while (isCXX11AttributeSpecifier());
3061 attrs.Range = SourceRange(StartLoc, *endLoc);
3064 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
3066 /// [MS] ms-attribute:
3067 /// '[' token-seq ']'
3069 /// [MS] ms-attribute-seq:
3070 /// ms-attribute[opt]
3071 /// ms-attribute ms-attribute-seq
3072 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3073 SourceLocation *endLoc) {
3074 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3076 while (Tok.is(tok::l_square)) {
3077 // FIXME: If this is actually a C++11 attribute, parse it as one.
3079 SkipUntil(tok::r_square, true, true);
3080 if (endLoc) *endLoc = Tok.getLocation();
3081 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare);
3085 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3086 AccessSpecifier& CurAS) {
3087 IfExistsCondition Result;
3088 if (ParseMicrosoftIfExistsCondition(Result))
3091 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3092 if (Braces.consumeOpen()) {
3093 Diag(Tok, diag::err_expected_lbrace);
3097 switch (Result.Behavior) {
3099 // Parse the declarations below.
3103 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3104 << Result.IsIfExists;
3105 // Fall through to skip.
3112 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
3113 // __if_exists, __if_not_exists can nest.
3114 if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
3115 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3119 // Check for extraneous top-level semicolon.
3120 if (Tok.is(tok::semi)) {
3121 ConsumeExtraSemi(InsideStruct, TagType);
3125 AccessSpecifier AS = getAccessSpecifierIfPresent();
3126 if (AS != AS_none) {
3127 // Current token is a C++ access specifier.
3129 SourceLocation ASLoc = Tok.getLocation();
3131 if (Tok.is(tok::colon))
3132 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3134 Diag(Tok, diag::err_expected_colon);
3139 // Parse all the comma separated declarators.
3140 ParseCXXClassMemberDeclaration(CurAS, 0);
3143 Braces.consumeClose();