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 "RAIIObjectsForParser.h"
22 using namespace clang
;
24 /// ParseNamespace - We know that the current token is a namespace keyword. This
25 /// may either be a top level namespace or a block-level namespace alias. If
26 /// there was an inline keyword, it has already been parsed.
28 /// namespace-definition: [C++ 7.3: basic.namespace]
29 /// named-namespace-definition
30 /// unnamed-namespace-definition
32 /// unnamed-namespace-definition:
33 /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
35 /// named-namespace-definition:
36 /// original-namespace-definition
37 /// extension-namespace-definition
39 /// original-namespace-definition:
40 /// 'inline'[opt] 'namespace' identifier attributes[opt]
41 /// '{' namespace-body '}'
43 /// extension-namespace-definition:
44 /// 'inline'[opt] 'namespace' original-namespace-name
45 /// '{' namespace-body '}'
47 /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
48 /// 'namespace' identifier '=' qualified-namespace-specifier ';'
50 Decl
*Parser::ParseNamespace(unsigned Context
,
51 SourceLocation
&DeclEnd
,
52 SourceLocation InlineLoc
) {
53 assert(Tok
.is(tok::kw_namespace
) && "Not a namespace!");
54 SourceLocation NamespaceLoc
= ConsumeToken(); // eat the 'namespace'.
56 if (Tok
.is(tok::code_completion
)) {
57 Actions
.CodeCompleteNamespaceDecl(getCurScope());
58 ConsumeCodeCompletionToken();
61 SourceLocation IdentLoc
;
62 IdentifierInfo
*Ident
= 0;
66 if (Tok
.is(tok::identifier
)) {
67 Ident
= Tok
.getIdentifierInfo();
68 IdentLoc
= ConsumeToken(); // eat the identifier.
71 // Read label attributes, if present.
72 ParsedAttributes attrs
;
73 if (Tok
.is(tok::kw___attribute
)) {
76 // FIXME: save these somewhere.
77 ParseGNUAttributes(attrs
);
80 if (Tok
.is(tok::equal
)) {
82 Diag(attrTok
, diag::err_unexpected_namespace_attributes_alias
);
83 if (InlineLoc
.isValid())
84 Diag(InlineLoc
, diag::err_inline_namespace_alias
)
85 << FixItHint::CreateRemoval(InlineLoc
);
87 return ParseNamespaceAlias(NamespaceLoc
, IdentLoc
, Ident
, DeclEnd
);
90 if (Tok
.isNot(tok::l_brace
)) {
91 Diag(Tok
, Ident
? diag::err_expected_lbrace
:
92 diag::err_expected_ident_lbrace
);
96 SourceLocation LBrace
= ConsumeBrace();
98 if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
99 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
100 getCurScope()->getFnParent()) {
101 Diag(LBrace
, diag::err_namespace_nonnamespace_scope
);
102 SkipUntil(tok::r_brace
, false);
106 // If we're still good, complain about inline namespaces in non-C++0x now.
107 if (!getLang().CPlusPlus0x
&& InlineLoc
.isValid())
108 Diag(InlineLoc
, diag::ext_inline_namespace
);
110 // Enter a scope for the namespace.
111 ParseScope
NamespaceScope(this, Scope::DeclScope
);
114 Actions
.ActOnStartNamespaceDef(getCurScope(), InlineLoc
, IdentLoc
, Ident
,
115 LBrace
, attrs
.getList());
117 PrettyDeclStackTraceEntry
CrashInfo(Actions
, NamespcDecl
, NamespaceLoc
,
118 "parsing namespace");
120 while (Tok
.isNot(tok::r_brace
) && Tok
.isNot(tok::eof
)) {
121 ParsedAttributesWithRange attrs
;
122 MaybeParseCXX0XAttributes(attrs
);
123 MaybeParseMicrosoftAttributes(attrs
);
124 ParseExternalDeclaration(attrs
);
127 // Leave the namespace scope.
128 NamespaceScope
.Exit();
130 SourceLocation RBraceLoc
= MatchRHSPunctuation(tok::r_brace
, LBrace
);
131 Actions
.ActOnFinishNamespaceDef(NamespcDecl
, RBraceLoc
);
137 /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
138 /// alias definition.
140 Decl
*Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc
,
141 SourceLocation AliasLoc
,
142 IdentifierInfo
*Alias
,
143 SourceLocation
&DeclEnd
) {
144 assert(Tok
.is(tok::equal
) && "Not equal token");
146 ConsumeToken(); // eat the '='.
148 if (Tok
.is(tok::code_completion
)) {
149 Actions
.CodeCompleteNamespaceAliasDecl(getCurScope());
150 ConsumeCodeCompletionToken();
154 // Parse (optional) nested-name-specifier.
155 ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), false);
157 if (SS
.isInvalid() || Tok
.isNot(tok::identifier
)) {
158 Diag(Tok
, diag::err_expected_namespace_name
);
159 // Skip to end of the definition and eat the ';'.
160 SkipUntil(tok::semi
);
165 IdentifierInfo
*Ident
= Tok
.getIdentifierInfo();
166 SourceLocation IdentLoc
= ConsumeToken();
169 DeclEnd
= Tok
.getLocation();
170 ExpectAndConsume(tok::semi
, diag::err_expected_semi_after_namespace_name
,
173 return Actions
.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc
, AliasLoc
, Alias
,
174 SS
, IdentLoc
, Ident
);
177 /// ParseLinkage - We know that the current token is a string_literal
178 /// and just before that, that extern was seen.
180 /// linkage-specification: [C++ 7.5p2: dcl.link]
181 /// 'extern' string-literal '{' declaration-seq[opt] '}'
182 /// 'extern' string-literal declaration
184 Decl
*Parser::ParseLinkage(ParsingDeclSpec
&DS
, unsigned Context
) {
185 assert(Tok
.is(tok::string_literal
) && "Not a string literal!");
186 llvm::SmallString
<8> LangBuffer
;
187 bool Invalid
= false;
188 llvm::StringRef Lang
= PP
.getSpelling(Tok
, LangBuffer
, &Invalid
);
192 SourceLocation Loc
= ConsumeStringToken();
194 ParseScope
LinkageScope(this, Scope::DeclScope
);
196 = Actions
.ActOnStartLinkageSpecification(getCurScope(),
197 /*FIXME: */SourceLocation(),
199 Tok
.is(tok::l_brace
)? Tok
.getLocation()
202 ParsedAttributesWithRange attrs
;
203 MaybeParseCXX0XAttributes(attrs
);
204 MaybeParseMicrosoftAttributes(attrs
);
206 if (Tok
.isNot(tok::l_brace
)) {
207 DS
.setExternInLinkageSpec(true);
208 ParseExternalDeclaration(attrs
, &DS
);
209 return Actions
.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec
,
215 ProhibitAttributes(attrs
);
217 SourceLocation LBrace
= ConsumeBrace();
218 while (Tok
.isNot(tok::r_brace
) && Tok
.isNot(tok::eof
)) {
219 ParsedAttributesWithRange attrs
;
220 MaybeParseCXX0XAttributes(attrs
);
221 MaybeParseMicrosoftAttributes(attrs
);
222 ParseExternalDeclaration(attrs
);
225 SourceLocation RBrace
= MatchRHSPunctuation(tok::r_brace
, LBrace
);
226 return Actions
.ActOnFinishLinkageSpecification(getCurScope(), LinkageSpec
,
230 /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
231 /// using-directive. Assumes that current token is 'using'.
232 Decl
*Parser::ParseUsingDirectiveOrDeclaration(unsigned Context
,
233 const ParsedTemplateInfo
&TemplateInfo
,
234 SourceLocation
&DeclEnd
,
235 ParsedAttributesWithRange
&attrs
) {
236 assert(Tok
.is(tok::kw_using
) && "Not using token");
239 SourceLocation UsingLoc
= ConsumeToken();
241 if (Tok
.is(tok::code_completion
)) {
242 Actions
.CodeCompleteUsing(getCurScope());
243 ConsumeCodeCompletionToken();
246 // 'using namespace' means this is a using-directive.
247 if (Tok
.is(tok::kw_namespace
)) {
248 // Template parameters are always an error here.
249 if (TemplateInfo
.Kind
) {
250 SourceRange R
= TemplateInfo
.getSourceRange();
251 Diag(UsingLoc
, diag::err_templated_using_directive
)
252 << R
<< FixItHint::CreateRemoval(R
);
255 return ParseUsingDirective(Context
, UsingLoc
, DeclEnd
, attrs
);
258 // Otherwise, it must be a using-declaration.
260 // Using declarations can't have attributes.
261 ProhibitAttributes(attrs
);
263 return ParseUsingDeclaration(Context
, TemplateInfo
, UsingLoc
, DeclEnd
);
266 /// ParseUsingDirective - Parse C++ using-directive, assumes
267 /// that current token is 'namespace' and 'using' was already parsed.
269 /// using-directive: [C++ 7.3.p4: namespace.udir]
270 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
272 /// [GNU] using-directive:
273 /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
274 /// namespace-name attributes[opt] ;
276 Decl
*Parser::ParseUsingDirective(unsigned Context
,
277 SourceLocation UsingLoc
,
278 SourceLocation
&DeclEnd
,
279 ParsedAttributes
&attrs
) {
280 assert(Tok
.is(tok::kw_namespace
) && "Not 'namespace' token");
283 SourceLocation NamespcLoc
= ConsumeToken();
285 if (Tok
.is(tok::code_completion
)) {
286 Actions
.CodeCompleteUsingDirective(getCurScope());
287 ConsumeCodeCompletionToken();
291 // Parse (optional) nested-name-specifier.
292 ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), false);
294 IdentifierInfo
*NamespcName
= 0;
295 SourceLocation IdentLoc
= SourceLocation();
297 // Parse namespace-name.
298 if (SS
.isInvalid() || Tok
.isNot(tok::identifier
)) {
299 Diag(Tok
, diag::err_expected_namespace_name
);
300 // If there was invalid namespace name, skip to end of decl, and eat ';'.
301 SkipUntil(tok::semi
);
302 // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
307 NamespcName
= Tok
.getIdentifierInfo();
308 IdentLoc
= ConsumeToken();
310 // Parse (optional) attributes (most likely GNU strong-using extension).
311 bool GNUAttr
= false;
312 if (Tok
.is(tok::kw___attribute
)) {
314 ParseGNUAttributes(attrs
);
318 DeclEnd
= Tok
.getLocation();
319 ExpectAndConsume(tok::semi
,
320 GNUAttr
? diag::err_expected_semi_after_attribute_list
321 : diag::err_expected_semi_after_namespace_name
,
324 return Actions
.ActOnUsingDirective(getCurScope(), UsingLoc
, NamespcLoc
, SS
,
325 IdentLoc
, NamespcName
, attrs
.getList());
328 /// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that
329 /// 'using' was already seen.
331 /// using-declaration: [C++ 7.3.p3: namespace.udecl]
332 /// 'using' 'typename'[opt] ::[opt] nested-name-specifier
334 /// 'using' :: unqualified-id
336 Decl
*Parser::ParseUsingDeclaration(unsigned Context
,
337 const ParsedTemplateInfo
&TemplateInfo
,
338 SourceLocation UsingLoc
,
339 SourceLocation
&DeclEnd
,
340 AccessSpecifier AS
) {
342 SourceLocation TypenameLoc
;
345 // TODO: in C++0x, if we have template parameters this must be a
347 // template <...> using id = type;
349 // Ignore optional 'typename'.
350 // FIXME: This is wrong; we should parse this as a typename-specifier.
351 if (Tok
.is(tok::kw_typename
)) {
352 TypenameLoc
= Tok
.getLocation();
359 // Parse nested-name-specifier.
360 ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), false);
362 // Check nested-name specifier.
363 if (SS
.isInvalid()) {
364 SkipUntil(tok::semi
);
368 // Parse the unqualified-id. We allow parsing of both constructor and
369 // destructor names and allow the action module to diagnose any semantic
372 if (ParseUnqualifiedId(SS
,
373 /*EnteringContext=*/false,
374 /*AllowDestructorName=*/true,
375 /*AllowConstructorName=*/true,
378 SkipUntil(tok::semi
);
382 // Parse (optional) attributes (most likely GNU strong-using extension).
383 ParsedAttributes attrs
;
384 MaybeParseGNUAttributes(attrs
);
387 DeclEnd
= Tok
.getLocation();
388 ExpectAndConsume(tok::semi
, diag::err_expected_semi_after
,
389 !attrs
.empty() ? "attributes list" : "using declaration",
392 // Diagnose an attempt to declare a templated using-declaration.
393 if (TemplateInfo
.Kind
) {
394 SourceRange R
= TemplateInfo
.getSourceRange();
395 Diag(UsingLoc
, diag::err_templated_using_declaration
)
396 << R
<< FixItHint::CreateRemoval(R
);
398 // Unfortunately, we have to bail out instead of recovering by
399 // ignoring the parameters, just in case the nested name specifier
400 // depends on the parameters.
404 return Actions
.ActOnUsingDeclaration(getCurScope(), AS
, true, UsingLoc
, SS
,
405 Name
, attrs
.getList(),
406 IsTypeName
, TypenameLoc
);
409 /// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion.
411 /// static_assert-declaration:
412 /// static_assert ( constant-expression , string-literal ) ;
414 Decl
*Parser::ParseStaticAssertDeclaration(SourceLocation
&DeclEnd
){
415 assert(Tok
.is(tok::kw_static_assert
) && "Not a static_assert declaration");
416 SourceLocation StaticAssertLoc
= ConsumeToken();
418 if (Tok
.isNot(tok::l_paren
)) {
419 Diag(Tok
, diag::err_expected_lparen
);
423 SourceLocation LParenLoc
= ConsumeParen();
425 ExprResult
AssertExpr(ParseConstantExpression());
426 if (AssertExpr
.isInvalid()) {
427 SkipUntil(tok::semi
);
431 if (ExpectAndConsume(tok::comma
, diag::err_expected_comma
, "", tok::semi
))
434 if (Tok
.isNot(tok::string_literal
)) {
435 Diag(Tok
, diag::err_expected_string_literal
);
436 SkipUntil(tok::semi
);
440 ExprResult
AssertMessage(ParseStringLiteralExpression());
441 if (AssertMessage
.isInvalid())
444 MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
446 DeclEnd
= Tok
.getLocation();
447 ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert
);
449 return Actions
.ActOnStaticAssertDeclaration(StaticAssertLoc
,
451 AssertMessage
.take());
454 /// ParseDecltypeSpecifier - Parse a C++0x decltype specifier.
456 /// 'decltype' ( expression )
458 void Parser::ParseDecltypeSpecifier(DeclSpec
&DS
) {
459 assert(Tok
.is(tok::kw_decltype
) && "Not a decltype specifier");
461 SourceLocation StartLoc
= ConsumeToken();
462 SourceLocation LParenLoc
= Tok
.getLocation();
464 if (ExpectAndConsume(tok::l_paren
, diag::err_expected_lparen_after
,
466 SkipUntil(tok::r_paren
);
470 // Parse the expression
472 // C++0x [dcl.type.simple]p4:
473 // The operand of the decltype specifier is an unevaluated operand.
474 EnterExpressionEvaluationContext
Unevaluated(Actions
,
476 ExprResult Result
= ParseExpression();
477 if (Result
.isInvalid()) {
478 SkipUntil(tok::r_paren
);
483 SourceLocation RParenLoc
;
484 if (Tok
.is(tok::r_paren
))
485 RParenLoc
= ConsumeParen();
487 MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
489 if (RParenLoc
.isInvalid())
492 const char *PrevSpec
= 0;
494 // Check for duplicate type specifiers (e.g. "int decltype(a)").
495 if (DS
.SetTypeSpecType(DeclSpec::TST_decltype
, StartLoc
, PrevSpec
,
496 DiagID
, Result
.release()))
497 Diag(StartLoc
, DiagID
) << PrevSpec
;
500 /// ParseClassName - Parse a C++ class-name, which names a class. Note
501 /// that we only check that the result names a type; semantic analysis
502 /// will need to verify that the type names a class. The result is
503 /// either a type or NULL, depending on whether a type name was
506 /// class-name: [C++ 9.1]
508 /// simple-template-id
510 Parser::TypeResult
Parser::ParseClassName(SourceLocation
&EndLocation
,
512 // Check whether we have a template-id that names a type.
513 if (Tok
.is(tok::annot_template_id
)) {
514 TemplateIdAnnotation
*TemplateId
515 = static_cast<TemplateIdAnnotation
*>(Tok
.getAnnotationValue());
516 if (TemplateId
->Kind
== TNK_Type_template
||
517 TemplateId
->Kind
== TNK_Dependent_template_name
) {
518 AnnotateTemplateIdTokenAsType(SS
);
520 assert(Tok
.is(tok::annot_typename
) && "template-id -> type failed");
521 ParsedType Type
= getTypeAnnotation(Tok
);
522 EndLocation
= Tok
.getAnnotationEndLoc();
530 // Fall through to produce an error below.
533 if (Tok
.isNot(tok::identifier
)) {
534 Diag(Tok
, diag::err_expected_class_name
);
538 IdentifierInfo
*Id
= Tok
.getIdentifierInfo();
539 SourceLocation IdLoc
= ConsumeToken();
541 if (Tok
.is(tok::less
)) {
542 // It looks the user intended to write a template-id here, but the
543 // template-name was wrong. Try to fix that.
544 TemplateNameKind TNK
= TNK_Type_template
;
546 if (!Actions
.DiagnoseUnknownTemplateName(*Id
, IdLoc
, getCurScope(),
547 SS
, Template
, TNK
)) {
548 Diag(IdLoc
, diag::err_unknown_template_name
)
555 // Form the template name
556 UnqualifiedId TemplateName
;
557 TemplateName
.setIdentifier(Id
, IdLoc
);
559 // Parse the full template-id, then turn it into a type.
560 if (AnnotateTemplateIdToken(Template
, TNK
, SS
, TemplateName
,
561 SourceLocation(), true))
563 if (TNK
== TNK_Dependent_template_name
)
564 AnnotateTemplateIdTokenAsType(SS
);
566 // If we didn't end up with a typename token, there's nothing more we
568 if (Tok
.isNot(tok::annot_typename
))
571 // Retrieve the type from the annotation token, consume that token, and
573 EndLocation
= Tok
.getAnnotationEndLoc();
574 ParsedType Type
= getTypeAnnotation(Tok
);
579 // We have an identifier; check whether it is actually a type.
580 ParsedType Type
= Actions
.getTypeName(*Id
, IdLoc
, getCurScope(), SS
, true);
582 Diag(IdLoc
, diag::err_expected_class_name
);
586 // Consume the identifier.
589 // Fake up a Declarator to use with ActOnTypeName.
591 DS
.SetRangeStart(IdLoc
);
592 DS
.SetRangeEnd(EndLocation
);
593 DS
.getTypeSpecScope() = *SS
;
595 const char *PrevSpec
= 0;
597 DS
.SetTypeSpecType(TST_typename
, IdLoc
, PrevSpec
, DiagID
, Type
);
599 Declarator
DeclaratorInfo(DS
, Declarator::TypeNameContext
);
600 return Actions
.ActOnTypeName(getCurScope(), DeclaratorInfo
);
603 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
604 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
605 /// until we reach the start of a definition or see a token that
606 /// cannot start a definition. If SuppressDeclarations is true, we do know.
608 /// class-specifier: [C++ class]
609 /// class-head '{' member-specification[opt] '}'
610 /// class-head '{' member-specification[opt] '}' attributes[opt]
612 /// class-key identifier[opt] base-clause[opt]
613 /// class-key nested-name-specifier identifier base-clause[opt]
614 /// class-key nested-name-specifier[opt] simple-template-id
616 /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
617 /// [GNU] class-key attributes[opt] nested-name-specifier
618 /// identifier base-clause[opt]
619 /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
620 /// simple-template-id base-clause[opt]
626 /// elaborated-type-specifier: [C++ dcl.type.elab]
627 /// class-key ::[opt] nested-name-specifier[opt] identifier
628 /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
629 /// simple-template-id
631 /// Note that the C++ class-specifier and elaborated-type-specifier,
632 /// together, subsume the C99 struct-or-union-specifier:
634 /// struct-or-union-specifier: [C99 6.7.2.1]
635 /// struct-or-union identifier[opt] '{' struct-contents '}'
636 /// struct-or-union identifier
637 /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
638 /// '}' attributes[opt]
639 /// [GNU] struct-or-union attributes[opt] identifier
643 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind
,
644 SourceLocation StartLoc
, DeclSpec
&DS
,
645 const ParsedTemplateInfo
&TemplateInfo
,
646 AccessSpecifier AS
, bool SuppressDeclarations
){
647 DeclSpec::TST TagType
;
648 if (TagTokKind
== tok::kw_struct
)
649 TagType
= DeclSpec::TST_struct
;
650 else if (TagTokKind
== tok::kw_class
)
651 TagType
= DeclSpec::TST_class
;
653 assert(TagTokKind
== tok::kw_union
&& "Not a class specifier");
654 TagType
= DeclSpec::TST_union
;
657 if (Tok
.is(tok::code_completion
)) {
658 // Code completion for a struct, class, or union name.
659 Actions
.CodeCompleteTag(getCurScope(), TagType
);
660 ConsumeCodeCompletionToken();
663 // C++03 [temp.explicit] 14.7.2/8:
664 // The usual access checking rules do not apply to names used to specify
665 // explicit instantiations.
667 // As an extension we do not perform access checking on the names used to
668 // specify explicit specializations either. This is important to allow
669 // specializing traits classes for private types.
670 bool SuppressingAccessChecks
= false;
671 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
||
672 TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitSpecialization
) {
673 Actions
.ActOnStartSuppressingAccessChecks();
674 SuppressingAccessChecks
= true;
677 ParsedAttributes attrs
;
678 // If attributes exist after tag, parse them.
679 if (Tok
.is(tok::kw___attribute
))
680 ParseGNUAttributes(attrs
);
682 // If declspecs exist after tag, parse them.
683 while (Tok
.is(tok::kw___declspec
))
684 ParseMicrosoftDeclSpec(attrs
);
686 // If C++0x attributes exist here, parse them.
687 // FIXME: Are we consistent with the ordering of parsing of different
688 // styles of attributes?
689 MaybeParseCXX0XAttributes(attrs
);
691 if (TagType
== DeclSpec::TST_struct
&& Tok
.is(tok::kw___is_pod
)) {
692 // GNU libstdc++ 4.2 uses __is_pod as the name of a struct template, but
693 // __is_pod is a keyword in GCC >= 4.3. Therefore, when we see the
694 // token sequence "struct __is_pod", make __is_pod into a normal
695 // identifier rather than a keyword, to allow libstdc++ 4.2 to work
697 Tok
.getIdentifierInfo()->RevertTokenIDToIdentifier();
698 Tok
.setKind(tok::identifier
);
701 if (TagType
== DeclSpec::TST_struct
&& Tok
.is(tok::kw___is_empty
)) {
702 // GNU libstdc++ 4.2 uses __is_empty as the name of a struct template, but
703 // __is_empty is a keyword in GCC >= 4.3. Therefore, when we see the
704 // token sequence "struct __is_empty", make __is_empty into a normal
705 // identifier rather than a keyword, to allow libstdc++ 4.2 to work
707 Tok
.getIdentifierInfo()->RevertTokenIDToIdentifier();
708 Tok
.setKind(tok::identifier
);
711 // Parse the (optional) nested-name-specifier.
712 CXXScopeSpec
&SS
= DS
.getTypeSpecScope();
713 if (getLang().CPlusPlus
) {
714 // "FOO : BAR" is not a potential typo for "FOO::BAR".
715 ColonProtectionRAIIObject
X(*this);
717 if (ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), true))
718 DS
.SetTypeSpecError();
720 if (Tok
.isNot(tok::identifier
) && Tok
.isNot(tok::annot_template_id
))
721 Diag(Tok
, diag::err_expected_ident
);
724 TemplateParameterLists
*TemplateParams
= TemplateInfo
.TemplateParams
;
726 // Parse the (optional) class name or simple-template-id.
727 IdentifierInfo
*Name
= 0;
728 SourceLocation NameLoc
;
729 TemplateIdAnnotation
*TemplateId
= 0;
730 if (Tok
.is(tok::identifier
)) {
731 Name
= Tok
.getIdentifierInfo();
732 NameLoc
= ConsumeToken();
734 if (Tok
.is(tok::less
) && getLang().CPlusPlus
) {
735 // The name was supposed to refer to a template, but didn't.
736 // Eat the template argument list and try to continue parsing this as
737 // a class (or template thereof).
738 TemplateArgList TemplateArgs
;
739 SourceLocation LAngleLoc
, RAngleLoc
;
740 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc
, &SS
,
742 TemplateArgs
, RAngleLoc
)) {
743 // We couldn't parse the template argument list at all, so don't
744 // try to give any location information for the list.
745 LAngleLoc
= RAngleLoc
= SourceLocation();
748 Diag(NameLoc
, diag::err_explicit_spec_non_template
)
749 << (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
)
750 << (TagType
== DeclSpec::TST_class
? 0
751 : TagType
== DeclSpec::TST_struct
? 1
754 << SourceRange(LAngleLoc
, RAngleLoc
);
756 // Strip off the last template parameter list if it was empty, since
757 // we've removed its template argument list.
758 if (TemplateParams
&& TemplateInfo
.LastParameterListWasEmpty
) {
759 if (TemplateParams
&& TemplateParams
->size() > 1) {
760 TemplateParams
->pop_back();
763 const_cast<ParsedTemplateInfo
&>(TemplateInfo
).Kind
764 = ParsedTemplateInfo::NonTemplate
;
766 } else if (TemplateInfo
.Kind
767 == ParsedTemplateInfo::ExplicitInstantiation
) {
768 // Pretend this is just a forward declaration.
770 const_cast<ParsedTemplateInfo
&>(TemplateInfo
).Kind
771 = ParsedTemplateInfo::NonTemplate
;
772 const_cast<ParsedTemplateInfo
&>(TemplateInfo
).TemplateLoc
774 const_cast<ParsedTemplateInfo
&>(TemplateInfo
).ExternLoc
778 } else if (Tok
.is(tok::annot_template_id
)) {
779 TemplateId
= static_cast<TemplateIdAnnotation
*>(Tok
.getAnnotationValue());
780 NameLoc
= ConsumeToken();
782 if (TemplateId
->Kind
!= TNK_Type_template
) {
783 // The template-name in the simple-template-id refers to
784 // something other than a class template. Give an appropriate
785 // error message and skip to the ';'.
786 SourceRange
Range(NameLoc
);
788 Range
.setBegin(SS
.getBeginLoc());
790 Diag(TemplateId
->LAngleLoc
, diag::err_template_spec_syntax_non_template
)
791 << Name
<< static_cast<int>(TemplateId
->Kind
) << Range
;
793 DS
.SetTypeSpecError();
794 SkipUntil(tok::semi
, false, true);
795 TemplateId
->Destroy();
796 if (SuppressingAccessChecks
)
797 Actions
.ActOnStopSuppressingAccessChecks();
803 // As soon as we're finished parsing the class's template-id, turn access
805 if (SuppressingAccessChecks
)
806 Actions
.ActOnStopSuppressingAccessChecks();
808 // There are four options here. If we have 'struct foo;', then this
809 // is either a forward declaration or a friend declaration, which
810 // have to be treated differently. If we have 'struct foo {...',
811 // 'struct foo :...' or 'struct foo <class-virt-specifier>' then this is a
812 // definition. Otherwise we have something like 'struct foo xyz', a reference.
813 // However, in some contexts, things look like declarations but are just
817 // &T::operator struct s;
818 // For these, SuppressDeclarations is true.
819 Sema::TagUseKind TUK
;
820 if (SuppressDeclarations
)
821 TUK
= Sema::TUK_Reference
;
822 else if (Tok
.is(tok::l_brace
) ||
823 (getLang().CPlusPlus
&& Tok
.is(tok::colon
)) ||
824 isCXX0XClassVirtSpecifier() != ClassVirtSpecifiers::CVS_None
) {
825 if (DS
.isFriendSpecified()) {
826 // C++ [class.friend]p2:
827 // A class shall not be defined in a friend declaration.
828 Diag(Tok
.getLocation(), diag::err_friend_decl_defines_class
)
829 << SourceRange(DS
.getFriendSpecLoc());
831 // Skip everything up to the semicolon, so that this looks like a proper
832 // friend class (or template thereof) declaration.
833 SkipUntil(tok::semi
, true, true);
834 TUK
= Sema::TUK_Friend
;
836 // Okay, this is a class definition.
837 TUK
= Sema::TUK_Definition
;
839 } else if (Tok
.is(tok::semi
))
840 TUK
= DS
.isFriendSpecified() ? Sema::TUK_Friend
: Sema::TUK_Declaration
;
842 TUK
= Sema::TUK_Reference
;
844 if (!Name
&& !TemplateId
&& (DS
.getTypeSpecType() == DeclSpec::TST_error
||
845 TUK
!= Sema::TUK_Definition
)) {
846 if (DS
.getTypeSpecType() != DeclSpec::TST_error
) {
847 // We have a declaration or reference to an anonymous class.
848 Diag(StartLoc
, diag::err_anon_type_definition
)
849 << DeclSpec::getSpecifierName(TagType
);
852 SkipUntil(tok::comma
, true);
855 TemplateId
->Destroy();
859 // Create the tag portion of the class or class template.
860 DeclResult TagOrTempResult
= true; // invalid
861 TypeResult TypeResult
= true; // invalid
865 // Explicit specialization, class template partial specialization,
866 // or explicit instantiation.
867 ASTTemplateArgsPtr
TemplateArgsPtr(Actions
,
868 TemplateId
->getTemplateArgs(),
869 TemplateId
->NumArgs
);
870 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
&&
871 TUK
== Sema::TUK_Declaration
) {
872 // This is an explicit instantiation of a class template.
874 = Actions
.ActOnExplicitInstantiation(getCurScope(),
875 TemplateInfo
.ExternLoc
,
876 TemplateInfo
.TemplateLoc
,
880 TemplateId
->Template
,
881 TemplateId
->TemplateNameLoc
,
882 TemplateId
->LAngleLoc
,
884 TemplateId
->RAngleLoc
,
887 // Friend template-ids are treated as references unless
888 // they have template headers, in which case they're ill-formed
889 // (FIXME: "template <class T> friend class A<T>::B<int>;").
890 // We diagnose this error in ActOnClassTemplateSpecialization.
891 } else if (TUK
== Sema::TUK_Reference
||
892 (TUK
== Sema::TUK_Friend
&&
893 TemplateInfo
.Kind
== ParsedTemplateInfo::NonTemplate
)) {
895 = Actions
.ActOnTemplateIdType(TemplateId
->Template
,
896 TemplateId
->TemplateNameLoc
,
897 TemplateId
->LAngleLoc
,
899 TemplateId
->RAngleLoc
);
901 TypeResult
= Actions
.ActOnTagTemplateIdType(SS
, TypeResult
, TUK
,
904 // This is an explicit specialization or a class template
905 // partial specialization.
906 TemplateParameterLists FakedParamLists
;
908 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
) {
909 // This looks like an explicit instantiation, because we have
912 // template class Foo<X>
914 // but it actually has a definition. Most likely, this was
915 // meant to be an explicit specialization, but the user forgot
916 // the '<>' after 'template'.
917 assert(TUK
== Sema::TUK_Definition
&& "Expected a definition here");
919 SourceLocation LAngleLoc
920 = PP
.getLocForEndOfToken(TemplateInfo
.TemplateLoc
);
921 Diag(TemplateId
->TemplateNameLoc
,
922 diag::err_explicit_instantiation_with_definition
)
923 << SourceRange(TemplateInfo
.TemplateLoc
)
924 << FixItHint::CreateInsertion(LAngleLoc
, "<>");
926 // Create a fake template parameter list that contains only
927 // "template<>", so that we treat this construct as a class
928 // template specialization.
929 FakedParamLists
.push_back(
930 Actions
.ActOnTemplateParameterList(0, SourceLocation(),
931 TemplateInfo
.TemplateLoc
,
935 TemplateParams
= &FakedParamLists
;
938 // Build the class template specialization.
940 = Actions
.ActOnClassTemplateSpecialization(getCurScope(), TagType
, TUK
,
942 TemplateId
->Template
,
943 TemplateId
->TemplateNameLoc
,
944 TemplateId
->LAngleLoc
,
946 TemplateId
->RAngleLoc
,
948 MultiTemplateParamsArg(Actions
,
949 TemplateParams
? &(*TemplateParams
)[0] : 0,
950 TemplateParams
? TemplateParams
->size() : 0));
952 TemplateId
->Destroy();
953 } else if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
&&
954 TUK
== Sema::TUK_Declaration
) {
955 // Explicit instantiation of a member of a class template
956 // specialization, e.g.,
958 // template struct Outer<int>::Inner;
961 = Actions
.ActOnExplicitInstantiation(getCurScope(),
962 TemplateInfo
.ExternLoc
,
963 TemplateInfo
.TemplateLoc
,
964 TagType
, StartLoc
, SS
, Name
,
965 NameLoc
, attrs
.getList());
966 } else if (TUK
== Sema::TUK_Friend
&&
967 TemplateInfo
.Kind
!= ParsedTemplateInfo::NonTemplate
) {
969 Actions
.ActOnTemplatedFriendTag(getCurScope(), DS
.getFriendSpecLoc(),
970 TagType
, StartLoc
, SS
,
971 Name
, NameLoc
, attrs
.getList(),
972 MultiTemplateParamsArg(Actions
,
973 TemplateParams
? &(*TemplateParams
)[0] : 0,
974 TemplateParams
? TemplateParams
->size() : 0));
976 if (TemplateInfo
.Kind
== ParsedTemplateInfo::ExplicitInstantiation
&&
977 TUK
== Sema::TUK_Definition
) {
978 // FIXME: Diagnose this particular error.
981 bool IsDependent
= false;
983 // Don't pass down template parameter lists if this is just a tag
984 // reference. For example, we don't need the template parameters here:
985 // template <class T> class A *makeA(T t);
986 MultiTemplateParamsArg TParams
;
987 if (TUK
!= Sema::TUK_Reference
&& TemplateParams
)
989 MultiTemplateParamsArg(&(*TemplateParams
)[0], TemplateParams
->size());
991 // Declaration or definition of a class type
992 TagOrTempResult
= Actions
.ActOnTag(getCurScope(), TagType
, TUK
, StartLoc
,
993 SS
, Name
, NameLoc
, attrs
.getList(), AS
,
994 TParams
, Owned
, IsDependent
, false,
995 false, clang::TypeResult());
997 // If ActOnTag said the type was dependent, try again with the
1000 assert(TUK
== Sema::TUK_Reference
|| TUK
== Sema::TUK_Friend
);
1001 TypeResult
= Actions
.ActOnDependentTag(getCurScope(), TagType
, TUK
,
1002 SS
, Name
, StartLoc
, NameLoc
);
1006 // If there is a body, parse it and inform the actions module.
1007 if (TUK
== Sema::TUK_Definition
) {
1008 assert(Tok
.is(tok::l_brace
) ||
1009 (getLang().CPlusPlus
&& Tok
.is(tok::colon
)) ||
1010 isCXX0XClassVirtSpecifier() != ClassVirtSpecifiers::CVS_None
);
1011 if (getLang().CPlusPlus
)
1012 ParseCXXMemberSpecification(StartLoc
, TagType
, TagOrTempResult
.get());
1014 ParseStructUnionBody(StartLoc
, TagType
, TagOrTempResult
.get());
1017 // FIXME: The DeclSpec should keep the locations of both the keyword and the
1018 // name (if there is one).
1019 SourceLocation TSTLoc
= NameLoc
.isValid()? NameLoc
: StartLoc
;
1021 const char *PrevSpec
= 0;
1024 if (!TypeResult
.isInvalid()) {
1025 Result
= DS
.SetTypeSpecType(DeclSpec::TST_typename
, TSTLoc
,
1026 PrevSpec
, DiagID
, TypeResult
.get());
1027 } else if (!TagOrTempResult
.isInvalid()) {
1028 Result
= DS
.SetTypeSpecType(TagType
, TSTLoc
, PrevSpec
, DiagID
,
1029 TagOrTempResult
.get(), Owned
);
1031 DS
.SetTypeSpecError();
1036 Diag(StartLoc
, DiagID
) << PrevSpec
;
1038 // At this point, we've successfully parsed a class-specifier in 'definition'
1039 // form (e.g. "struct foo { int x; }". While we could just return here, we're
1040 // going to look at what comes after it to improve error recovery. If an
1041 // impossible token occurs next, we assume that the programmer forgot a ; at
1042 // the end of the declaration and recover that way.
1044 // This switch enumerates the valid "follow" set for definition.
1045 if (TUK
== Sema::TUK_Definition
) {
1046 bool ExpectedSemi
= true;
1047 switch (Tok
.getKind()) {
1049 case tok::semi
: // struct foo {...} ;
1050 case tok::star
: // struct foo {...} * P;
1051 case tok::amp
: // struct foo {...} & R = ...
1052 case tok::identifier
: // struct foo {...} V ;
1053 case tok::r_paren
: //(struct foo {...} ) {4}
1054 case tok::annot_cxxscope
: // struct foo {...} a:: b;
1055 case tok::annot_typename
: // struct foo {...} a ::b;
1056 case tok::annot_template_id
: // struct foo {...} a<int> ::b;
1057 case tok::l_paren
: // struct foo {...} ( x);
1058 case tok::comma
: // __builtin_offsetof(struct foo{...} ,
1059 ExpectedSemi
= false;
1062 case tok::kw_const
: // struct foo {...} const x;
1063 case tok::kw_volatile
: // struct foo {...} volatile x;
1064 case tok::kw_restrict
: // struct foo {...} restrict x;
1065 case tok::kw_inline
: // struct foo {...} inline foo() {};
1066 // Storage-class specifiers
1067 case tok::kw_static
: // struct foo {...} static x;
1068 case tok::kw_extern
: // struct foo {...} extern x;
1069 case tok::kw_typedef
: // struct foo {...} typedef x;
1070 case tok::kw_register
: // struct foo {...} register x;
1071 case tok::kw_auto
: // struct foo {...} auto x;
1072 case tok::kw_mutable
: // struct foo {...} mutable x;
1073 // As shown above, type qualifiers and storage class specifiers absolutely
1074 // can occur after class specifiers according to the grammar. However,
1075 // almost noone actually writes code like this. If we see one of these,
1076 // it is much more likely that someone missed a semi colon and the
1077 // type/storage class specifier we're seeing is part of the *next*
1078 // intended declaration, as in:
1080 // struct foo { ... }
1083 // We'd really like to emit a missing semicolon error instead of emitting
1084 // an error on the 'int' saying that you can't have two type specifiers in
1085 // the same declaration of X. Because of this, we look ahead past this
1086 // token to see if it's a type specifier. If so, we know the code is
1087 // otherwise invalid, so we can produce the expected semi error.
1088 if (!isKnownToBeTypeSpecifier(NextToken()))
1089 ExpectedSemi
= false;
1092 case tok::r_brace
: // struct bar { struct foo {...} }
1093 // Missing ';' at end of struct is accepted as an extension in C mode.
1094 if (!getLang().CPlusPlus
)
1095 ExpectedSemi
= false;
1100 ExpectAndConsume(tok::semi
, diag::err_expected_semi_after_tagdecl
,
1101 TagType
== DeclSpec::TST_class
? "class"
1102 : TagType
== DeclSpec::TST_struct
? "struct" : "union");
1103 // Push this token back into the preprocessor and change our current token
1104 // to ';' so that the rest of the code recovers as though there were an
1105 // ';' after the definition.
1107 Tok
.setKind(tok::semi
);
1112 /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
1114 /// base-clause : [C++ class.derived]
1115 /// ':' base-specifier-list
1116 /// base-specifier-list:
1117 /// base-specifier '...'[opt]
1118 /// base-specifier-list ',' base-specifier '...'[opt]
1119 void Parser::ParseBaseClause(Decl
*ClassDecl
) {
1120 assert(Tok
.is(tok::colon
) && "Not a base clause");
1123 // Build up an array of parsed base specifiers.
1124 llvm::SmallVector
<CXXBaseSpecifier
*, 8> BaseInfo
;
1127 // Parse a base-specifier.
1128 BaseResult Result
= ParseBaseSpecifier(ClassDecl
);
1129 if (Result
.isInvalid()) {
1130 // Skip the rest of this base specifier, up until the comma or
1132 SkipUntil(tok::comma
, tok::l_brace
, true, true);
1134 // Add this to our array of base specifiers.
1135 BaseInfo
.push_back(Result
.get());
1138 // If the next token is a comma, consume it and keep reading
1140 if (Tok
.isNot(tok::comma
)) break;
1142 // Consume the comma.
1146 // Attach the base specifiers
1147 Actions
.ActOnBaseSpecifiers(ClassDecl
, BaseInfo
.data(), BaseInfo
.size());
1150 /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
1151 /// one entry in the base class list of a class specifier, for example:
1152 /// class foo : public bar, virtual private baz {
1153 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1155 /// base-specifier: [C++ class.derived]
1156 /// ::[opt] nested-name-specifier[opt] class-name
1157 /// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt]
1159 /// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt]
1161 Parser::BaseResult
Parser::ParseBaseSpecifier(Decl
*ClassDecl
) {
1162 bool IsVirtual
= false;
1163 SourceLocation StartLoc
= Tok
.getLocation();
1165 // Parse the 'virtual' keyword.
1166 if (Tok
.is(tok::kw_virtual
)) {
1171 // Parse an (optional) access specifier.
1172 AccessSpecifier Access
= getAccessSpecifierIfPresent();
1173 if (Access
!= AS_none
)
1176 // Parse the 'virtual' keyword (again!), in case it came after the
1177 // access specifier.
1178 if (Tok
.is(tok::kw_virtual
)) {
1179 SourceLocation VirtualLoc
= ConsumeToken();
1181 // Complain about duplicate 'virtual'
1182 Diag(VirtualLoc
, diag::err_dup_virtual
)
1183 << FixItHint::CreateRemoval(VirtualLoc
);
1189 // Parse optional '::' and optional nested-name-specifier.
1191 ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), /*EnteringContext=*/false);
1193 // The location of the base class itself.
1194 SourceLocation BaseLoc
= Tok
.getLocation();
1196 // Parse the class-name.
1197 SourceLocation EndLocation
;
1198 TypeResult BaseType
= ParseClassName(EndLocation
, &SS
);
1199 if (BaseType
.isInvalid())
1202 // Parse the optional ellipsis (for a pack expansion). The ellipsis is
1203 // actually part of the base-specifier-list grammar productions, but we
1204 // parse it here for convenience.
1205 SourceLocation EllipsisLoc
;
1206 if (Tok
.is(tok::ellipsis
))
1207 EllipsisLoc
= ConsumeToken();
1209 // Find the complete source range for the base-specifier.
1210 SourceRange
Range(StartLoc
, EndLocation
);
1212 // Notify semantic analysis that we have parsed a complete
1214 return Actions
.ActOnBaseSpecifier(ClassDecl
, Range
, IsVirtual
, Access
,
1215 BaseType
.get(), BaseLoc
, EllipsisLoc
);
1218 /// getAccessSpecifierIfPresent - Determine whether the next token is
1219 /// a C++ access-specifier.
1221 /// access-specifier: [C++ class.derived]
1225 AccessSpecifier
Parser::getAccessSpecifierIfPresent() const {
1226 switch (Tok
.getKind()) {
1227 default: return AS_none
;
1228 case tok::kw_private
: return AS_private
;
1229 case tok::kw_protected
: return AS_protected
;
1230 case tok::kw_public
: return AS_public
;
1234 void Parser::HandleMemberFunctionDefaultArgs(Declarator
& DeclaratorInfo
,
1236 // We just declared a member function. If this member function
1237 // has any default arguments, we'll need to parse them later.
1238 LateParsedMethodDeclaration
*LateMethod
= 0;
1239 DeclaratorChunk::FunctionTypeInfo
&FTI
1240 = DeclaratorInfo
.getFunctionTypeInfo();
1241 for (unsigned ParamIdx
= 0; ParamIdx
< FTI
.NumArgs
; ++ParamIdx
) {
1242 if (LateMethod
|| FTI
.ArgInfo
[ParamIdx
].DefaultArgTokens
) {
1244 // Push this method onto the stack of late-parsed method
1246 LateMethod
= new LateParsedMethodDeclaration(this, ThisDecl
);
1247 getCurrentClass().LateParsedDeclarations
.push_back(LateMethod
);
1248 LateMethod
->TemplateScope
= getCurScope()->isTemplateParamScope();
1250 // Add all of the parameters prior to this one (they don't
1251 // have default arguments).
1252 LateMethod
->DefaultArgs
.reserve(FTI
.NumArgs
);
1253 for (unsigned I
= 0; I
< ParamIdx
; ++I
)
1254 LateMethod
->DefaultArgs
.push_back(
1255 LateParsedDefaultArgument(FTI
.ArgInfo
[I
].Param
));
1258 // Add this parameter to the list of parameters (it or may
1259 // not have a default argument).
1260 LateMethod
->DefaultArgs
.push_back(
1261 LateParsedDefaultArgument(FTI
.ArgInfo
[ParamIdx
].Param
,
1262 FTI
.ArgInfo
[ParamIdx
].DefaultArgTokens
));
1267 /// isCXX0XVirtSpecifier - Determine whether the next token is a C++0x
1274 VirtSpecifiers::Specifier
Parser::isCXX0XVirtSpecifier() const {
1275 if (!getLang().CPlusPlus
)
1276 return VirtSpecifiers::VS_None
;
1278 if (Tok
.is(tok::kw_new
))
1279 return VirtSpecifiers::VS_New
;
1281 if (Tok
.is(tok::identifier
)) {
1282 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
1284 // Initialize the contextual keywords.
1286 Ident_final
= &PP
.getIdentifierTable().get("final");
1287 Ident_override
= &PP
.getIdentifierTable().get("override");
1290 if (II
== Ident_override
)
1291 return VirtSpecifiers::VS_Override
;
1293 if (II
== Ident_final
)
1294 return VirtSpecifiers::VS_Final
;
1297 return VirtSpecifiers::VS_None
;
1300 /// ParseOptionalCXX0XVirtSpecifierSeq - Parse a virt-specifier-seq.
1302 /// virt-specifier-seq:
1304 /// virt-specifier-seq virt-specifier
1305 void Parser::ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers
&VS
) {
1307 VirtSpecifiers::Specifier Specifier
= isCXX0XVirtSpecifier();
1308 if (Specifier
== VirtSpecifiers::VS_None
)
1311 // C++ [class.mem]p8:
1312 // A virt-specifier-seq shall contain at most one of each virt-specifier.
1313 const char *PrevSpec
= 0;
1314 if (VS
.SetSpecifier(Specifier
, Tok
.getLocation(), PrevSpec
))
1315 Diag(Tok
.getLocation(), diag::err_duplicate_virt_specifier
)
1317 << FixItHint::CreateRemoval(Tok
.getLocation());
1319 if (!getLang().CPlusPlus0x
)
1320 Diag(Tok
.getLocation(), diag::ext_override_control_keyword
)
1321 << VirtSpecifiers::getSpecifierName(Specifier
);
1326 /// isCXX0XClassVirtSpecifier - Determine whether the next token is a C++0x
1327 /// class-virt-specifier.
1329 /// class-virt-specifier:
1332 ClassVirtSpecifiers::Specifier
Parser::isCXX0XClassVirtSpecifier() const {
1333 if (!getLang().CPlusPlus
)
1334 return ClassVirtSpecifiers::CVS_None
;
1336 if (Tok
.is(tok::kw_explicit
))
1337 return ClassVirtSpecifiers::CVS_Explicit
;
1339 if (Tok
.is(tok::identifier
)) {
1340 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
1342 // Initialize the contextual keywords.
1344 Ident_final
= &PP
.getIdentifierTable().get("final");
1345 Ident_override
= &PP
.getIdentifierTable().get("override");
1348 if (II
== Ident_final
)
1349 return ClassVirtSpecifiers::CVS_Final
;
1352 return ClassVirtSpecifiers::CVS_None
;
1355 /// ParseOptionalCXX0XClassVirtSpecifierSeq - Parse a class-virt-specifier-seq.
1357 /// class-virt-specifier-seq:
1358 /// class-virt-specifier
1359 /// class-virt-specifier-seq class-virt-specifier
1360 void Parser::ParseOptionalCXX0XClassVirtSpecifierSeq(ClassVirtSpecifiers
&CVS
) {
1362 ClassVirtSpecifiers::Specifier Specifier
= isCXX0XClassVirtSpecifier();
1363 if (Specifier
== ClassVirtSpecifiers::CVS_None
)
1367 // A class-virt-specifier-seq shall contain at most one of each
1368 // class-virt-specifier.
1369 const char *PrevSpec
= 0;
1370 if (CVS
.SetSpecifier(Specifier
, Tok
.getLocation(), PrevSpec
))
1371 Diag(Tok
.getLocation(), diag::err_duplicate_class_virt_specifier
)
1373 << FixItHint::CreateRemoval(Tok
.getLocation());
1375 if (!getLang().CPlusPlus0x
)
1376 Diag(Tok
.getLocation(), diag::ext_override_control_keyword
)
1377 << ClassVirtSpecifiers::getSpecifierName(Specifier
);
1383 /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
1385 /// member-declaration:
1386 /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
1387 /// function-definition ';'[opt]
1388 /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
1389 /// using-declaration [TODO]
1390 /// [C++0x] static_assert-declaration
1391 /// template-declaration
1392 /// [GNU] '__extension__' member-declaration
1394 /// member-declarator-list:
1395 /// member-declarator
1396 /// member-declarator-list ',' member-declarator
1398 /// member-declarator:
1399 /// declarator virt-specifier-seq[opt] pure-specifier[opt]
1400 /// declarator constant-initializer[opt]
1401 /// identifier[opt] ':' constant-expression
1403 /// virt-specifier-seq:
1405 /// virt-specifier-seq virt-specifier
1415 /// constant-initializer:
1416 /// '=' constant-expression
1418 void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS
,
1419 const ParsedTemplateInfo
&TemplateInfo
,
1420 ParsingDeclRAIIObject
*TemplateDiags
) {
1421 // Access declarations.
1422 if (!TemplateInfo
.Kind
&&
1423 (Tok
.is(tok::identifier
) || Tok
.is(tok::coloncolon
)) &&
1424 !TryAnnotateCXXScopeToken() &&
1425 Tok
.is(tok::annot_cxxscope
)) {
1426 bool isAccessDecl
= false;
1427 if (NextToken().is(tok::identifier
))
1428 isAccessDecl
= GetLookAheadToken(2).is(tok::semi
);
1430 isAccessDecl
= NextToken().is(tok::kw_operator
);
1433 // Collect the scope specifier token we annotated earlier.
1435 ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), false);
1437 // Try to parse an unqualified-id.
1439 if (ParseUnqualifiedId(SS
, false, true, true, ParsedType(), Name
)) {
1440 SkipUntil(tok::semi
);
1444 // TODO: recover from mistakenly-qualified operator declarations.
1445 if (ExpectAndConsume(tok::semi
,
1446 diag::err_expected_semi_after
,
1447 "access declaration",
1451 Actions
.ActOnUsingDeclaration(getCurScope(), AS
,
1452 false, SourceLocation(),
1455 /* IsTypeName */ false,
1461 // static_assert-declaration
1462 if (Tok
.is(tok::kw_static_assert
)) {
1463 // FIXME: Check for templates
1464 SourceLocation DeclEnd
;
1465 ParseStaticAssertDeclaration(DeclEnd
);
1469 if (Tok
.is(tok::kw_template
)) {
1470 assert(!TemplateInfo
.TemplateParams
&&
1471 "Nested template improperly parsed?");
1472 SourceLocation DeclEnd
;
1473 ParseDeclarationStartingWithTemplate(Declarator::MemberContext
, DeclEnd
,
1478 // Handle: member-declaration ::= '__extension__' member-declaration
1479 if (Tok
.is(tok::kw___extension__
)) {
1480 // __extension__ silences extension warnings in the subexpression.
1481 ExtensionRAIIObject
O(Diags
); // Use RAII to do this.
1483 return ParseCXXClassMemberDeclaration(AS
, TemplateInfo
, TemplateDiags
);
1486 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it
1488 ColonProtectionRAIIObject
X(*this);
1490 ParsedAttributesWithRange attrs
;
1491 // Optional C++0x attribute-specifier
1492 MaybeParseCXX0XAttributes(attrs
);
1493 MaybeParseMicrosoftAttributes(attrs
);
1495 if (Tok
.is(tok::kw_using
)) {
1496 // FIXME: Check for template aliases
1498 ProhibitAttributes(attrs
);
1501 SourceLocation UsingLoc
= ConsumeToken();
1503 if (Tok
.is(tok::kw_namespace
)) {
1504 Diag(UsingLoc
, diag::err_using_namespace_in_class
);
1505 SkipUntil(tok::semi
, true, true);
1507 SourceLocation DeclEnd
;
1508 // Otherwise, it must be using-declaration.
1509 ParseUsingDeclaration(Declarator::MemberContext
, TemplateInfo
,
1510 UsingLoc
, DeclEnd
, AS
);
1515 // decl-specifier-seq:
1516 // Parse the common declaration-specifiers piece.
1517 ParsingDeclSpec
DS(*this, TemplateDiags
);
1518 DS
.takeAttributesFrom(attrs
);
1519 ParseDeclarationSpecifiers(DS
, TemplateInfo
, AS
, DSC_class
);
1521 MultiTemplateParamsArg
TemplateParams(Actions
,
1522 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->data() : 0,
1523 TemplateInfo
.TemplateParams
? TemplateInfo
.TemplateParams
->size() : 0);
1525 if (Tok
.is(tok::semi
)) {
1528 Actions
.ParsedFreeStandingDeclSpec(getCurScope(), AS
, DS
);
1529 DS
.complete(TheDecl
);
1533 ParsingDeclarator
DeclaratorInfo(*this, DS
, Declarator::MemberContext
);
1536 if (Tok
.isNot(tok::colon
)) {
1537 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
1538 ColonProtectionRAIIObject
X(*this);
1540 // Parse the first declarator.
1541 ParseDeclarator(DeclaratorInfo
);
1542 // Error parsing the declarator?
1543 if (!DeclaratorInfo
.hasName()) {
1544 // If so, skip until the semi-colon or a }.
1545 SkipUntil(tok::r_brace
, true);
1546 if (Tok
.is(tok::semi
))
1551 ParseOptionalCXX0XVirtSpecifierSeq(VS
);
1553 // If attributes exist after the declarator, but before an '{', parse them.
1554 MaybeParseGNUAttributes(DeclaratorInfo
);
1556 // function-definition:
1557 if (Tok
.is(tok::l_brace
)
1558 || (DeclaratorInfo
.isFunctionDeclarator() &&
1559 (Tok
.is(tok::colon
) || Tok
.is(tok::kw_try
)))) {
1560 if (!DeclaratorInfo
.isFunctionDeclarator()) {
1561 Diag(Tok
, diag::err_func_def_no_params
);
1563 SkipUntil(tok::r_brace
, true);
1565 // Consume the optional ';'
1566 if (Tok
.is(tok::semi
))
1571 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
) {
1572 Diag(Tok
, diag::err_function_declared_typedef
);
1573 // This recovery skips the entire function body. It would be nice
1574 // to simply call ParseCXXInlineMethodDef() below, however Sema
1575 // assumes the declarator represents a function, not a typedef.
1577 SkipUntil(tok::r_brace
, true);
1579 // Consume the optional ';'
1580 if (Tok
.is(tok::semi
))
1585 ParseCXXInlineMethodDef(AS
, DeclaratorInfo
, TemplateInfo
, VS
);
1586 // Consume the optional ';'
1587 if (Tok
.is(tok::semi
))
1594 // member-declarator-list:
1595 // member-declarator
1596 // member-declarator-list ',' member-declarator
1598 llvm::SmallVector
<Decl
*, 8> DeclsInGroup
;
1599 ExprResult BitfieldSize
;
1601 bool Deleted
= false;
1604 // member-declarator:
1605 // declarator pure-specifier[opt]
1606 // declarator constant-initializer[opt]
1607 // identifier[opt] ':' constant-expression
1608 if (Tok
.is(tok::colon
)) {
1610 BitfieldSize
= ParseConstantExpression();
1611 if (BitfieldSize
.isInvalid())
1612 SkipUntil(tok::comma
, true, true);
1615 ParseOptionalCXX0XVirtSpecifierSeq(VS
);
1620 // constant-initializer:
1621 // '=' constant-expression
1623 // defaulted/deleted function-definition:
1624 // '=' 'default' [TODO]
1626 if (Tok
.is(tok::equal
)) {
1628 if (Tok
.is(tok::kw_delete
)) {
1629 if (!getLang().CPlusPlus0x
)
1630 Diag(Tok
, diag::warn_deleted_function_accepted_as_extension
);
1634 Init
= ParseInitializer();
1635 if (Init
.isInvalid())
1636 SkipUntil(tok::comma
, true, true);
1640 // If a simple-asm-expr is present, parse it.
1641 if (Tok
.is(tok::kw_asm
)) {
1643 ExprResult
AsmLabel(ParseSimpleAsm(&Loc
));
1644 if (AsmLabel
.isInvalid())
1645 SkipUntil(tok::comma
, true, true);
1647 DeclaratorInfo
.setAsmLabel(AsmLabel
.release());
1648 DeclaratorInfo
.SetRangeEnd(Loc
);
1651 // If attributes exist after the declarator, parse them.
1652 MaybeParseGNUAttributes(DeclaratorInfo
);
1654 // NOTE: If Sema is the Action module and declarator is an instance field,
1655 // this call will *not* return the created decl; It will return null.
1656 // See Sema::ActOnCXXMemberDeclarator for details.
1659 if (DS
.isFriendSpecified()) {
1660 // TODO: handle initializers, bitfields, 'delete'
1661 ThisDecl
= Actions
.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo
,
1662 /*IsDefinition*/ false,
1663 move(TemplateParams
));
1665 ThisDecl
= Actions
.ActOnCXXMemberDeclarator(getCurScope(), AS
,
1667 move(TemplateParams
),
1668 BitfieldSize
.release(),
1670 /*IsDefinition*/Deleted
,
1674 DeclsInGroup
.push_back(ThisDecl
);
1676 if (DeclaratorInfo
.isFunctionDeclarator() &&
1677 DeclaratorInfo
.getDeclSpec().getStorageClassSpec()
1678 != DeclSpec::SCS_typedef
) {
1679 HandleMemberFunctionDefaultArgs(DeclaratorInfo
, ThisDecl
);
1682 DeclaratorInfo
.complete(ThisDecl
);
1684 // If we don't have a comma, it is either the end of the list (a ';')
1685 // or an error, bail out.
1686 if (Tok
.isNot(tok::comma
))
1689 // Consume the comma.
1692 // Parse the next declarator.
1693 DeclaratorInfo
.clear();
1699 // Attributes are only allowed on the second declarator.
1700 MaybeParseGNUAttributes(DeclaratorInfo
);
1702 if (Tok
.isNot(tok::colon
))
1703 ParseDeclarator(DeclaratorInfo
);
1706 if (ExpectAndConsume(tok::semi
, diag::err_expected_semi_decl_list
)) {
1707 // Skip to end of block or statement.
1708 SkipUntil(tok::r_brace
, true, true);
1709 // If we stopped at a ';', eat it.
1710 if (Tok
.is(tok::semi
)) ConsumeToken();
1714 Actions
.FinalizeDeclaratorGroup(getCurScope(), DS
, DeclsInGroup
.data(),
1715 DeclsInGroup
.size());
1718 /// ParseCXXMemberSpecification - Parse the class definition.
1720 /// member-specification:
1721 /// member-declaration member-specification[opt]
1722 /// access-specifier ':' member-specification[opt]
1724 void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc
,
1725 unsigned TagType
, Decl
*TagDecl
) {
1726 assert((TagType
== DeclSpec::TST_struct
||
1727 TagType
== DeclSpec::TST_union
||
1728 TagType
== DeclSpec::TST_class
) && "Invalid TagType!");
1730 PrettyDeclStackTraceEntry
CrashInfo(Actions
, TagDecl
, RecordLoc
,
1731 "parsing struct/union/class body");
1733 // Determine whether this is a non-nested class. Note that local
1734 // classes are *not* considered to be nested classes.
1735 bool NonNestedClass
= true;
1736 if (!ClassStack
.empty()) {
1737 for (const Scope
*S
= getCurScope(); S
; S
= S
->getParent()) {
1738 if (S
->isClassScope()) {
1739 // We're inside a class scope, so this is a nested class.
1740 NonNestedClass
= false;
1744 if ((S
->getFlags() & Scope::FnScope
)) {
1745 // If we're in a function or function template declared in the
1746 // body of a class, then this is a local class rather than a
1748 const Scope
*Parent
= S
->getParent();
1749 if (Parent
->isTemplateParamScope())
1750 Parent
= Parent
->getParent();
1751 if (Parent
->isClassScope())
1757 // Enter a scope for the class.
1758 ParseScope
ClassScope(this, Scope::ClassScope
|Scope::DeclScope
);
1760 // Note that we are parsing a new (potentially-nested) class definition.
1761 ParsingClassDefinition
ParsingDef(*this, TagDecl
, NonNestedClass
);
1764 Actions
.ActOnTagStartDefinition(getCurScope(), TagDecl
);
1766 ClassVirtSpecifiers CVS
;
1767 ParseOptionalCXX0XClassVirtSpecifierSeq(CVS
);
1769 if (Tok
.is(tok::colon
)) {
1770 ParseBaseClause(TagDecl
);
1772 if (!Tok
.is(tok::l_brace
)) {
1773 Diag(Tok
, diag::err_expected_lbrace_after_base_specifiers
);
1776 Actions
.ActOnTagDefinitionError(getCurScope(), TagDecl
);
1781 assert(Tok
.is(tok::l_brace
));
1783 SourceLocation LBraceLoc
= ConsumeBrace();
1786 Actions
.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl
, CVS
,
1789 // C++ 11p3: Members of a class defined with the keyword class are private
1790 // by default. Members of a class defined with the keywords struct or union
1791 // are public by default.
1792 AccessSpecifier CurAS
;
1793 if (TagType
== DeclSpec::TST_class
)
1798 SourceLocation RBraceLoc
;
1800 // While we still have something to read, read the member-declarations.
1801 while (Tok
.isNot(tok::r_brace
) && Tok
.isNot(tok::eof
)) {
1802 // Each iteration of this loop reads one member-declaration.
1804 // Check for extraneous top-level semicolon.
1805 if (Tok
.is(tok::semi
)) {
1806 Diag(Tok
, diag::ext_extra_struct_semi
)
1807 << DeclSpec::getSpecifierName((DeclSpec::TST
)TagType
)
1808 << FixItHint::CreateRemoval(Tok
.getLocation());
1813 AccessSpecifier AS
= getAccessSpecifierIfPresent();
1814 if (AS
!= AS_none
) {
1815 // Current token is a C++ access specifier.
1817 SourceLocation ASLoc
= Tok
.getLocation();
1819 if (Tok
.is(tok::colon
))
1820 Actions
.ActOnAccessSpecifier(AS
, ASLoc
, Tok
.getLocation());
1822 Diag(Tok
, diag::err_expected_colon
);
1827 // FIXME: Make sure we don't have a template here.
1829 // Parse all the comma separated declarators.
1830 ParseCXXClassMemberDeclaration(CurAS
);
1833 RBraceLoc
= MatchRHSPunctuation(tok::r_brace
, LBraceLoc
);
1835 SkipUntil(tok::r_brace
, false, false);
1838 // If attributes exist after class contents, parse them.
1839 ParsedAttributes attrs
;
1840 MaybeParseGNUAttributes(attrs
);
1843 Actions
.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc
, TagDecl
,
1844 LBraceLoc
, RBraceLoc
,
1847 // C++ 9.2p2: Within the class member-specification, the class is regarded as
1848 // complete within function bodies, default arguments,
1849 // exception-specifications, and constructor ctor-initializers (including
1850 // such things in nested classes).
1852 // FIXME: Only function bodies and constructor ctor-initializers are
1853 // parsed correctly, fix the rest.
1854 if (TagDecl
&& NonNestedClass
) {
1855 // We are not inside a nested class. This class and its nested classes
1856 // are complete and we can parse the delayed portions of method
1857 // declarations and the lexed inline method definitions.
1858 SourceLocation SavedPrevTokLocation
= PrevTokLocation
;
1859 ParseLexedMethodDeclarations(getCurrentClass());
1860 ParseLexedMethodDefs(getCurrentClass());
1861 PrevTokLocation
= SavedPrevTokLocation
;
1865 Actions
.ActOnTagFinishDefinition(getCurScope(), TagDecl
, RBraceLoc
);
1867 // Leave the class scope.
1872 /// ParseConstructorInitializer - Parse a C++ constructor initializer,
1873 /// which explicitly initializes the members or base classes of a
1874 /// class (C++ [class.base.init]). For example, the three initializers
1875 /// after the ':' in the Derived constructor below:
1879 /// class Derived : Base {
1883 /// Derived(float f) : Base(), x(17), f(f) { }
1887 /// [C++] ctor-initializer:
1888 /// ':' mem-initializer-list
1890 /// [C++] mem-initializer-list:
1891 /// mem-initializer ...[opt]
1892 /// mem-initializer ...[opt] , mem-initializer-list
1893 void Parser::ParseConstructorInitializer(Decl
*ConstructorDecl
) {
1894 assert(Tok
.is(tok::colon
) && "Constructor initializer always starts with ':'");
1896 SourceLocation ColonLoc
= ConsumeToken();
1898 llvm::SmallVector
<CXXCtorInitializer
*, 4> MemInitializers
;
1899 bool AnyErrors
= false;
1902 if (Tok
.is(tok::code_completion
)) {
1903 Actions
.CodeCompleteConstructorInitializer(ConstructorDecl
,
1904 MemInitializers
.data(),
1905 MemInitializers
.size());
1906 ConsumeCodeCompletionToken();
1908 MemInitResult MemInit
= ParseMemInitializer(ConstructorDecl
);
1909 if (!MemInit
.isInvalid())
1910 MemInitializers
.push_back(MemInit
.get());
1915 if (Tok
.is(tok::comma
))
1917 else if (Tok
.is(tok::l_brace
))
1919 // If the next token looks like a base or member initializer, assume that
1920 // we're just missing a comma.
1921 else if (Tok
.is(tok::identifier
) || Tok
.is(tok::coloncolon
)) {
1922 SourceLocation Loc
= PP
.getLocForEndOfToken(PrevTokLocation
);
1923 Diag(Loc
, diag::err_ctor_init_missing_comma
)
1924 << FixItHint::CreateInsertion(Loc
, ", ");
1926 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1927 Diag(Tok
.getLocation(), diag::err_expected_lbrace_or_comma
);
1928 SkipUntil(tok::l_brace
, true, true);
1933 Actions
.ActOnMemInitializers(ConstructorDecl
, ColonLoc
,
1934 MemInitializers
.data(), MemInitializers
.size(),
1938 /// ParseMemInitializer - Parse a C++ member initializer, which is
1939 /// part of a constructor initializer that explicitly initializes one
1940 /// member or base class (C++ [class.base.init]). See
1941 /// ParseConstructorInitializer for an example.
1943 /// [C++] mem-initializer:
1944 /// mem-initializer-id '(' expression-list[opt] ')'
1946 /// [C++] mem-initializer-id:
1947 /// '::'[opt] nested-name-specifier[opt] class-name
1949 Parser::MemInitResult
Parser::ParseMemInitializer(Decl
*ConstructorDecl
) {
1950 // parse '::'[opt] nested-name-specifier[opt]
1952 ParseOptionalCXXScopeSpecifier(SS
, ParsedType(), false);
1953 ParsedType TemplateTypeTy
;
1954 if (Tok
.is(tok::annot_template_id
)) {
1955 TemplateIdAnnotation
*TemplateId
1956 = static_cast<TemplateIdAnnotation
*>(Tok
.getAnnotationValue());
1957 if (TemplateId
->Kind
== TNK_Type_template
||
1958 TemplateId
->Kind
== TNK_Dependent_template_name
) {
1959 AnnotateTemplateIdTokenAsType(&SS
);
1960 assert(Tok
.is(tok::annot_typename
) && "template-id -> type failed");
1961 TemplateTypeTy
= getTypeAnnotation(Tok
);
1964 if (!TemplateTypeTy
&& Tok
.isNot(tok::identifier
)) {
1965 Diag(Tok
, diag::err_expected_member_or_base_name
);
1969 // Get the identifier. This may be a member name or a class name,
1970 // but we'll let the semantic analysis determine which it is.
1971 IdentifierInfo
*II
= Tok
.is(tok::identifier
) ? Tok
.getIdentifierInfo() : 0;
1972 SourceLocation IdLoc
= ConsumeToken();
1975 if (Tok
.isNot(tok::l_paren
)) {
1976 Diag(Tok
, diag::err_expected_lparen
);
1979 SourceLocation LParenLoc
= ConsumeParen();
1981 // Parse the optional expression-list.
1982 ExprVector
ArgExprs(Actions
);
1983 CommaLocsTy CommaLocs
;
1984 if (Tok
.isNot(tok::r_paren
) && ParseExpressionList(ArgExprs
, CommaLocs
)) {
1985 SkipUntil(tok::r_paren
);
1989 SourceLocation RParenLoc
= MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
1991 SourceLocation EllipsisLoc
;
1992 if (Tok
.is(tok::ellipsis
))
1993 EllipsisLoc
= ConsumeToken();
1995 return Actions
.ActOnMemInitializer(ConstructorDecl
, getCurScope(), SS
, II
,
1996 TemplateTypeTy
, IdLoc
,
1997 LParenLoc
, ArgExprs
.take(),
1998 ArgExprs
.size(), RParenLoc
,
2002 /// ParseExceptionSpecification - Parse a C++ exception-specification
2003 /// (C++ [except.spec]).
2005 /// exception-specification:
2006 /// 'throw' '(' type-id-list [opt] ')'
2007 /// [MS] 'throw' '(' '...' ')'
2010 /// type-id ... [opt]
2011 /// type-id-list ',' type-id ... [opt]
2013 bool Parser::ParseExceptionSpecification(SourceLocation
&EndLoc
,
2014 llvm::SmallVectorImpl
<ParsedType
>
2016 llvm::SmallVectorImpl
<SourceRange
>
2018 bool &hasAnyExceptionSpec
) {
2019 assert(Tok
.is(tok::kw_throw
) && "expected throw");
2023 if (!Tok
.is(tok::l_paren
)) {
2024 return Diag(Tok
, diag::err_expected_lparen_after
) << "throw";
2026 SourceLocation LParenLoc
= ConsumeParen();
2028 // Parse throw(...), a Microsoft extension that means "this function
2029 // can throw anything".
2030 if (Tok
.is(tok::ellipsis
)) {
2031 hasAnyExceptionSpec
= true;
2032 SourceLocation EllipsisLoc
= ConsumeToken();
2033 if (!getLang().Microsoft
)
2034 Diag(EllipsisLoc
, diag::ext_ellipsis_exception_spec
);
2035 EndLoc
= MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
2039 // Parse the sequence of type-ids.
2041 while (Tok
.isNot(tok::r_paren
)) {
2042 TypeResult
Res(ParseTypeName(&Range
));
2044 if (Tok
.is(tok::ellipsis
)) {
2045 // C++0x [temp.variadic]p5:
2046 // - In a dynamic-exception-specification (15.4); the pattern is a
2048 SourceLocation Ellipsis
= ConsumeToken();
2049 if (!Res
.isInvalid())
2050 Res
= Actions
.ActOnPackExpansion(Res
.get(), Ellipsis
);
2053 if (!Res
.isInvalid()) {
2054 Exceptions
.push_back(Res
.get());
2055 Ranges
.push_back(Range
);
2058 if (Tok
.is(tok::comma
))
2064 EndLoc
= MatchRHSPunctuation(tok::r_paren
, LParenLoc
);
2068 /// ParseTrailingReturnType - Parse a trailing return type on a new-style
2069 /// function declaration.
2070 TypeResult
Parser::ParseTrailingReturnType() {
2071 assert(Tok
.is(tok::arrow
) && "expected arrow");
2075 // FIXME: Need to suppress declarations when parsing this typename.
2076 // Otherwise in this function definition:
2078 // auto f() -> struct X {}
2080 // struct X is parsed as class definition because of the trailing
2084 return ParseTypeName(&Range
);
2087 /// \brief We have just started parsing the definition of a new class,
2088 /// so push that class onto our stack of classes that is currently
2090 Sema::ParsingClassState
2091 Parser::PushParsingClass(Decl
*ClassDecl
, bool NonNestedClass
) {
2092 assert((NonNestedClass
|| !ClassStack
.empty()) &&
2093 "Nested class without outer class");
2094 ClassStack
.push(new ParsingClass(ClassDecl
, NonNestedClass
));
2095 return Actions
.PushParsingClass();
2098 /// \brief Deallocate the given parsed class and all of its nested
2100 void Parser::DeallocateParsedClasses(Parser::ParsingClass
*Class
) {
2101 for (unsigned I
= 0, N
= Class
->LateParsedDeclarations
.size(); I
!= N
; ++I
)
2102 delete Class
->LateParsedDeclarations
[I
];
2106 /// \brief Pop the top class of the stack of classes that are
2107 /// currently being parsed.
2109 /// This routine should be called when we have finished parsing the
2110 /// definition of a class, but have not yet popped the Scope
2111 /// associated with the class's definition.
2113 /// \returns true if the class we've popped is a top-level class,
2114 /// false otherwise.
2115 void Parser::PopParsingClass(Sema::ParsingClassState state
) {
2116 assert(!ClassStack
.empty() && "Mismatched push/pop for class parsing");
2118 Actions
.PopParsingClass(state
);
2120 ParsingClass
*Victim
= ClassStack
.top();
2122 if (Victim
->TopLevelClass
) {
2123 // Deallocate all of the nested classes of this class,
2124 // recursively: we don't need to keep any of this information.
2125 DeallocateParsedClasses(Victim
);
2128 assert(!ClassStack
.empty() && "Missing top-level class?");
2130 if (Victim
->LateParsedDeclarations
.empty()) {
2131 // The victim is a nested class, but we will not need to perform
2132 // any processing after the definition of this class since it has
2133 // no members whose handling was delayed. Therefore, we can just
2134 // remove this nested class.
2135 DeallocateParsedClasses(Victim
);
2139 // This nested class has some members that will need to be processed
2140 // after the top-level class is completely defined. Therefore, add
2141 // it to the list of nested classes within its parent.
2142 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
2143 ClassStack
.top()->LateParsedDeclarations
.push_back(new LateParsedClass(this, Victim
));
2144 Victim
->TemplateScope
= getCurScope()->getParent()->isTemplateParamScope();
2147 /// ParseCXX0XAttributes - Parse a C++0x attribute-specifier. Currently only
2148 /// parses standard attributes.
2150 /// [C++0x] attribute-specifier:
2151 /// '[' '[' attribute-list ']' ']'
2153 /// [C++0x] attribute-list:
2155 /// attribute-list ',' attribute[opt]
2157 /// [C++0x] attribute:
2158 /// attribute-token attribute-argument-clause[opt]
2160 /// [C++0x] attribute-token:
2162 /// attribute-scoped-token
2164 /// [C++0x] attribute-scoped-token:
2165 /// attribute-namespace '::' identifier
2167 /// [C++0x] attribute-namespace:
2170 /// [C++0x] attribute-argument-clause:
2171 /// '(' balanced-token-seq ')'
2173 /// [C++0x] balanced-token-seq:
2175 /// balanced-token-seq balanced-token
2177 /// [C++0x] balanced-token:
2178 /// '(' balanced-token-seq ')'
2179 /// '[' balanced-token-seq ']'
2180 /// '{' balanced-token-seq '}'
2181 /// any token but '(', ')', '[', ']', '{', or '}'
2182 void Parser::ParseCXX0XAttributes(ParsedAttributesWithRange
&attrs
,
2183 SourceLocation
*endLoc
) {
2184 assert(Tok
.is(tok::l_square
) && NextToken().is(tok::l_square
)
2185 && "Not a C++0x attribute list");
2187 SourceLocation StartLoc
= Tok
.getLocation(), Loc
;
2192 if (Tok
.is(tok::comma
)) {
2193 Diag(Tok
.getLocation(), diag::err_expected_ident
);
2197 while (Tok
.is(tok::identifier
) || Tok
.is(tok::comma
)) {
2198 // attribute not present
2199 if (Tok
.is(tok::comma
)) {
2204 IdentifierInfo
*ScopeName
= 0, *AttrName
= Tok
.getIdentifierInfo();
2205 SourceLocation ScopeLoc
, AttrLoc
= ConsumeToken();
2208 if (Tok
.is(tok::coloncolon
)) {
2211 if (!Tok
.is(tok::identifier
)) {
2212 Diag(Tok
.getLocation(), diag::err_expected_ident
);
2213 SkipUntil(tok::r_square
, tok::comma
, true, true);
2217 ScopeName
= AttrName
;
2220 AttrName
= Tok
.getIdentifierInfo();
2221 AttrLoc
= ConsumeToken();
2224 bool AttrParsed
= false;
2225 // No scoped names are supported; ideally we could put all non-standard
2226 // attributes into namespaces.
2228 switch(AttributeList::getKind(AttrName
))
2231 case AttributeList::AT_carries_dependency
:
2232 case AttributeList::AT_noreturn
: {
2233 if (Tok
.is(tok::l_paren
)) {
2234 Diag(Tok
.getLocation(), diag::err_cxx0x_attribute_forbids_arguments
)
2235 << AttrName
->getName();
2239 attrs
.add(AttrFactory
.Create(AttrName
, AttrLoc
, 0, AttrLoc
, 0,
2240 SourceLocation(), 0, 0, false, true));
2245 // One argument; must be a type-id or assignment-expression
2246 case AttributeList::AT_aligned
: {
2247 if (Tok
.isNot(tok::l_paren
)) {
2248 Diag(Tok
.getLocation(), diag::err_cxx0x_attribute_requires_arguments
)
2249 << AttrName
->getName();
2252 SourceLocation ParamLoc
= ConsumeParen();
2254 ExprResult ArgExpr
= ParseCXX0XAlignArgument(ParamLoc
);
2256 MatchRHSPunctuation(tok::r_paren
, ParamLoc
);
2258 ExprVector
ArgExprs(Actions
);
2259 ArgExprs
.push_back(ArgExpr
.release());
2260 attrs
.add(AttrFactory
.Create(AttrName
, AttrLoc
, 0, AttrLoc
,
2261 0, ParamLoc
, ArgExprs
.take(), 1,
2273 // Skip the entire parameter clause, if any
2274 if (!AttrParsed
&& Tok
.is(tok::l_paren
)) {
2276 // SkipUntil maintains the balancedness of tokens.
2277 SkipUntil(tok::r_paren
, false);
2281 if (ExpectAndConsume(tok::r_square
, diag::err_expected_rsquare
))
2282 SkipUntil(tok::r_square
, false);
2283 Loc
= Tok
.getLocation();
2284 if (ExpectAndConsume(tok::r_square
, diag::err_expected_rsquare
))
2285 SkipUntil(tok::r_square
, false);
2287 attrs
.Range
= SourceRange(StartLoc
, Loc
);
2290 /// ParseCXX0XAlignArgument - Parse the argument to C++0x's [[align]]
2293 /// FIXME: Simply returns an alignof() expression if the argument is a
2294 /// type. Ideally, the type should be propagated directly into Sema.
2296 /// [C++0x] 'align' '(' type-id ')'
2297 /// [C++0x] 'align' '(' assignment-expression ')'
2298 ExprResult
Parser::ParseCXX0XAlignArgument(SourceLocation Start
) {
2299 if (isTypeIdInParens()) {
2300 EnterExpressionEvaluationContext
Unevaluated(Actions
, Sema::Unevaluated
);
2301 SourceLocation TypeLoc
= Tok
.getLocation();
2302 ParsedType Ty
= ParseTypeName().get();
2303 SourceRange
TypeRange(Start
, Tok
.getLocation());
2304 return Actions
.ActOnSizeOfAlignOfExpr(TypeLoc
, false, true,
2305 Ty
.getAsOpaquePtr(), TypeRange
);
2307 return ParseConstantExpression();
2310 /// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr]
2312 /// [MS] ms-attribute:
2313 /// '[' token-seq ']'
2315 /// [MS] ms-attribute-seq:
2316 /// ms-attribute[opt]
2317 /// ms-attribute ms-attribute-seq
2318 void Parser::ParseMicrosoftAttributes(ParsedAttributes
&attrs
,
2319 SourceLocation
*endLoc
) {
2320 assert(Tok
.is(tok::l_square
) && "Not a Microsoft attribute list");
2322 while (Tok
.is(tok::l_square
)) {
2324 SkipUntil(tok::r_square
, true, true);
2325 if (endLoc
) *endLoc
= Tok
.getLocation();
2326 ExpectAndConsume(tok::r_square
, diag::err_expected_rsquare
);