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 "llvm/ADT/SmallString.h"
22 #include "RAIIObjectsForParser.h"
23 using namespace clang;
25 /// ParseNamespace - We know that the current token is a namespace keyword. This
26 /// may either be a top level namespace or a block-level namespace alias. If
27 /// there was an inline keyword, it has already been parsed.
29 /// namespace-definition: [C++ 7.3: basic.namespace]
30 /// named-namespace-definition
31 /// unnamed-namespace-definition
33 /// unnamed-namespace-definition:
34 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
36 /// named-namespace-definition:
37 /// original-namespace-definition
38 /// extension-namespace-definition
40 /// original-namespace-definition:
41 /// 'inline'[opt] 'namespace' identifier attributes[opt]
42 /// '{' namespace-body '}'
44 /// extension-namespace-definition:
45 /// 'inline'[opt] 'namespace' original-namespace-name
46 /// '{' namespace-body '}'
48 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
49 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
51 Decl *Parser::ParseNamespace(unsigned Context,
52 SourceLocation &DeclEnd,
53 SourceLocation InlineLoc) {
54 assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
55 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
56 ObjCDeclContextSwitch ObjCDC(*this);
58 if (Tok.is(tok::code_completion)) {
59 Actions.CodeCompleteNamespaceDecl(getCurScope());
64 SourceLocation IdentLoc;
65 IdentifierInfo *Ident = 0;
66 std::vector<SourceLocation> ExtraIdentLoc;
67 std::vector<IdentifierInfo*> ExtraIdent;
68 std::vector<SourceLocation> ExtraNamespaceLoc;
72 if (Tok.is(tok::identifier)) {
73 Ident = Tok.getIdentifierInfo();
74 IdentLoc = ConsumeToken(); // eat the identifier.
75 while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) {
76 ExtraNamespaceLoc.push_back(ConsumeToken());
77 ExtraIdent.push_back(Tok.getIdentifierInfo());
78 ExtraIdentLoc.push_back(ConsumeToken());
82 // Read label attributes, if present.
83 ParsedAttributes attrs(AttrFactory);
84 if (Tok.is(tok::kw___attribute)) {
86 ParseGNUAttributes(attrs);
89 if (Tok.is(tok::equal)) {
91 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias);
92 if (InlineLoc.isValid())
93 Diag(InlineLoc, diag::err_inline_namespace_alias)
94 << FixItHint::CreateRemoval(InlineLoc);
95 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
99 BalancedDelimiterTracker T(*this, tok::l_brace);
100 if (T.consumeOpen()) {
101 if (!ExtraIdent.empty()) {
102 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
103 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
105 Diag(Tok, Ident ? diag::err_expected_lbrace :
106 diag::err_expected_ident_lbrace);
110 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
111 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
112 getCurScope()->getFnParent()) {
113 if (!ExtraIdent.empty()) {
114 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
115 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
117 Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
118 SkipUntil(tok::r_brace, false);
122 if (!ExtraIdent.empty()) {
123 TentativeParsingAction TPA(*this);
124 SkipUntil(tok::r_brace, /*StopAtSemi*/false, /*DontConsume*/true);
125 Token rBraceToken = Tok;
128 if (!rBraceToken.is(tok::r_brace)) {
129 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
130 << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back());
132 std::string NamespaceFix;
133 for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(),
134 E = ExtraIdent.end(); I != E; ++I) {
135 NamespaceFix += " { namespace ";
136 NamespaceFix += (*I)->getName();
140 for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i)
143 Diag(ExtraNamespaceLoc[0], diag::err_nested_namespaces_with_double_colon)
144 << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(),
145 ExtraIdentLoc.back()),
147 << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
151 // If we're still good, complain about inline namespaces in non-C++0x now.
152 if (InlineLoc.isValid())
153 Diag(InlineLoc, getLangOpts().CPlusPlus0x ?
154 diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
156 // Enter a scope for the namespace.
157 ParseScope NamespaceScope(this, Scope::DeclScope);
160 Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc,
161 IdentLoc, Ident, T.getOpenLocation(),
164 PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc,
165 "parsing namespace");
167 // Parse the contents of the namespace. This includes parsing recovery on
168 // any improperly nested namespaces.
169 ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0,
170 InlineLoc, attrs, T);
172 // Leave the namespace scope.
173 NamespaceScope.Exit();
175 DeclEnd = T.getCloseLocation();
176 Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
181 /// ParseInnerNamespace - Parse the contents of a namespace.
182 void Parser::ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
183 std::vector<IdentifierInfo*>& Ident,
184 std::vector<SourceLocation>& NamespaceLoc,
185 unsigned int index, SourceLocation& InlineLoc,
186 ParsedAttributes& attrs,
187 BalancedDelimiterTracker &Tracker) {
188 if (index == Ident.size()) {
189 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
190 ParsedAttributesWithRange attrs(AttrFactory);
191 MaybeParseCXX0XAttributes(attrs);
192 MaybeParseMicrosoftAttributes(attrs);
193 ParseExternalDeclaration(attrs);
196 // The caller is what called check -- we are simply calling
198 Tracker.consumeClose();
203 // Parse improperly nested namespaces.
204 ParseScope NamespaceScope(this, Scope::DeclScope);
206 Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(),
207 NamespaceLoc[index], IdentLoc[index],
208 Ident[index], Tracker.getOpenLocation(),
211 ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc,
214 NamespaceScope.Exit();
216 Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
219 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
220 /// alias definition.
222 Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
223 SourceLocation AliasLoc,
224 IdentifierInfo *Alias,
225 SourceLocation &DeclEnd) {
226 assert(Tok.is(tok::equal) && "Not equal token");
228 ConsumeToken(); // eat the '='.
230 if (Tok.is(tok::code_completion)) {
231 Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
237 // Parse (optional) nested-name-specifier.
238 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
240 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
241 Diag(Tok, diag::err_expected_namespace_name);
242 // Skip to end of the definition and eat the ';'.
243 SkipUntil(tok::semi);
248 IdentifierInfo *Ident = Tok.getIdentifierInfo();
249 SourceLocation IdentLoc = ConsumeToken();
252 DeclEnd = Tok.getLocation();
253 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name,
256 return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias,
257 SS, IdentLoc, Ident);
260 /// ParseLinkage - We know that the current token is a string_literal
261 /// and just before that, that extern was seen.
263 /// linkage-specification: [C++ 7.5p2: dcl.link]
264 /// 'extern' string-literal '{' declaration-seq[opt] '}'
265 /// 'extern' string-literal declaration
267 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
268 assert(Tok.is(tok::string_literal) && "Not a string literal!");
269 SmallString<8> LangBuffer;
270 bool Invalid = false;
271 StringRef Lang = PP.getSpelling(Tok, LangBuffer, &Invalid);
275 // FIXME: This is incorrect: linkage-specifiers are parsed in translation
276 // phase 7, so string-literal concatenation is supposed to occur.
277 // extern "" "C" "" "+" "+" { } is legal.
278 if (Tok.hasUDSuffix())
279 Diag(Tok, diag::err_invalid_string_udl);
280 SourceLocation Loc = ConsumeStringToken();
282 ParseScope LinkageScope(this, Scope::DeclScope);
284 = Actions.ActOnStartLinkageSpecification(getCurScope(),
285 DS.getSourceRange().getBegin(),
287 Tok.is(tok::l_brace) ? Tok.getLocation()
290 ParsedAttributesWithRange attrs(AttrFactory);
291 MaybeParseCXX0XAttributes(attrs);
292 MaybeParseMicrosoftAttributes(attrs);
294 if (Tok.isNot(tok::l_brace)) {
295 // Reset the source range in DS, as the leading "extern"
296 // does not really belong to the inner declaration ...
297 DS.SetRangeStart(SourceLocation());
298 DS.SetRangeEnd(SourceLocation());
299 // ... but anyway remember that such an "extern" was seen.
300 DS.setExternInLinkageSpec(true);
301 ParseExternalDeclaration(attrs, &DS);
302 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
308 ProhibitAttributes(attrs);
310 BalancedDelimiterTracker T(*this, tok::l_brace);
312 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
313 ParsedAttributesWithRange attrs(AttrFactory);
314 MaybeParseCXX0XAttributes(attrs);
315 MaybeParseMicrosoftAttributes(attrs);
316 ParseExternalDeclaration(attrs);
320 return Actions.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec,
321 T.getCloseLocation());
324 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
325 /// using-directive. Assumes that current token is 'using'.
326 Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context,
327 const ParsedTemplateInfo &TemplateInfo,
328 SourceLocation &DeclEnd,
329 ParsedAttributesWithRange &attrs,
331 assert(Tok.is(tok::kw_using) && "Not using token");
332 ObjCDeclContextSwitch ObjCDC(*this);
335 SourceLocation UsingLoc = ConsumeToken();
337 if (Tok.is(tok::code_completion)) {
338 Actions.CodeCompleteUsing(getCurScope());
343 // 'using namespace' means this is a using-directive.
344 if (Tok.is(tok::kw_namespace)) {
345 // Template parameters are always an error here.
346 if (TemplateInfo.Kind) {
347 SourceRange R = TemplateInfo.getSourceRange();
348 Diag(UsingLoc, diag::err_templated_using_directive)
349 << R << FixItHint::CreateRemoval(R);
352 return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
355 // Otherwise, it must be a using-declaration or an alias-declaration.
357 // Using declarations can't have attributes.
358 ProhibitAttributes(attrs);
360 return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd,
364 /// ParseUsingDirective - Parse C++ using-directive, assumes
365 /// that current token is 'namespace' and 'using' was already parsed.
367 /// using-directive: [C++ 7.3.p4: namespace.udir]
368 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
370 /// [GNU] using-directive:
371 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
372 /// namespace-name attributes[opt] ;
374 Decl *Parser::ParseUsingDirective(unsigned Context,
375 SourceLocation UsingLoc,
376 SourceLocation &DeclEnd,
377 ParsedAttributes &attrs) {
378 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
381 SourceLocation NamespcLoc = ConsumeToken();
383 if (Tok.is(tok::code_completion)) {
384 Actions.CodeCompleteUsingDirective(getCurScope());
390 // Parse (optional) nested-name-specifier.
391 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
393 IdentifierInfo *NamespcName = 0;
394 SourceLocation IdentLoc = SourceLocation();
396 // Parse namespace-name.
397 if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
398 Diag(Tok, diag::err_expected_namespace_name);
399 // If there was invalid namespace name, skip to end of decl, and eat ';'.
400 SkipUntil(tok::semi);
401 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
406 NamespcName = Tok.getIdentifierInfo();
407 IdentLoc = ConsumeToken();
409 // Parse (optional) attributes (most likely GNU strong-using extension).
410 bool GNUAttr = false;
411 if (Tok.is(tok::kw___attribute)) {
413 ParseGNUAttributes(attrs);
417 DeclEnd = Tok.getLocation();
418 ExpectAndConsume(tok::semi,
419 GNUAttr ? diag::err_expected_semi_after_attribute_list
420 : diag::err_expected_semi_after_namespace_name,
423 return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
424 IdentLoc, NamespcName, attrs.getList());
427 /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
428 /// Assumes that 'using' was already seen.
430 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
431 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
433 /// 'using' :: unqualified-id
435 /// alias-declaration: C++0x [decl.typedef]p2
436 /// 'using' identifier = type-id ;
438 Decl *Parser::ParseUsingDeclaration(unsigned Context,
439 const ParsedTemplateInfo &TemplateInfo,
440 SourceLocation UsingLoc,
441 SourceLocation &DeclEnd,
445 SourceLocation TypenameLoc;
448 // Ignore optional 'typename'.
449 // FIXME: This is wrong; we should parse this as a typename-specifier.
450 if (Tok.is(tok::kw_typename)) {
451 TypenameLoc = Tok.getLocation();
458 // Parse nested-name-specifier.
459 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
461 // Check nested-name specifier.
462 if (SS.isInvalid()) {
463 SkipUntil(tok::semi);
467 // Parse the unqualified-id. We allow parsing of both constructor and
468 // destructor names and allow the action module to diagnose any semantic
470 SourceLocation TemplateKWLoc;
472 if (ParseUnqualifiedId(SS,
473 /*EnteringContext=*/false,
474 /*AllowDestructorName=*/true,
475 /*AllowConstructorName=*/true,
479 SkipUntil(tok::semi);
483 ParsedAttributes attrs(AttrFactory);
485 // Maybe this is an alias-declaration.
486 bool IsAliasDecl = Tok.is(tok::equal);
487 TypeResult TypeAlias;
489 // TODO: Attribute support. C++0x attributes may appear before the equals.
490 // Where can GNU attributes appear?
493 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
494 diag::warn_cxx98_compat_alias_declaration :
495 diag::ext_alias_declaration);
497 // Type alias templates cannot be specialized.
499 if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
500 Name.getKind() == UnqualifiedId::IK_TemplateId)
502 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
504 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
506 if (SpecKind != -1) {
509 Range = SourceRange(Name.TemplateId->LAngleLoc,
510 Name.TemplateId->RAngleLoc);
512 Range = TemplateInfo.getSourceRange();
513 Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
514 << SpecKind << Range;
515 SkipUntil(tok::semi);
519 // Name must be an identifier.
520 if (Name.getKind() != UnqualifiedId::IK_Identifier) {
521 Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier);
522 // No removal fixit: can't recover from this.
523 SkipUntil(tok::semi);
525 } else if (IsTypeName)
526 Diag(TypenameLoc, diag::err_alias_declaration_not_identifier)
527 << FixItHint::CreateRemoval(SourceRange(TypenameLoc,
528 SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc));
529 else if (SS.isNotEmpty())
530 Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
531 << FixItHint::CreateRemoval(SS.getRange());
533 TypeAlias = ParseTypeName(0, TemplateInfo.Kind ?
534 Declarator::AliasTemplateContext :
535 Declarator::AliasDeclContext, AS, OwnedType);
537 // Parse (optional) attributes (most likely GNU strong-using extension).
538 MaybeParseGNUAttributes(attrs);
541 DeclEnd = Tok.getLocation();
542 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
543 !attrs.empty() ? "attributes list" :
544 IsAliasDecl ? "alias declaration" : "using declaration",
547 // Diagnose an attempt to declare a templated using-declaration.
548 // In C++0x, alias-declarations can be templates:
549 // template <...> using id = type;
550 if (TemplateInfo.Kind && !IsAliasDecl) {
551 SourceRange R = TemplateInfo.getSourceRange();
552 Diag(UsingLoc, diag::err_templated_using_declaration)
553 << R << FixItHint::CreateRemoval(R);
555 // Unfortunately, we have to bail out instead of recovering by
556 // ignoring the parameters, just in case the nested name specifier
557 // depends on the parameters.
561 // "typename" keyword is allowed for identifiers only,
562 // because it may be a type definition.
563 if (IsTypeName && Name.getKind() != UnqualifiedId::IK_Identifier) {
564 Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only)
565 << FixItHint::CreateRemoval(SourceRange(TypenameLoc));
566 // Proceed parsing, but reset the IsTypeName flag.
571 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
572 MultiTemplateParamsArg TemplateParamsArg(Actions,
573 TemplateParams ? TemplateParams->data() : 0,
574 TemplateParams ? TemplateParams->size() : 0);
575 return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
576 UsingLoc, Name, TypeAlias);
579 return Actions.ActOnUsingDeclaration(getCurScope(), AS, true, UsingLoc, SS,
580 Name, attrs.getList(),
581 IsTypeName, TypenameLoc);
584 /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
586 /// [C++0x] static_assert-declaration:
587 /// static_assert ( constant-expression , string-literal ) ;
589 /// [C11] static_assert-declaration:
590 /// _Static_assert ( constant-expression , string-literal ) ;
592 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
593 assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) &&
594 "Not a static_assert declaration");
596 if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
597 Diag(Tok, diag::ext_c11_static_assert);
598 if (Tok.is(tok::kw_static_assert))
599 Diag(Tok, diag::warn_cxx98_compat_static_assert);
601 SourceLocation StaticAssertLoc = ConsumeToken();
603 BalancedDelimiterTracker T(*this, tok::l_paren);
604 if (T.consumeOpen()) {
605 Diag(Tok, diag::err_expected_lparen);
609 ExprResult AssertExpr(ParseConstantExpression());
610 if (AssertExpr.isInvalid()) {
611 SkipUntil(tok::semi);
615 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi))
618 if (!isTokenStringLiteral()) {
619 Diag(Tok, diag::err_expected_string_literal);
620 SkipUntil(tok::semi);
624 ExprResult AssertMessage(ParseStringLiteralExpression());
625 if (AssertMessage.isInvalid()) {
626 SkipUntil(tok::semi);
632 DeclEnd = Tok.getLocation();
633 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
635 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
637 AssertMessage.take(),
638 T.getCloseLocation());
641 /// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
643 /// 'decltype' ( expression )
645 SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
646 assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
647 && "Not a decltype specifier");
651 SourceLocation StartLoc = Tok.getLocation();
652 SourceLocation EndLoc;
654 if (Tok.is(tok::annot_decltype)) {
655 Result = getExprAnnotation(Tok);
656 EndLoc = Tok.getAnnotationEndLoc();
658 if (Result.isInvalid()) {
659 DS.SetTypeSpecError();
663 if (Tok.getIdentifierInfo()->isStr("decltype"))
664 Diag(Tok, diag::warn_cxx98_compat_decltype);
668 BalancedDelimiterTracker T(*this, tok::l_paren);
669 if (T.expectAndConsume(diag::err_expected_lparen_after,
670 "decltype", tok::r_paren)) {
671 DS.SetTypeSpecError();
672 return T.getOpenLocation() == Tok.getLocation() ?
673 StartLoc : T.getOpenLocation();
676 // Parse the expression
678 // C++0x [dcl.type.simple]p4:
679 // The operand of the decltype specifier is an unevaluated operand.
680 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
681 0, /*IsDecltype=*/true);
682 Result = ParseExpression();
683 if (Result.isInvalid()) {
684 SkipUntil(tok::r_paren);
685 DS.SetTypeSpecError();
691 if (T.getCloseLocation().isInvalid()) {
692 DS.SetTypeSpecError();
693 // FIXME: this should return the location of the last token
694 // that was consumed (by "consumeClose()")
695 return T.getCloseLocation();
698 Result = Actions.ActOnDecltypeExpression(Result.take());
699 if (Result.isInvalid()) {
700 DS.SetTypeSpecError();
701 return T.getCloseLocation();
704 EndLoc = T.getCloseLocation();
707 const char *PrevSpec = 0;
709 // Check for duplicate type specifiers (e.g. "int decltype(a)").
710 if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
711 DiagID, Result.release())) {
712 Diag(StartLoc, DiagID) << PrevSpec;
713 DS.SetTypeSpecError();
718 void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
719 SourceLocation StartLoc,
720 SourceLocation EndLoc) {
721 // make sure we have a token we can turn into an annotation token
722 if (PP.isBacktrackEnabled())
723 PP.RevertCachedTokens(1);
727 Tok.setKind(tok::annot_decltype);
728 setExprAnnotation(Tok, DS.getTypeSpecType() == TST_decltype ?
729 DS.getRepAsExpr() : ExprResult());
730 Tok.setAnnotationEndLoc(EndLoc);
731 Tok.setLocation(StartLoc);
732 PP.AnnotateCachedTokens(Tok);
735 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
736 assert(Tok.is(tok::kw___underlying_type) &&
737 "Not an underlying type specifier");
739 SourceLocation StartLoc = ConsumeToken();
740 BalancedDelimiterTracker T(*this, tok::l_paren);
741 if (T.expectAndConsume(diag::err_expected_lparen_after,
742 "__underlying_type", tok::r_paren)) {
746 TypeResult Result = ParseTypeName();
747 if (Result.isInvalid()) {
748 SkipUntil(tok::r_paren);
754 if (T.getCloseLocation().isInvalid())
757 const char *PrevSpec = 0;
759 if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
760 DiagID, Result.release()))
761 Diag(StartLoc, DiagID) << PrevSpec;
764 /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
765 /// class name or decltype-specifier. Note that we only check that the result
766 /// names a type; semantic analysis will need to verify that the type names a
767 /// class. The result is either a type or null, depending on whether a type
770 /// base-type-specifier: [C++ 10.1]
771 /// class-or-decltype
772 /// class-or-decltype: [C++ 10.1]
773 /// nested-name-specifier[opt] class-name
774 /// decltype-specifier
775 /// class-name: [C++ 9.1]
777 /// simple-template-id
779 Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
780 SourceLocation &EndLocation) {
781 // Ignore attempts to use typename
782 if (Tok.is(tok::kw_typename)) {
783 Diag(Tok, diag::err_expected_class_name_not_template)
784 << FixItHint::CreateRemoval(Tok.getLocation());
788 // Parse optional nested-name-specifier
790 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
792 BaseLoc = Tok.getLocation();
794 // Parse decltype-specifier
795 // tok == kw_decltype is just error recovery, it can only happen when SS
797 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
799 Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
800 << FixItHint::CreateRemoval(SS.getRange());
801 // Fake up a Declarator to use with ActOnTypeName.
802 DeclSpec DS(AttrFactory);
804 EndLocation = ParseDecltypeSpecifier(DS);
806 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
807 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
810 // Check whether we have a template-id that names a type.
811 if (Tok.is(tok::annot_template_id)) {
812 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
813 if (TemplateId->Kind == TNK_Type_template ||
814 TemplateId->Kind == TNK_Dependent_template_name) {
815 AnnotateTemplateIdTokenAsType();
817 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
818 ParsedType Type = getTypeAnnotation(Tok);
819 EndLocation = Tok.getAnnotationEndLoc();
827 // Fall through to produce an error below.
830 if (Tok.isNot(tok::identifier)) {
831 Diag(Tok, diag::err_expected_class_name);
835 IdentifierInfo *Id = Tok.getIdentifierInfo();
836 SourceLocation IdLoc = ConsumeToken();
838 if (Tok.is(tok::less)) {
839 // It looks the user intended to write a template-id here, but the
840 // template-name was wrong. Try to fix that.
841 TemplateNameKind TNK = TNK_Type_template;
843 if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
844 &SS, Template, TNK)) {
845 Diag(IdLoc, diag::err_unknown_template_name)
852 // Form the template name
853 UnqualifiedId TemplateName;
854 TemplateName.setIdentifier(Id, IdLoc);
856 // Parse the full template-id, then turn it into a type.
857 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
860 if (TNK == TNK_Dependent_template_name)
861 AnnotateTemplateIdTokenAsType();
863 // If we didn't end up with a typename token, there's nothing more we
865 if (Tok.isNot(tok::annot_typename))
868 // Retrieve the type from the annotation token, consume that token, and
870 EndLocation = Tok.getAnnotationEndLoc();
871 ParsedType Type = getTypeAnnotation(Tok);
876 // We have an identifier; check whether it is actually a type.
877 ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true,
879 /*IsCtorOrDtorName=*/false,
880 /*NonTrivialTypeSourceInfo=*/true);
882 Diag(IdLoc, diag::err_expected_class_name);
886 // Consume the identifier.
889 // Fake up a Declarator to use with ActOnTypeName.
890 DeclSpec DS(AttrFactory);
891 DS.SetRangeStart(IdLoc);
892 DS.SetRangeEnd(EndLocation);
893 DS.getTypeSpecScope() = SS;
895 const char *PrevSpec = 0;
897 DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type);
899 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
900 return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
903 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
904 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
905 /// until we reach the start of a definition or see a token that
906 /// cannot start a definition.
908 /// class-specifier: [C++ class]
909 /// class-head '{' member-specification[opt] '}'
910 /// class-head '{' member-specification[opt] '}' attributes[opt]
912 /// class-key identifier[opt] base-clause[opt]
913 /// class-key nested-name-specifier identifier base-clause[opt]
914 /// class-key nested-name-specifier[opt] simple-template-id
916 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
917 /// [GNU] class-key attributes[opt] nested-name-specifier
918 /// identifier base-clause[opt]
919 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
920 /// simple-template-id base-clause[opt]
926 /// elaborated-type-specifier: [C++ dcl.type.elab]
927 /// class-key ::[opt] nested-name-specifier[opt] identifier
928 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
929 /// simple-template-id
931 /// Note that the C++ class-specifier and elaborated-type-specifier,
932 /// together, subsume the C99 struct-or-union-specifier:
934 /// struct-or-union-specifier: [C99 6.7.2.1]
935 /// struct-or-union identifier[opt] '{' struct-contents '}'
936 /// struct-or-union identifier
937 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
938 /// '}' attributes[opt]
939 /// [GNU] struct-or-union attributes[opt] identifier
943 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
944 SourceLocation StartLoc, DeclSpec &DS,
945 const ParsedTemplateInfo &TemplateInfo,
947 bool EnteringContext, DeclSpecContext DSC) {
948 DeclSpec::TST TagType;
949 if (TagTokKind == tok::kw_struct)
950 TagType = DeclSpec::TST_struct;
951 else if (TagTokKind == tok::kw_class)
952 TagType = DeclSpec::TST_class;
954 assert(TagTokKind == tok::kw_union && "Not a class specifier");
955 TagType = DeclSpec::TST_union;
958 if (Tok.is(tok::code_completion)) {
959 // Code completion for a struct, class, or union name.
960 Actions.CodeCompleteTag(getCurScope(), TagType);
961 return cutOffParsing();
964 // C++03 [temp.explicit] 14.7.2/8:
965 // The usual access checking rules do not apply to names used to specify
966 // explicit instantiations.
968 // As an extension we do not perform access checking on the names used to
969 // specify explicit specializations either. This is important to allow
970 // specializing traits classes for private types.
971 Sema::SuppressAccessChecksRAII SuppressAccess(Actions,
972 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
973 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
975 ParsedAttributes attrs(AttrFactory);
976 // If attributes exist after tag, parse them.
977 if (Tok.is(tok::kw___attribute))
978 ParseGNUAttributes(attrs);
980 // If declspecs exist after tag, parse them.
981 while (Tok.is(tok::kw___declspec))
982 ParseMicrosoftDeclSpec(attrs);
984 // If C++0x attributes exist here, parse them.
985 // FIXME: Are we consistent with the ordering of parsing of different
986 // styles of attributes?
987 MaybeParseCXX0XAttributes(attrs);
989 if (TagType == DeclSpec::TST_struct &&
990 !Tok.is(tok::identifier) &&
991 Tok.getIdentifierInfo() &&
992 (Tok.is(tok::kw___is_arithmetic) ||
993 Tok.is(tok::kw___is_convertible) ||
994 Tok.is(tok::kw___is_empty) ||
995 Tok.is(tok::kw___is_floating_point) ||
996 Tok.is(tok::kw___is_function) ||
997 Tok.is(tok::kw___is_fundamental) ||
998 Tok.is(tok::kw___is_integral) ||
999 Tok.is(tok::kw___is_member_function_pointer) ||
1000 Tok.is(tok::kw___is_member_pointer) ||
1001 Tok.is(tok::kw___is_pod) ||
1002 Tok.is(tok::kw___is_pointer) ||
1003 Tok.is(tok::kw___is_same) ||
1004 Tok.is(tok::kw___is_scalar) ||
1005 Tok.is(tok::kw___is_signed) ||
1006 Tok.is(tok::kw___is_unsigned) ||
1007 Tok.is(tok::kw___is_void))) {
1008 // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
1009 // name of struct templates, but some are keywords in GCC >= 4.3
1010 // and Clang. Therefore, when we see the token sequence "struct
1011 // X", make X into a normal identifier rather than a keyword, to
1012 // allow libstdc++ 4.2 and libc++ to work properly.
1013 Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
1014 Tok.setKind(tok::identifier);
1017 // Parse the (optional) nested-name-specifier.
1018 CXXScopeSpec &SS = DS.getTypeSpecScope();
1019 if (getLangOpts().CPlusPlus) {
1020 // "FOO : BAR" is not a potential typo for "FOO::BAR".
1021 ColonProtectionRAIIObject X(*this);
1023 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
1024 DS.SetTypeSpecError();
1026 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
1027 Diag(Tok, diag::err_expected_ident);
1030 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
1032 // Parse the (optional) class name or simple-template-id.
1033 IdentifierInfo *Name = 0;
1034 SourceLocation NameLoc;
1035 TemplateIdAnnotation *TemplateId = 0;
1036 if (Tok.is(tok::identifier)) {
1037 Name = Tok.getIdentifierInfo();
1038 NameLoc = ConsumeToken();
1040 if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
1041 // The name was supposed to refer to a template, but didn't.
1042 // Eat the template argument list and try to continue parsing this as
1043 // a class (or template thereof).
1044 TemplateArgList TemplateArgs;
1045 SourceLocation LAngleLoc, RAngleLoc;
1046 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS,
1048 TemplateArgs, RAngleLoc)) {
1049 // We couldn't parse the template argument list at all, so don't
1050 // try to give any location information for the list.
1051 LAngleLoc = RAngleLoc = SourceLocation();
1054 Diag(NameLoc, diag::err_explicit_spec_non_template)
1055 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
1056 << (TagType == DeclSpec::TST_class? 0
1057 : TagType == DeclSpec::TST_struct? 1
1060 << SourceRange(LAngleLoc, RAngleLoc);
1062 // Strip off the last template parameter list if it was empty, since
1063 // we've removed its template argument list.
1064 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
1065 if (TemplateParams && TemplateParams->size() > 1) {
1066 TemplateParams->pop_back();
1069 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1070 = ParsedTemplateInfo::NonTemplate;
1072 } else if (TemplateInfo.Kind
1073 == ParsedTemplateInfo::ExplicitInstantiation) {
1074 // Pretend this is just a forward declaration.
1076 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind
1077 = ParsedTemplateInfo::NonTemplate;
1078 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc
1080 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc
1084 } else if (Tok.is(tok::annot_template_id)) {
1085 TemplateId = takeTemplateIdAnnotation(Tok);
1086 NameLoc = ConsumeToken();
1088 if (TemplateId->Kind != TNK_Type_template &&
1089 TemplateId->Kind != TNK_Dependent_template_name) {
1090 // The template-name in the simple-template-id refers to
1091 // something other than a class template. Give an appropriate
1092 // error message and skip to the ';'.
1093 SourceRange Range(NameLoc);
1094 if (SS.isNotEmpty())
1095 Range.setBegin(SS.getBeginLoc());
1097 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
1098 << Name << static_cast<int>(TemplateId->Kind) << Range;
1100 DS.SetTypeSpecError();
1101 SkipUntil(tok::semi, false, true);
1106 // As soon as we're finished parsing the class's template-id, turn access
1107 // checking back on.
1108 SuppressAccess.done();
1110 // There are four options here.
1111 // - If we are in a trailing return type, this is always just a reference,
1112 // and we must not try to parse a definition. For instance,
1113 // [] () -> struct S { };
1114 // does not define a type.
1115 // - If we have 'struct foo {...', 'struct foo :...',
1116 // 'struct foo final :' or 'struct foo final {', then this is a definition.
1117 // - If we have 'struct foo;', then this is either a forward declaration
1118 // or a friend declaration, which have to be treated differently.
1119 // - Otherwise we have something like 'struct foo xyz', a reference.
1120 // However, in type-specifier-seq's, things look like declarations but are
1121 // just references, e.g.
1124 // &T::operator struct s;
1125 // For these, DSC is DSC_type_specifier.
1126 Sema::TagUseKind TUK;
1127 if (DSC == DSC_trailing)
1128 TUK = Sema::TUK_Reference;
1129 else if (Tok.is(tok::l_brace) ||
1130 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1131 (isCXX0XFinalKeyword() &&
1132 (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
1133 if (DS.isFriendSpecified()) {
1134 // C++ [class.friend]p2:
1135 // A class shall not be defined in a friend declaration.
1136 Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
1137 << SourceRange(DS.getFriendSpecLoc());
1139 // Skip everything up to the semicolon, so that this looks like a proper
1140 // friend class (or template thereof) declaration.
1141 SkipUntil(tok::semi, true, true);
1142 TUK = Sema::TUK_Friend;
1144 // Okay, this is a class definition.
1145 TUK = Sema::TUK_Definition;
1147 } else if (Tok.is(tok::semi) && DSC != DSC_type_specifier)
1148 TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
1150 TUK = Sema::TUK_Reference;
1152 if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
1153 TUK != Sema::TUK_Definition)) {
1154 if (DS.getTypeSpecType() != DeclSpec::TST_error) {
1155 // We have a declaration or reference to an anonymous class.
1156 Diag(StartLoc, diag::err_anon_type_definition)
1157 << DeclSpec::getSpecifierName(TagType);
1160 SkipUntil(tok::comma, true);
1164 // Create the tag portion of the class or class template.
1165 DeclResult TagOrTempResult = true; // invalid
1166 TypeResult TypeResult = true; // invalid
1170 // Explicit specialization, class template partial specialization,
1171 // or explicit instantiation.
1172 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
1173 TemplateId->getTemplateArgs(),
1174 TemplateId->NumArgs);
1175 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1176 TUK == Sema::TUK_Declaration) {
1177 // This is an explicit instantiation of a class template.
1179 = Actions.ActOnExplicitInstantiation(getCurScope(),
1180 TemplateInfo.ExternLoc,
1181 TemplateInfo.TemplateLoc,
1185 TemplateId->Template,
1186 TemplateId->TemplateNameLoc,
1187 TemplateId->LAngleLoc,
1189 TemplateId->RAngleLoc,
1192 // Friend template-ids are treated as references unless
1193 // they have template headers, in which case they're ill-formed
1194 // (FIXME: "template <class T> friend class A<T>::B<int>;").
1195 // We diagnose this error in ActOnClassTemplateSpecialization.
1196 } else if (TUK == Sema::TUK_Reference ||
1197 (TUK == Sema::TUK_Friend &&
1198 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
1199 TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
1201 TemplateId->TemplateKWLoc,
1202 TemplateId->Template,
1203 TemplateId->TemplateNameLoc,
1204 TemplateId->LAngleLoc,
1206 TemplateId->RAngleLoc);
1208 // This is an explicit specialization or a class template
1209 // partial specialization.
1210 TemplateParameterLists FakedParamLists;
1212 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
1213 // This looks like an explicit instantiation, because we have
1216 // template class Foo<X>
1218 // but it actually has a definition. Most likely, this was
1219 // meant to be an explicit specialization, but the user forgot
1220 // the '<>' after 'template'.
1221 assert(TUK == Sema::TUK_Definition && "Expected a definition here");
1223 SourceLocation LAngleLoc
1224 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
1225 Diag(TemplateId->TemplateNameLoc,
1226 diag::err_explicit_instantiation_with_definition)
1227 << SourceRange(TemplateInfo.TemplateLoc)
1228 << FixItHint::CreateInsertion(LAngleLoc, "<>");
1230 // Create a fake template parameter list that contains only
1231 // "template<>", so that we treat this construct as a class
1232 // template specialization.
1233 FakedParamLists.push_back(
1234 Actions.ActOnTemplateParameterList(0, SourceLocation(),
1235 TemplateInfo.TemplateLoc,
1239 TemplateParams = &FakedParamLists;
1242 // Build the class template specialization.
1244 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK,
1245 StartLoc, DS.getModulePrivateSpecLoc(), SS,
1246 TemplateId->Template,
1247 TemplateId->TemplateNameLoc,
1248 TemplateId->LAngleLoc,
1250 TemplateId->RAngleLoc,
1252 MultiTemplateParamsArg(Actions,
1253 TemplateParams? &(*TemplateParams)[0] : 0,
1254 TemplateParams? TemplateParams->size() : 0));
1256 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1257 TUK == Sema::TUK_Declaration) {
1258 // Explicit instantiation of a member of a class template
1259 // specialization, e.g.,
1261 // template struct Outer<int>::Inner;
1264 = Actions.ActOnExplicitInstantiation(getCurScope(),
1265 TemplateInfo.ExternLoc,
1266 TemplateInfo.TemplateLoc,
1267 TagType, StartLoc, SS, Name,
1268 NameLoc, attrs.getList());
1269 } else if (TUK == Sema::TUK_Friend &&
1270 TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
1272 Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(),
1273 TagType, StartLoc, SS,
1274 Name, NameLoc, attrs.getList(),
1275 MultiTemplateParamsArg(Actions,
1276 TemplateParams? &(*TemplateParams)[0] : 0,
1277 TemplateParams? TemplateParams->size() : 0));
1279 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
1280 TUK == Sema::TUK_Definition) {
1281 // FIXME: Diagnose this particular error.
1284 bool IsDependent = false;
1286 // Don't pass down template parameter lists if this is just a tag
1287 // reference. For example, we don't need the template parameters here:
1288 // template <class T> class A *makeA(T t);
1289 MultiTemplateParamsArg TParams;
1290 if (TUK != Sema::TUK_Reference && TemplateParams)
1292 MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
1294 // Declaration or definition of a class type
1295 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc,
1296 SS, Name, NameLoc, attrs.getList(), AS,
1297 DS.getModulePrivateSpecLoc(),
1298 TParams, Owned, IsDependent,
1299 SourceLocation(), false,
1300 clang::TypeResult());
1302 // If ActOnTag said the type was dependent, try again with the
1303 // less common call.
1305 assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
1306 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
1307 SS, Name, StartLoc, NameLoc);
1311 // If there is a body, parse it and inform the actions module.
1312 if (TUK == Sema::TUK_Definition) {
1313 assert(Tok.is(tok::l_brace) ||
1314 (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
1315 isCXX0XFinalKeyword());
1316 if (getLangOpts().CPlusPlus)
1317 ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get());
1319 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
1322 const char *PrevSpec = 0;
1325 if (!TypeResult.isInvalid()) {
1326 Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
1327 NameLoc.isValid() ? NameLoc : StartLoc,
1328 PrevSpec, DiagID, TypeResult.get());
1329 } else if (!TagOrTempResult.isInvalid()) {
1330 Result = DS.SetTypeSpecType(TagType, StartLoc,
1331 NameLoc.isValid() ? NameLoc : StartLoc,
1332 PrevSpec, DiagID, TagOrTempResult.get(), Owned);
1334 DS.SetTypeSpecError();
1339 Diag(StartLoc, DiagID) << PrevSpec;
1341 // At this point, we've successfully parsed a class-specifier in 'definition'
1342 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1343 // going to look at what comes after it to improve error recovery. If an
1344 // impossible token occurs next, we assume that the programmer forgot a ; at
1345 // the end of the declaration and recover that way.
1347 // This switch enumerates the valid "follow" set for definition.
1348 if (TUK == Sema::TUK_Definition) {
1349 bool ExpectedSemi = true;
1350 switch (Tok.getKind()) {
1352 case tok::semi: // struct foo {...} ;
1353 case tok::star: // struct foo {...} * P;
1354 case tok::amp: // struct foo {...} & R = ...
1355 case tok::identifier: // struct foo {...} V ;
1356 case tok::r_paren: //(struct foo {...} ) {4}
1357 case tok::annot_cxxscope: // struct foo {...} a:: b;
1358 case tok::annot_typename: // struct foo {...} a ::b;
1359 case tok::annot_template_id: // struct foo {...} a<int> ::b;
1360 case tok::l_paren: // struct foo {...} ( x);
1361 case tok::comma: // __builtin_offsetof(struct foo{...} ,
1362 ExpectedSemi = false;
1365 case tok::kw_const: // struct foo {...} const x;
1366 case tok::kw_volatile: // struct foo {...} volatile x;
1367 case tok::kw_restrict: // struct foo {...} restrict x;
1368 case tok::kw_inline: // struct foo {...} inline foo() {};
1369 // Storage-class specifiers
1370 case tok::kw_static: // struct foo {...} static x;
1371 case tok::kw_extern: // struct foo {...} extern x;
1372 case tok::kw_typedef: // struct foo {...} typedef x;
1373 case tok::kw_register: // struct foo {...} register x;
1374 case tok::kw_auto: // struct foo {...} auto x;
1375 case tok::kw_mutable: // struct foo {...} mutable x;
1376 case tok::kw_constexpr: // struct foo {...} constexpr x;
1377 // As shown above, type qualifiers and storage class specifiers absolutely
1378 // can occur after class specifiers according to the grammar. However,
1379 // almost no one actually writes code like this. If we see one of these,
1380 // it is much more likely that someone missed a semi colon and the
1381 // type/storage class specifier we're seeing is part of the *next*
1382 // intended declaration, as in:
1384 // struct foo { ... }
1387 // We'd really like to emit a missing semicolon error instead of emitting
1388 // an error on the 'int' saying that you can't have two type specifiers in
1389 // the same declaration of X. Because of this, we look ahead past this
1390 // token to see if it's a type specifier. If so, we know the code is
1391 // otherwise invalid, so we can produce the expected semi error.
1392 if (!isKnownToBeTypeSpecifier(NextToken()))
1393 ExpectedSemi = false;
1396 case tok::r_brace: // struct bar { struct foo {...} }
1397 // Missing ';' at end of struct is accepted as an extension in C mode.
1398 if (!getLangOpts().CPlusPlus)
1399 ExpectedSemi = false;
1403 // C++ [temp]p3 In a template-declaration which defines a class, no
1404 // declarator is permitted.
1405 if (TemplateInfo.Kind)
1406 ExpectedSemi = true;
1409 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
1410 TagType == DeclSpec::TST_class ? "class"
1411 : TagType == DeclSpec::TST_struct? "struct" : "union");
1412 // Push this token back into the preprocessor and change our current token
1413 // to ';' so that the rest of the code recovers as though there were an
1414 // ';' after the definition.
1416 Tok.setKind(tok::semi);
1421 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1423 /// base-clause : [C++ class.derived]
1424 /// ':' base-specifier-list
1425 /// base-specifier-list:
1426 /// base-specifier '...'[opt]
1427 /// base-specifier-list ',' base-specifier '...'[opt]
1428 void Parser::ParseBaseClause(Decl *ClassDecl) {
1429 assert(Tok.is(tok::colon) && "Not a base clause");
1432 // Build up an array of parsed base specifiers.
1433 SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
1436 // Parse a base-specifier.
1437 BaseResult Result = ParseBaseSpecifier(ClassDecl);
1438 if (Result.isInvalid()) {
1439 // Skip the rest of this base specifier, up until the comma or
1441 SkipUntil(tok::comma, tok::l_brace, true, true);
1443 // Add this to our array of base specifiers.
1444 BaseInfo.push_back(Result.get());
1447 // If the next token is a comma, consume it and keep reading
1449 if (Tok.isNot(tok::comma)) break;
1451 // Consume the comma.
1455 // Attach the base specifiers
1456 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size());
1459 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1460 /// one entry in the base class list of a class specifier, for example:
1461 /// class foo : public bar, virtual private baz {
1462 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1464 /// base-specifier: [C++ class.derived]
1465 /// ::[opt] nested-name-specifier[opt] class-name
1466 /// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
1467 /// base-type-specifier
1468 /// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
1469 /// base-type-specifier
1470 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
1471 bool IsVirtual = false;
1472 SourceLocation StartLoc = Tok.getLocation();
1474 // Parse the 'virtual' keyword.
1475 if (Tok.is(tok::kw_virtual)) {
1480 // Parse an (optional) access specifier.
1481 AccessSpecifier Access = getAccessSpecifierIfPresent();
1482 if (Access != AS_none)
1485 // Parse the 'virtual' keyword (again!), in case it came after the
1486 // access specifier.
1487 if (Tok.is(tok::kw_virtual)) {
1488 SourceLocation VirtualLoc = ConsumeToken();
1490 // Complain about duplicate 'virtual'
1491 Diag(VirtualLoc, diag::err_dup_virtual)
1492 << FixItHint::CreateRemoval(VirtualLoc);
1498 // Parse the class-name.
1499 SourceLocation EndLocation;
1500 SourceLocation BaseLoc;
1501 TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
1502 if (BaseType.isInvalid())
1505 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1506 // actually part of the base-specifier-list grammar productions, but we
1507 // parse it here for convenience.
1508 SourceLocation EllipsisLoc;
1509 if (Tok.is(tok::ellipsis))
1510 EllipsisLoc = ConsumeToken();
1512 // Find the complete source range for the base-specifier.
1513 SourceRange Range(StartLoc, EndLocation);
1515 // Notify semantic analysis that we have parsed a complete
1517 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access,
1518 BaseType.get(), BaseLoc, EllipsisLoc);
1521 /// getAccessSpecifierIfPresent - Determine whether the next token is
1522 /// a C++ access-specifier.
1524 /// access-specifier: [C++ class.derived]
1528 AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
1529 switch (Tok.getKind()) {
1530 default: return AS_none;
1531 case tok::kw_private: return AS_private;
1532 case tok::kw_protected: return AS_protected;
1533 case tok::kw_public: return AS_public;
1537 /// \brief If the given declarator has any parts for which parsing has to be
1538 /// delayed, e.g., default arguments or an exception-specification, create a
1539 /// late-parsed method declaration record to handle the parsing at the end of
1540 /// the class definition.
1541 void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
1543 // We just declared a member function. If this member function
1544 // has any default arguments or an exception-specification, we'll need to
1545 // parse them later.
1546 LateParsedMethodDeclaration *LateMethod = 0;
1547 DeclaratorChunk::FunctionTypeInfo &FTI
1548 = DeclaratorInfo.getFunctionTypeInfo();
1550 // If there was a delayed exception-specification, hold onto its tokens.
1551 if (FTI.getExceptionSpecType() == EST_Delayed) {
1552 // Push this method onto the stack of late-parsed method
1554 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1555 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1556 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1558 // Stash the exception-specification tokens in the late-pased mthod.
1559 LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
1560 FTI.ExceptionSpecTokens = 0;
1562 // Reserve space for the parameters.
1563 LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1566 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) {
1567 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) {
1569 // Push this method onto the stack of late-parsed method
1571 LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
1572 getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
1573 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
1575 // Add all of the parameters prior to this one (they don't
1576 // have default arguments).
1577 LateMethod->DefaultArgs.reserve(FTI.NumArgs);
1578 for (unsigned I = 0; I < ParamIdx; ++I)
1579 LateMethod->DefaultArgs.push_back(
1580 LateParsedDefaultArgument(FTI.ArgInfo[I].Param));
1583 // Add this parameter to the list of parameters (it may or may
1584 // not have a default argument).
1585 LateMethod->DefaultArgs.push_back(
1586 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param,
1587 FTI.ArgInfo[ParamIdx].DefaultArgTokens));
1592 /// isCXX0XVirtSpecifier - Determine whether the given token is a C++0x
1598 VirtSpecifiers::Specifier Parser::isCXX0XVirtSpecifier(const Token &Tok) const {
1599 if (!getLangOpts().CPlusPlus)
1600 return VirtSpecifiers::VS_None;
1602 if (Tok.is(tok::identifier)) {
1603 IdentifierInfo *II = Tok.getIdentifierInfo();
1605 // Initialize the contextual keywords.
1607 Ident_final = &PP.getIdentifierTable().get("final");
1608 Ident_override = &PP.getIdentifierTable().get("override");
1611 if (II == Ident_override)
1612 return VirtSpecifiers::VS_Override;
1614 if (II == Ident_final)
1615 return VirtSpecifiers::VS_Final;
1618 return VirtSpecifiers::VS_None;
1621 /// ParseOptionalCXX0XVirtSpecifierSeq - Parse a virt-specifier-seq.
1623 /// virt-specifier-seq:
1625 /// virt-specifier-seq virt-specifier
1626 void Parser::ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS) {
1628 VirtSpecifiers::Specifier Specifier = isCXX0XVirtSpecifier();
1629 if (Specifier == VirtSpecifiers::VS_None)
1632 // C++ [class.mem]p8:
1633 // A virt-specifier-seq shall contain at most one of each virt-specifier.
1634 const char *PrevSpec = 0;
1635 if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
1636 Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
1638 << FixItHint::CreateRemoval(Tok.getLocation());
1640 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
1641 diag::warn_cxx98_compat_override_control_keyword :
1642 diag::ext_override_control_keyword)
1643 << VirtSpecifiers::getSpecifierName(Specifier);
1648 /// isCXX0XFinalKeyword - Determine whether the next token is a C++0x
1649 /// contextual 'final' keyword.
1650 bool Parser::isCXX0XFinalKeyword() const {
1651 if (!getLangOpts().CPlusPlus)
1654 if (!Tok.is(tok::identifier))
1657 // Initialize the contextual keywords.
1659 Ident_final = &PP.getIdentifierTable().get("final");
1660 Ident_override = &PP.getIdentifierTable().get("override");
1663 return Tok.getIdentifierInfo() == Ident_final;
1666 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1668 /// member-declaration:
1669 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
1670 /// function-definition ';'[opt]
1671 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1672 /// using-declaration [TODO]
1673 /// [C++0x] static_assert-declaration
1674 /// template-declaration
1675 /// [GNU] '__extension__' member-declaration
1677 /// member-declarator-list:
1678 /// member-declarator
1679 /// member-declarator-list ',' member-declarator
1681 /// member-declarator:
1682 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
1683 /// declarator constant-initializer[opt]
1684 /// [C++11] declarator brace-or-equal-initializer[opt]
1685 /// identifier[opt] ':' constant-expression
1687 /// virt-specifier-seq:
1689 /// virt-specifier-seq virt-specifier
1698 /// constant-initializer:
1699 /// '=' constant-expression
1701 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
1702 AttributeList *AccessAttrs,
1703 const ParsedTemplateInfo &TemplateInfo,
1704 ParsingDeclRAIIObject *TemplateDiags) {
1705 if (Tok.is(tok::at)) {
1706 if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
1707 Diag(Tok, diag::err_at_defs_cxx);
1709 Diag(Tok, diag::err_at_in_class);
1712 SkipUntil(tok::r_brace);
1716 // Access declarations.
1717 if (!TemplateInfo.Kind &&
1718 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) &&
1719 !TryAnnotateCXXScopeToken() &&
1720 Tok.is(tok::annot_cxxscope)) {
1721 bool isAccessDecl = false;
1722 if (NextToken().is(tok::identifier))
1723 isAccessDecl = GetLookAheadToken(2).is(tok::semi);
1725 isAccessDecl = NextToken().is(tok::kw_operator);
1728 // Collect the scope specifier token we annotated earlier.
1730 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1731 /*EnteringContext=*/false);
1733 // Try to parse an unqualified-id.
1734 SourceLocation TemplateKWLoc;
1736 if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
1737 TemplateKWLoc, Name)) {
1738 SkipUntil(tok::semi);
1742 // TODO: recover from mistakenly-qualified operator declarations.
1743 if (ExpectAndConsume(tok::semi,
1744 diag::err_expected_semi_after,
1745 "access declaration",
1749 Actions.ActOnUsingDeclaration(getCurScope(), AS,
1750 false, SourceLocation(),
1753 /* IsTypeName */ false,
1759 // static_assert-declaration
1760 if (Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert)) {
1761 // FIXME: Check for templates
1762 SourceLocation DeclEnd;
1763 ParseStaticAssertDeclaration(DeclEnd);
1767 if (Tok.is(tok::kw_template)) {
1768 assert(!TemplateInfo.TemplateParams &&
1769 "Nested template improperly parsed?");
1770 SourceLocation DeclEnd;
1771 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd,
1776 // Handle: member-declaration ::= '__extension__' member-declaration
1777 if (Tok.is(tok::kw___extension__)) {
1778 // __extension__ silences extension warnings in the subexpression.
1779 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1781 return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
1782 TemplateInfo, TemplateDiags);
1785 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1787 ColonProtectionRAIIObject X(*this);
1789 ParsedAttributesWithRange attrs(AttrFactory);
1790 // Optional C++0x attribute-specifier
1791 MaybeParseCXX0XAttributes(attrs);
1792 MaybeParseMicrosoftAttributes(attrs);
1794 if (Tok.is(tok::kw_using)) {
1795 ProhibitAttributes(attrs);
1798 SourceLocation UsingLoc = ConsumeToken();
1800 if (Tok.is(tok::kw_namespace)) {
1801 Diag(UsingLoc, diag::err_using_namespace_in_class);
1802 SkipUntil(tok::semi, true, true);
1804 SourceLocation DeclEnd;
1805 // Otherwise, it must be a using-declaration or an alias-declaration.
1806 ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo,
1807 UsingLoc, DeclEnd, AS);
1812 // Hold late-parsed attributes so we can attach a Decl to them later.
1813 LateParsedAttrList CommonLateParsedAttrs;
1815 // decl-specifier-seq:
1816 // Parse the common declaration-specifiers piece.
1817 ParsingDeclSpec DS(*this, TemplateDiags);
1818 DS.takeAttributesFrom(attrs);
1819 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
1820 &CommonLateParsedAttrs);
1822 MultiTemplateParamsArg TemplateParams(Actions,
1823 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
1824 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
1826 if (Tok.is(tok::semi)) {
1829 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams);
1830 DS.complete(TheDecl);
1834 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext);
1837 // Hold late-parsed attributes so we can attach a Decl to them later.
1838 LateParsedAttrList LateParsedAttrs;
1840 SourceLocation EqualLoc;
1841 bool HasInitializer = false;
1843 if (Tok.isNot(tok::colon)) {
1844 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1845 ColonProtectionRAIIObject X(*this);
1847 // Parse the first declarator.
1848 ParseDeclarator(DeclaratorInfo);
1849 // Error parsin g the declarator?
1850 if (!DeclaratorInfo.hasName()) {
1851 // If so, skip until the semi-colon or a }.
1852 SkipUntil(tok::r_brace, true, true);
1853 if (Tok.is(tok::semi))
1858 ParseOptionalCXX0XVirtSpecifierSeq(VS);
1860 // If attributes exist after the declarator, but before an '{', parse them.
1861 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
1863 // MSVC permits pure specifier on inline functions declared at class scope.
1864 // Hence check for =0 before checking for function definition.
1865 if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
1866 DeclaratorInfo.isFunctionDeclarator() &&
1867 NextToken().is(tok::numeric_constant)) {
1868 EqualLoc = ConsumeToken();
1869 Init = ParseInitializer();
1870 if (Init.isInvalid())
1871 SkipUntil(tok::comma, true, true);
1873 HasInitializer = true;
1876 FunctionDefinitionKind DefinitionKind = FDK_Declaration;
1877 // function-definition:
1879 // In C++11, a non-function declarator followed by an open brace is a
1880 // braced-init-list for an in-class member initialization, not an
1881 // erroneous function definition.
1882 if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus0x) {
1883 DefinitionKind = FDK_Definition;
1884 } else if (DeclaratorInfo.isFunctionDeclarator()) {
1885 if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
1886 DefinitionKind = FDK_Definition;
1887 } else if (Tok.is(tok::equal)) {
1888 const Token &KW = NextToken();
1889 if (KW.is(tok::kw_default))
1890 DefinitionKind = FDK_Defaulted;
1891 else if (KW.is(tok::kw_delete))
1892 DefinitionKind = FDK_Deleted;
1896 if (DefinitionKind) {
1897 if (!DeclaratorInfo.isFunctionDeclarator()) {
1898 Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
1900 SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1902 // Consume the optional ';'
1903 if (Tok.is(tok::semi))
1908 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1909 Diag(DeclaratorInfo.getIdentifierLoc(),
1910 diag::err_function_declared_typedef);
1911 // This recovery skips the entire function body. It would be nice
1912 // to simply call ParseCXXInlineMethodDef() below, however Sema
1913 // assumes the declarator represents a function, not a typedef.
1915 SkipUntil(tok::r_brace, /*StopAtSemi*/false);
1917 // Consume the optional ';'
1918 if (Tok.is(tok::semi))
1924 ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
1925 VS, DefinitionKind, Init);
1927 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
1928 CommonLateParsedAttrs[i]->addDecl(FunDecl);
1930 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
1931 LateParsedAttrs[i]->addDecl(FunDecl);
1933 LateParsedAttrs.clear();
1935 // Consume the ';' - it's optional unless we have a delete or default
1936 if (Tok.is(tok::semi)) {
1944 // member-declarator-list:
1945 // member-declarator
1946 // member-declarator-list ',' member-declarator
1948 SmallVector<Decl *, 8> DeclsInGroup;
1949 ExprResult BitfieldSize;
1950 bool ExpectSemi = true;
1953 // member-declarator:
1954 // declarator pure-specifier[opt]
1955 // declarator brace-or-equal-initializer[opt]
1956 // identifier[opt] ':' constant-expression
1957 if (Tok.is(tok::colon)) {
1959 BitfieldSize = ParseConstantExpression();
1960 if (BitfieldSize.isInvalid())
1961 SkipUntil(tok::comma, true, true);
1964 // If a simple-asm-expr is present, parse it.
1965 if (Tok.is(tok::kw_asm)) {
1967 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
1968 if (AsmLabel.isInvalid())
1969 SkipUntil(tok::comma, true, true);
1971 DeclaratorInfo.setAsmLabel(AsmLabel.release());
1972 DeclaratorInfo.SetRangeEnd(Loc);
1975 // If attributes exist after the declarator, parse them.
1976 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
1978 // FIXME: When g++ adds support for this, we'll need to check whether it
1979 // goes before or after the GNU attributes and __asm__.
1980 ParseOptionalCXX0XVirtSpecifierSeq(VS);
1982 bool HasDeferredInitializer = false;
1983 if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
1984 if (BitfieldSize.get()) {
1985 Diag(Tok, diag::err_bitfield_member_init);
1986 SkipUntil(tok::comma, true, true);
1988 HasInitializer = true;
1989 HasDeferredInitializer = !DeclaratorInfo.isDeclarationOfFunction() &&
1990 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
1991 != DeclSpec::SCS_static &&
1992 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
1993 != DeclSpec::SCS_typedef;
1997 // NOTE: If Sema is the Action module and declarator is an instance field,
1998 // this call will *not* return the created decl; It will return null.
1999 // See Sema::ActOnCXXMemberDeclarator for details.
2002 if (DS.isFriendSpecified()) {
2003 // TODO: handle initializers, bitfields, 'delete'
2004 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
2005 move(TemplateParams));
2007 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
2009 move(TemplateParams),
2010 BitfieldSize.release(),
2011 VS, HasDeferredInitializer);
2013 Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs,
2017 // Set the Decl for any late parsed attributes
2018 for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
2019 CommonLateParsedAttrs[i]->addDecl(ThisDecl);
2021 for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
2022 LateParsedAttrs[i]->addDecl(ThisDecl);
2024 LateParsedAttrs.clear();
2026 // Handle the initializer.
2027 if (HasDeferredInitializer) {
2028 // The initializer was deferred; parse it and cache the tokens.
2029 Diag(Tok, getLangOpts().CPlusPlus0x ?
2030 diag::warn_cxx98_compat_nonstatic_member_init :
2031 diag::ext_nonstatic_member_init);
2033 if (DeclaratorInfo.isArrayOfUnknownBound()) {
2034 // C++0x [dcl.array]p3: An array bound may also be omitted when the
2035 // declarator is followed by an initializer.
2037 // A brace-or-equal-initializer for a member-declarator is not an
2038 // initializer in the grammar, so this is ill-formed.
2039 Diag(Tok, diag::err_incomplete_array_member_init);
2040 SkipUntil(tok::comma, true, true);
2042 // Avoid later warnings about a class member of incomplete type.
2043 ThisDecl->setInvalidDecl();
2045 ParseCXXNonStaticMemberInitializer(ThisDecl);
2046 } else if (HasInitializer) {
2047 // Normal initializer.
2048 if (!Init.isUsable())
2049 Init = ParseCXXMemberInitializer(ThisDecl,
2050 DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
2052 if (Init.isInvalid())
2053 SkipUntil(tok::comma, true, true);
2055 Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(),
2056 DS.getTypeSpecType() == DeclSpec::TST_auto);
2057 } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) {
2059 Actions.ActOnUninitializedDecl(ThisDecl,
2060 DS.getTypeSpecType() == DeclSpec::TST_auto);
2064 Actions.FinalizeDeclaration(ThisDecl);
2065 DeclsInGroup.push_back(ThisDecl);
2068 if (DeclaratorInfo.isFunctionDeclarator() &&
2069 DeclaratorInfo.getDeclSpec().getStorageClassSpec()
2070 != DeclSpec::SCS_typedef) {
2071 HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
2074 DeclaratorInfo.complete(ThisDecl);
2076 // If we don't have a comma, it is either the end of the list (a ';')
2077 // or an error, bail out.
2078 if (Tok.isNot(tok::comma))
2081 // Consume the comma.
2082 SourceLocation CommaLoc = ConsumeToken();
2084 if (Tok.isAtStartOfLine() &&
2085 !MightBeDeclarator(Declarator::MemberContext)) {
2086 // This comma was followed by a line-break and something which can't be
2087 // the start of a declarator. The comma was probably a typo for a
2089 Diag(CommaLoc, diag::err_expected_semi_declaration)
2090 << FixItHint::CreateReplacement(CommaLoc, ";");
2095 // Parse the next declarator.
2096 DeclaratorInfo.clear();
2098 BitfieldSize = true;
2100 HasInitializer = false;
2101 DeclaratorInfo.setCommaLoc(CommaLoc);
2103 // Attributes are only allowed on the second declarator.
2104 MaybeParseGNUAttributes(DeclaratorInfo);
2106 if (Tok.isNot(tok::colon))
2107 ParseDeclarator(DeclaratorInfo);
2111 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
2112 // Skip to end of block or statement.
2113 SkipUntil(tok::r_brace, true, true);
2114 // If we stopped at a ';', eat it.
2115 if (Tok.is(tok::semi)) ConsumeToken();
2119 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(),
2120 DeclsInGroup.size());
2123 /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer or
2124 /// pure-specifier. Also detect and reject any attempted defaulted/deleted
2125 /// function definition. The location of the '=', if any, will be placed in
2131 /// brace-or-equal-initializer:
2132 /// '=' initializer-expression
2133 /// braced-init-list
2135 /// initializer-clause:
2136 /// assignment-expression
2137 /// braced-init-list
2139 /// defaulted/deleted function-definition:
2143 /// Prior to C++0x, the assignment-expression in an initializer-clause must
2144 /// be a constant-expression.
2145 ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
2146 SourceLocation &EqualLoc) {
2147 assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
2148 && "Data member initializer not starting with '=' or '{'");
2150 EnterExpressionEvaluationContext Context(Actions,
2151 Sema::PotentiallyEvaluated,
2153 if (Tok.is(tok::equal)) {
2154 EqualLoc = ConsumeToken();
2155 if (Tok.is(tok::kw_delete)) {
2156 // In principle, an initializer of '= delete p;' is legal, but it will
2157 // never type-check. It's better to diagnose it as an ill-formed expression
2158 // than as an ill-formed deleted non-function member.
2159 // An initializer of '= delete p, foo' will never be parsed, because
2160 // a top-level comma always ends the initializer expression.
2161 const Token &Next = NextToken();
2162 if (IsFunction || Next.is(tok::semi) || Next.is(tok::comma) ||
2163 Next.is(tok::eof)) {
2165 Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2168 Diag(ConsumeToken(), diag::err_deleted_non_function);
2169 return ExprResult();
2171 } else if (Tok.is(tok::kw_default)) {
2173 Diag(Tok, diag::err_default_delete_in_multiple_declaration)
2176 Diag(ConsumeToken(), diag::err_default_special_members);
2177 return ExprResult();
2181 return ParseInitializer();
2184 /// ParseCXXMemberSpecification - Parse the class definition.
2186 /// member-specification:
2187 /// member-declaration member-specification[opt]
2188 /// access-specifier ':' member-specification[opt]
2190 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
2191 unsigned TagType, Decl *TagDecl) {
2192 assert((TagType == DeclSpec::TST_struct ||
2193 TagType == DeclSpec::TST_union ||
2194 TagType == DeclSpec::TST_class) && "Invalid TagType!");
2196 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2197 "parsing struct/union/class body");
2199 // Determine whether this is a non-nested class. Note that local
2200 // classes are *not* considered to be nested classes.
2201 bool NonNestedClass = true;
2202 if (!ClassStack.empty()) {
2203 for (const Scope *S = getCurScope(); S; S = S->getParent()) {
2204 if (S->isClassScope()) {
2205 // We're inside a class scope, so this is a nested class.
2206 NonNestedClass = false;
2210 if ((S->getFlags() & Scope::FnScope)) {
2211 // If we're in a function or function template declared in the
2212 // body of a class, then this is a local class rather than a
2214 const Scope *Parent = S->getParent();
2215 if (Parent->isTemplateParamScope())
2216 Parent = Parent->getParent();
2217 if (Parent->isClassScope())
2223 // Enter a scope for the class.
2224 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
2226 // Note that we are parsing a new (potentially-nested) class definition.
2227 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass);
2230 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2232 SourceLocation FinalLoc;
2234 // Parse the optional 'final' keyword.
2235 if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
2236 assert(isCXX0XFinalKeyword() && "not a class definition");
2237 FinalLoc = ConsumeToken();
2239 Diag(FinalLoc, getLangOpts().CPlusPlus0x ?
2240 diag::warn_cxx98_compat_override_control_keyword :
2241 diag::ext_override_control_keyword) << "final";
2244 if (Tok.is(tok::colon)) {
2245 ParseBaseClause(TagDecl);
2247 if (!Tok.is(tok::l_brace)) {
2248 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers);
2251 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
2256 assert(Tok.is(tok::l_brace));
2257 BalancedDelimiterTracker T(*this, tok::l_brace);
2261 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
2262 T.getOpenLocation());
2264 // C++ 11p3: Members of a class defined with the keyword class are private
2265 // by default. Members of a class defined with the keywords struct or union
2266 // are public by default.
2267 AccessSpecifier CurAS;
2268 if (TagType == DeclSpec::TST_class)
2272 ParsedAttributes AccessAttrs(AttrFactory);
2275 // While we still have something to read, read the member-declarations.
2276 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2277 // Each iteration of this loop reads one member-declaration.
2279 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
2280 Tok.is(tok::kw___if_not_exists))) {
2281 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
2285 // Check for extraneous top-level semicolon.
2286 if (Tok.is(tok::semi)) {
2287 Diag(Tok, diag::ext_extra_struct_semi)
2288 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
2289 << FixItHint::CreateRemoval(Tok.getLocation());
2294 if (Tok.is(tok::annot_pragma_vis)) {
2295 HandlePragmaVisibility();
2299 if (Tok.is(tok::annot_pragma_pack)) {
2304 AccessSpecifier AS = getAccessSpecifierIfPresent();
2305 if (AS != AS_none) {
2306 // Current token is a C++ access specifier.
2308 SourceLocation ASLoc = Tok.getLocation();
2309 unsigned TokLength = Tok.getLength();
2311 AccessAttrs.clear();
2312 MaybeParseGNUAttributes(AccessAttrs);
2314 SourceLocation EndLoc;
2315 if (Tok.is(tok::colon)) {
2316 EndLoc = Tok.getLocation();
2318 } else if (Tok.is(tok::semi)) {
2319 EndLoc = Tok.getLocation();
2321 Diag(EndLoc, diag::err_expected_colon)
2322 << FixItHint::CreateReplacement(EndLoc, ":");
2324 EndLoc = ASLoc.getLocWithOffset(TokLength);
2325 Diag(EndLoc, diag::err_expected_colon)
2326 << FixItHint::CreateInsertion(EndLoc, ":");
2329 if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
2330 AccessAttrs.getList())) {
2331 // found another attribute than only annotations
2332 AccessAttrs.clear();
2338 // FIXME: Make sure we don't have a template here.
2340 // Parse all the comma separated declarators.
2341 ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList());
2346 SkipUntil(tok::r_brace, false, false);
2349 // If attributes exist after class contents, parse them.
2350 ParsedAttributes attrs(AttrFactory);
2351 MaybeParseGNUAttributes(attrs);
2354 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
2355 T.getOpenLocation(),
2356 T.getCloseLocation(),
2359 // C++11 [class.mem]p2:
2360 // Within the class member-specification, the class is regarded as complete
2361 // within function bodies, default arguments, exception-specifications, and
2362 // brace-or-equal-initializers for non-static data members (including such
2363 // things in nested classes).
2364 if (TagDecl && NonNestedClass) {
2365 // We are not inside a nested class. This class and its nested classes
2366 // are complete and we can parse the delayed portions of method
2367 // declarations and the lexed inline method definitions, along with any
2368 // delayed attributes.
2369 SourceLocation SavedPrevTokLocation = PrevTokLocation;
2370 ParseLexedAttributes(getCurrentClass());
2371 ParseLexedMethodDeclarations(getCurrentClass());
2372 ParseLexedMemberInitializers(getCurrentClass());
2373 ParseLexedMethodDefs(getCurrentClass());
2374 PrevTokLocation = SavedPrevTokLocation;
2378 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
2379 T.getCloseLocation());
2381 // Leave the class scope.
2386 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
2387 /// which explicitly initializes the members or base classes of a
2388 /// class (C++ [class.base.init]). For example, the three initializers
2389 /// after the ':' in the Derived constructor below:
2393 /// class Derived : Base {
2397 /// Derived(float f) : Base(), x(17), f(f) { }
2401 /// [C++] ctor-initializer:
2402 /// ':' mem-initializer-list
2404 /// [C++] mem-initializer-list:
2405 /// mem-initializer ...[opt]
2406 /// mem-initializer ...[opt] , mem-initializer-list
2407 void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
2408 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'");
2410 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers
2411 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
2412 SourceLocation ColonLoc = ConsumeToken();
2414 SmallVector<CXXCtorInitializer*, 4> MemInitializers;
2415 bool AnyErrors = false;
2418 if (Tok.is(tok::code_completion)) {
2419 Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
2420 MemInitializers.data(),
2421 MemInitializers.size());
2422 return cutOffParsing();
2424 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
2425 if (!MemInit.isInvalid())
2426 MemInitializers.push_back(MemInit.get());
2431 if (Tok.is(tok::comma))
2433 else if (Tok.is(tok::l_brace))
2435 // If the next token looks like a base or member initializer, assume that
2436 // we're just missing a comma.
2437 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
2438 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2439 Diag(Loc, diag::err_ctor_init_missing_comma)
2440 << FixItHint::CreateInsertion(Loc, ", ");
2442 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2443 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
2444 SkipUntil(tok::l_brace, true, true);
2449 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc,
2450 MemInitializers.data(), MemInitializers.size(),
2454 /// ParseMemInitializer - Parse a C++ member initializer, which is
2455 /// part of a constructor initializer that explicitly initializes one
2456 /// member or base class (C++ [class.base.init]). See
2457 /// ParseConstructorInitializer for an example.
2459 /// [C++] mem-initializer:
2460 /// mem-initializer-id '(' expression-list[opt] ')'
2461 /// [C++0x] mem-initializer-id braced-init-list
2463 /// [C++] mem-initializer-id:
2464 /// '::'[opt] nested-name-specifier[opt] class-name
2466 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
2467 // parse '::'[opt] nested-name-specifier[opt]
2469 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
2470 ParsedType TemplateTypeTy;
2471 if (Tok.is(tok::annot_template_id)) {
2472 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2473 if (TemplateId->Kind == TNK_Type_template ||
2474 TemplateId->Kind == TNK_Dependent_template_name) {
2475 AnnotateTemplateIdTokenAsType();
2476 assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
2477 TemplateTypeTy = getTypeAnnotation(Tok);
2480 // Uses of decltype will already have been converted to annot_decltype by
2481 // ParseOptionalCXXScopeSpecifier at this point.
2482 if (!TemplateTypeTy && Tok.isNot(tok::identifier)
2483 && Tok.isNot(tok::annot_decltype)) {
2484 Diag(Tok, diag::err_expected_member_or_base_name);
2488 IdentifierInfo *II = 0;
2489 DeclSpec DS(AttrFactory);
2490 SourceLocation IdLoc = Tok.getLocation();
2491 if (Tok.is(tok::annot_decltype)) {
2492 // Get the decltype expression, if there is one.
2493 ParseDecltypeSpecifier(DS);
2495 if (Tok.is(tok::identifier))
2496 // Get the identifier. This may be a member name or a class name,
2497 // but we'll let the semantic analysis determine which it is.
2498 II = Tok.getIdentifierInfo();
2504 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
2505 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2507 ExprResult InitList = ParseBraceInitializer();
2508 if (InitList.isInvalid())
2511 SourceLocation EllipsisLoc;
2512 if (Tok.is(tok::ellipsis))
2513 EllipsisLoc = ConsumeToken();
2515 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2516 TemplateTypeTy, DS, IdLoc,
2517 InitList.take(), EllipsisLoc);
2518 } else if(Tok.is(tok::l_paren)) {
2519 BalancedDelimiterTracker T(*this, tok::l_paren);
2522 // Parse the optional expression-list.
2523 ExprVector ArgExprs(Actions);
2524 CommaLocsTy CommaLocs;
2525 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) {
2526 SkipUntil(tok::r_paren);
2532 SourceLocation EllipsisLoc;
2533 if (Tok.is(tok::ellipsis))
2534 EllipsisLoc = ConsumeToken();
2536 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
2537 TemplateTypeTy, DS, IdLoc,
2538 T.getOpenLocation(), ArgExprs.take(),
2539 ArgExprs.size(), T.getCloseLocation(),
2543 Diag(Tok, getLangOpts().CPlusPlus0x ? diag::err_expected_lparen_or_lbrace
2544 : diag::err_expected_lparen);
2548 /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]).
2550 /// exception-specification:
2551 /// dynamic-exception-specification
2552 /// noexcept-specification
2554 /// noexcept-specification:
2556 /// 'noexcept' '(' constant-expression ')'
2557 ExceptionSpecificationType
2558 Parser::tryParseExceptionSpecification(bool Delayed,
2559 SourceRange &SpecificationRange,
2560 SmallVectorImpl<ParsedType> &DynamicExceptions,
2561 SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
2562 ExprResult &NoexceptExpr,
2563 CachedTokens *&ExceptionSpecTokens) {
2564 ExceptionSpecificationType Result = EST_None;
2565 ExceptionSpecTokens = 0;
2567 // Handle delayed parsing of exception-specifications.
2569 if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
2572 // Consume and cache the starting token.
2573 bool IsNoexcept = Tok.is(tok::kw_noexcept);
2574 Token StartTok = Tok;
2575 SpecificationRange = SourceRange(ConsumeToken());
2578 if (!Tok.is(tok::l_paren)) {
2579 // If this is a bare 'noexcept', we're done.
2581 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
2583 return EST_BasicNoexcept;
2586 Diag(Tok, diag::err_expected_lparen_after) << "throw";
2587 return EST_DynamicNone;
2590 // Cache the tokens for the exception-specification.
2591 ExceptionSpecTokens = new CachedTokens;
2592 ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
2593 ExceptionSpecTokens->push_back(Tok); // '('
2594 SpecificationRange.setEnd(ConsumeParen()); // '('
2596 if (!ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
2597 /*StopAtSemi=*/true,
2598 /*ConsumeFinalToken=*/true)) {
2600 delete ExceptionSpecTokens;
2601 ExceptionSpecTokens = 0;
2602 return IsNoexcept? EST_BasicNoexcept : EST_DynamicNone;
2604 SpecificationRange.setEnd(Tok.getLocation());
2606 // Add the 'stop' token.
2609 End.setKind(tok::cxx_exceptspec_end);
2610 End.setLocation(Tok.getLocation());
2611 ExceptionSpecTokens->push_back(End);
2615 // See if there's a dynamic specification.
2616 if (Tok.is(tok::kw_throw)) {
2617 Result = ParseDynamicExceptionSpecification(SpecificationRange,
2619 DynamicExceptionRanges);
2620 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
2621 "Produced different number of exception types and ranges.");
2624 // If there's no noexcept specification, we're done.
2625 if (Tok.isNot(tok::kw_noexcept))
2628 Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
2630 // If we already had a dynamic specification, parse the noexcept for,
2631 // recovery, but emit a diagnostic and don't store the results.
2632 SourceRange NoexceptRange;
2633 ExceptionSpecificationType NoexceptType = EST_None;
2635 SourceLocation KeywordLoc = ConsumeToken();
2636 if (Tok.is(tok::l_paren)) {
2637 // There is an argument.
2638 BalancedDelimiterTracker T(*this, tok::l_paren);
2640 NoexceptType = EST_ComputedNoexcept;
2641 NoexceptExpr = ParseConstantExpression();
2642 // The argument must be contextually convertible to bool. We use
2643 // ActOnBooleanCondition for this purpose.
2644 if (!NoexceptExpr.isInvalid())
2645 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc,
2646 NoexceptExpr.get());
2648 NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
2650 // There is no argument.
2651 NoexceptType = EST_BasicNoexcept;
2652 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
2655 if (Result == EST_None) {
2656 SpecificationRange = NoexceptRange;
2657 Result = NoexceptType;
2659 // If there's a dynamic specification after a noexcept specification,
2660 // parse that and ignore the results.
2661 if (Tok.is(tok::kw_throw)) {
2662 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2663 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
2664 DynamicExceptionRanges);
2667 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
2673 /// ParseDynamicExceptionSpecification - Parse a C++
2674 /// dynamic-exception-specification (C++ [except.spec]).
2676 /// dynamic-exception-specification:
2677 /// 'throw' '(' type-id-list [opt] ')'
2678 /// [MS] 'throw' '(' '...' ')'
2681 /// type-id ... [opt]
2682 /// type-id-list ',' type-id ... [opt]
2684 ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
2685 SourceRange &SpecificationRange,
2686 SmallVectorImpl<ParsedType> &Exceptions,
2687 SmallVectorImpl<SourceRange> &Ranges) {
2688 assert(Tok.is(tok::kw_throw) && "expected throw");
2690 SpecificationRange.setBegin(ConsumeToken());
2691 BalancedDelimiterTracker T(*this, tok::l_paren);
2692 if (T.consumeOpen()) {
2693 Diag(Tok, diag::err_expected_lparen_after) << "throw";
2694 SpecificationRange.setEnd(SpecificationRange.getBegin());
2695 return EST_DynamicNone;
2698 // Parse throw(...), a Microsoft extension that means "this function
2699 // can throw anything".
2700 if (Tok.is(tok::ellipsis)) {
2701 SourceLocation EllipsisLoc = ConsumeToken();
2702 if (!getLangOpts().MicrosoftExt)
2703 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
2705 SpecificationRange.setEnd(T.getCloseLocation());
2709 // Parse the sequence of type-ids.
2711 while (Tok.isNot(tok::r_paren)) {
2712 TypeResult Res(ParseTypeName(&Range));
2714 if (Tok.is(tok::ellipsis)) {
2715 // C++0x [temp.variadic]p5:
2716 // - In a dynamic-exception-specification (15.4); the pattern is a
2718 SourceLocation Ellipsis = ConsumeToken();
2719 Range.setEnd(Ellipsis);
2720 if (!Res.isInvalid())
2721 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
2724 if (!Res.isInvalid()) {
2725 Exceptions.push_back(Res.get());
2726 Ranges.push_back(Range);
2729 if (Tok.is(tok::comma))
2736 SpecificationRange.setEnd(T.getCloseLocation());
2737 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
2740 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
2741 /// function declaration.
2742 TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) {
2743 assert(Tok.is(tok::arrow) && "expected arrow");
2747 return ParseTypeName(&Range, Declarator::TrailingReturnContext);
2750 /// \brief We have just started parsing the definition of a new class,
2751 /// so push that class onto our stack of classes that is currently
2753 Sema::ParsingClassState
2754 Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass) {
2755 assert((NonNestedClass || !ClassStack.empty()) &&
2756 "Nested class without outer class");
2757 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass));
2758 return Actions.PushParsingClass();
2761 /// \brief Deallocate the given parsed class and all of its nested
2763 void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
2764 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
2765 delete Class->LateParsedDeclarations[I];
2769 /// \brief Pop the top class of the stack of classes that are
2770 /// currently being parsed.
2772 /// This routine should be called when we have finished parsing the
2773 /// definition of a class, but have not yet popped the Scope
2774 /// associated with the class's definition.
2776 /// \returns true if the class we've popped is a top-level class,
2777 /// false otherwise.
2778 void Parser::PopParsingClass(Sema::ParsingClassState state) {
2779 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
2781 Actions.PopParsingClass(state);
2783 ParsingClass *Victim = ClassStack.top();
2785 if (Victim->TopLevelClass) {
2786 // Deallocate all of the nested classes of this class,
2787 // recursively: we don't need to keep any of this information.
2788 DeallocateParsedClasses(Victim);
2791 assert(!ClassStack.empty() && "Missing top-level class?");
2793 if (Victim->LateParsedDeclarations.empty()) {
2794 // The victim is a nested class, but we will not need to perform
2795 // any processing after the definition of this class since it has
2796 // no members whose handling was delayed. Therefore, we can just
2797 // remove this nested class.
2798 DeallocateParsedClasses(Victim);
2802 // This nested class has some members that will need to be processed
2803 // after the top-level class is completely defined. Therefore, add
2804 // it to the list of nested classes within its parent.
2805 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
2806 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
2807 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
2810 /// \brief Try to parse an 'identifier' which appears within an attribute-token.
2812 /// \return the parsed identifier on success, and 0 if the next token is not an
2813 /// attribute-token.
2815 /// C++11 [dcl.attr.grammar]p3:
2816 /// If a keyword or an alternative token that satisfies the syntactic
2817 /// requirements of an identifier is contained in an attribute-token,
2818 /// it is considered an identifier.
2819 IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
2820 switch (Tok.getKind()) {
2822 // Identifiers and keywords have identifier info attached.
2823 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
2824 Loc = ConsumeToken();
2829 case tok::ampamp: // 'and'
2830 case tok::pipe: // 'bitor'
2831 case tok::pipepipe: // 'or'
2832 case tok::caret: // 'xor'
2833 case tok::tilde: // 'compl'
2834 case tok::amp: // 'bitand'
2835 case tok::ampequal: // 'and_eq'
2836 case tok::pipeequal: // 'or_eq'
2837 case tok::caretequal: // 'xor_eq'
2838 case tok::exclaim: // 'not'
2839 case tok::exclaimequal: // 'not_eq'
2840 // Alternative tokens do not have identifier info, but their spelling
2841 // starts with an alphabetical character.
2842 llvm::SmallString<8> SpellingBuf;
2843 StringRef Spelling = PP.getSpelling(Tok.getLocation(), SpellingBuf);
2844 if (std::isalpha(Spelling[0])) {
2845 Loc = ConsumeToken();
2846 return &PP.getIdentifierTable().get(Spelling.data());
2852 /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Currently
2853 /// only parses standard attributes.
2855 /// [C++11] attribute-specifier:
2856 /// '[' '[' attribute-list ']' ']'
2857 /// alignment-specifier
2859 /// [C++11] attribute-list:
2861 /// attribute-list ',' attribute[opt]
2863 /// attribute-list ',' attribute '...'
2865 /// [C++11] attribute:
2866 /// attribute-token attribute-argument-clause[opt]
2868 /// [C++11] attribute-token:
2870 /// attribute-scoped-token
2872 /// [C++11] attribute-scoped-token:
2873 /// attribute-namespace '::' identifier
2875 /// [C++11] attribute-namespace:
2878 /// [C++11] attribute-argument-clause:
2879 /// '(' balanced-token-seq ')'
2881 /// [C++11] balanced-token-seq:
2883 /// balanced-token-seq balanced-token
2885 /// [C++11] balanced-token:
2886 /// '(' balanced-token-seq ')'
2887 /// '[' balanced-token-seq ']'
2888 /// '{' balanced-token-seq '}'
2889 /// any token but '(', ')', '[', ']', '{', or '}'
2890 void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
2891 SourceLocation *endLoc) {
2892 if (Tok.is(tok::kw_alignas)) {
2893 Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
2894 ParseAlignmentSpecifier(attrs, endLoc);
2898 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
2899 && "Not a C++11 attribute list");
2901 Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
2906 while (Tok.isNot(tok::r_square)) {
2907 // attribute not present
2908 if (Tok.is(tok::comma)) {
2913 SourceLocation ScopeLoc, AttrLoc;
2914 IdentifierInfo *ScopeName = 0, *AttrName = 0;
2916 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
2918 // Break out to the "expected ']'" diagnostic.
2922 if (Tok.is(tok::coloncolon)) {
2925 ScopeName = AttrName;
2928 AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
2930 Diag(Tok.getLocation(), diag::err_expected_ident);
2931 SkipUntil(tok::r_square, tok::comma, true, true);
2936 bool AttrParsed = false;
2937 // No scoped names are supported; ideally we could put all non-standard
2938 // attributes into namespaces.
2940 switch (AttributeList::getKind(AttrName)) {
2942 case AttributeList::AT_carries_dependency:
2943 case AttributeList::AT_noreturn: {
2944 if (Tok.is(tok::l_paren)) {
2945 Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_arguments)
2946 << AttrName->getName();
2950 attrs.addNew(AttrName, AttrLoc, 0, AttrLoc, 0,
2951 SourceLocation(), 0, 0, false, true);
2961 // Skip the entire parameter clause, if any
2962 if (!AttrParsed && Tok.is(tok::l_paren)) {
2964 // SkipUntil maintains the balancedness of tokens.
2965 SkipUntil(tok::r_paren, false);
2968 if (Tok.is(tok::ellipsis)) {
2970 Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
2971 << AttrName->getName();
2976 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
2977 SkipUntil(tok::r_square, false);
2979 *endLoc = Tok.getLocation();
2980 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
2981 SkipUntil(tok::r_square, false);
2984 /// ParseCXX11Attributes - Parse a C++0x attribute-specifier-seq.
2986 /// attribute-specifier-seq:
2987 /// attribute-specifier-seq[opt] attribute-specifier
2988 void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
2989 SourceLocation *endLoc) {
2990 SourceLocation StartLoc = Tok.getLocation(), Loc;
2995 ParseCXX11AttributeSpecifier(attrs, endLoc);
2996 } while (isCXX11AttributeSpecifier());
2998 attrs.Range = SourceRange(StartLoc, *endLoc);
3001 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
3003 /// [MS] ms-attribute:
3004 /// '[' token-seq ']'
3006 /// [MS] ms-attribute-seq:
3007 /// ms-attribute[opt]
3008 /// ms-attribute ms-attribute-seq
3009 void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
3010 SourceLocation *endLoc) {
3011 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
3013 while (Tok.is(tok::l_square)) {
3014 // FIXME: If this is actually a C++11 attribute, parse it as one.
3016 SkipUntil(tok::r_square, true, true);
3017 if (endLoc) *endLoc = Tok.getLocation();
3018 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare);
3022 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
3023 AccessSpecifier& CurAS) {
3024 IfExistsCondition Result;
3025 if (ParseMicrosoftIfExistsCondition(Result))
3028 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3029 if (Braces.consumeOpen()) {
3030 Diag(Tok, diag::err_expected_lbrace);
3034 switch (Result.Behavior) {
3036 // Parse the declarations below.
3040 Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
3041 << Result.IsIfExists;
3042 // Fall through to skip.
3049 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
3050 // __if_exists, __if_not_exists can nest.
3051 if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
3052 ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS);
3056 // Check for extraneous top-level semicolon.
3057 if (Tok.is(tok::semi)) {
3058 Diag(Tok, diag::ext_extra_struct_semi)
3059 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
3060 << FixItHint::CreateRemoval(Tok.getLocation());
3065 AccessSpecifier AS = getAccessSpecifierIfPresent();
3066 if (AS != AS_none) {
3067 // Current token is a C++ access specifier.
3069 SourceLocation ASLoc = Tok.getLocation();
3071 if (Tok.is(tok::colon))
3072 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation());
3074 Diag(Tok, diag::err_expected_colon);
3079 // Parse all the comma separated declarators.
3080 ParseCXXClassMemberDeclaration(CurAS, 0);
3083 Braces.consumeClose();