1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements semantic analysis for C++ templates.
10 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/Sema/Lookup.h"
14 #include "clang/Sema/Scope.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/Sema/TemplateDeduction.h"
17 #include "TreeTransform.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/TypeVisitor.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/ParsedTemplate.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "llvm/ADT/StringExtras.h"
30 using namespace clang
;
33 // Exported for use by Parser.
35 clang::getTemplateParamsRange(TemplateParameterList
const * const *Ps
,
37 if (!N
) return SourceRange();
38 return SourceRange(Ps
[0]->getTemplateLoc(), Ps
[N
-1]->getRAngleLoc());
41 /// \brief Determine whether the declaration found is acceptable as the name
42 /// of a template and, if so, return that template declaration. Otherwise,
44 static NamedDecl
*isAcceptableTemplateName(ASTContext
&Context
,
46 NamedDecl
*D
= Orig
->getUnderlyingDecl();
48 if (isa
<TemplateDecl
>(D
))
51 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(D
)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
63 if (Record
->isInjectedClassName()) {
64 Record
= cast
<CXXRecordDecl
>(Record
->getDeclContext());
65 if (Record
->getDescribedClassTemplate())
66 return Record
->getDescribedClassTemplate();
68 if (ClassTemplateSpecializationDecl
*Spec
69 = dyn_cast
<ClassTemplateSpecializationDecl
>(Record
))
70 return Spec
->getSpecializedTemplate();
79 static void FilterAcceptableTemplateNames(ASTContext
&C
, LookupResult
&R
) {
80 // The set of class templates we've already seen.
81 llvm::SmallPtrSet
<ClassTemplateDecl
*, 8> ClassTemplates
;
82 LookupResult::Filter filter
= R
.makeFilter();
83 while (filter
.hasNext()) {
84 NamedDecl
*Orig
= filter
.next();
85 NamedDecl
*Repl
= isAcceptableTemplateName(C
, Orig
);
88 else if (Repl
!= Orig
) {
90 // C++ [temp.local]p3:
91 // A lookup that finds an injected-class-name (10.2) can result in an
92 // ambiguity in certain cases (for example, if it is found in more than
93 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
95 // is followed by a template-argument-list, the reference refers to the
96 // class template itself and not a specialization thereof, and is not
99 // FIXME: Will we eventually have to do the same for alias templates?
100 if (ClassTemplateDecl
*ClassTmpl
= dyn_cast
<ClassTemplateDecl
>(Repl
))
101 if (!ClassTemplates
.insert(ClassTmpl
)) {
106 // FIXME: we promote access to public here as a workaround to
107 // the fact that LookupResult doesn't let us remember that we
108 // found this template through a particular injected class name,
109 // which means we end up doing nasty things to the invariants.
110 // Pretending that access is public is *much* safer.
111 filter
.replace(Repl
, AS_public
);
117 TemplateNameKind
Sema::isTemplateName(Scope
*S
,
119 bool hasTemplateKeyword
,
121 ParsedType ObjectTypePtr
,
122 bool EnteringContext
,
123 TemplateTy
&TemplateResult
,
124 bool &MemberOfUnknownSpecialization
) {
125 assert(getLangOptions().CPlusPlus
&& "No template names in C!");
127 DeclarationName TName
;
128 MemberOfUnknownSpecialization
= false;
130 switch (Name
.getKind()) {
131 case UnqualifiedId::IK_Identifier
:
132 TName
= DeclarationName(Name
.Identifier
);
135 case UnqualifiedId::IK_OperatorFunctionId
:
136 TName
= Context
.DeclarationNames
.getCXXOperatorName(
137 Name
.OperatorFunctionId
.Operator
);
140 case UnqualifiedId::IK_LiteralOperatorId
:
141 TName
= Context
.DeclarationNames
.getCXXLiteralOperatorName(Name
.Identifier
);
145 return TNK_Non_template
;
148 QualType ObjectType
= ObjectTypePtr
.get();
150 LookupResult
R(*this, TName
, Name
.getSourceRange().getBegin(),
152 LookupTemplateName(R
, S
, SS
, ObjectType
, EnteringContext
,
153 MemberOfUnknownSpecialization
);
154 if (R
.empty()) return TNK_Non_template
;
155 if (R
.isAmbiguous()) {
156 // Suppress diagnostics; we'll redo this lookup later.
157 R
.suppressDiagnostics();
159 // FIXME: we might have ambiguous templates, in which case we
160 // should at least parse them properly!
161 return TNK_Non_template
;
164 TemplateName Template
;
165 TemplateNameKind TemplateKind
;
167 unsigned ResultCount
= R
.end() - R
.begin();
168 if (ResultCount
> 1) {
169 // We assume that we'll preserve the qualifier from a function
170 // template name in other ways.
171 Template
= Context
.getOverloadedTemplateName(R
.begin(), R
.end());
172 TemplateKind
= TNK_Function_template
;
174 // We'll do this lookup again later.
175 R
.suppressDiagnostics();
177 TemplateDecl
*TD
= cast
<TemplateDecl
>((*R
.begin())->getUnderlyingDecl());
179 if (SS
.isSet() && !SS
.isInvalid()) {
180 NestedNameSpecifier
*Qualifier
181 = static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
182 Template
= Context
.getQualifiedTemplateName(Qualifier
,
183 hasTemplateKeyword
, TD
);
185 Template
= TemplateName(TD
);
188 if (isa
<FunctionTemplateDecl
>(TD
)) {
189 TemplateKind
= TNK_Function_template
;
191 // We'll do this lookup again later.
192 R
.suppressDiagnostics();
194 assert(isa
<ClassTemplateDecl
>(TD
) || isa
<TemplateTemplateParmDecl
>(TD
));
195 TemplateKind
= TNK_Type_template
;
199 TemplateResult
= TemplateTy::make(Template
);
203 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo
&II
,
204 SourceLocation IILoc
,
206 const CXXScopeSpec
*SS
,
207 TemplateTy
&SuggestedTemplate
,
208 TemplateNameKind
&SuggestedKind
) {
209 // We can't recover unless there's a dependent scope specifier preceding the
211 // FIXME: Typo correction?
212 if (!SS
|| !SS
->isSet() || !isDependentScopeSpecifier(*SS
) ||
213 computeDeclContext(*SS
))
216 // The code is missing a 'template' keyword prior to the dependent template
218 NestedNameSpecifier
*Qualifier
= (NestedNameSpecifier
*)SS
->getScopeRep();
219 Diag(IILoc
, diag::err_template_kw_missing
)
220 << Qualifier
<< II
.getName()
221 << FixItHint::CreateInsertion(IILoc
, "template ");
223 = TemplateTy::make(Context
.getDependentTemplateName(Qualifier
, &II
));
224 SuggestedKind
= TNK_Dependent_template_name
;
228 void Sema::LookupTemplateName(LookupResult
&Found
,
229 Scope
*S
, CXXScopeSpec
&SS
,
231 bool EnteringContext
,
232 bool &MemberOfUnknownSpecialization
) {
233 // Determine where to perform name lookup
234 MemberOfUnknownSpecialization
= false;
235 DeclContext
*LookupCtx
= 0;
236 bool isDependent
= false;
237 if (!ObjectType
.isNull()) {
238 // This nested-name-specifier occurs in a member access expression, e.g.,
239 // x->B::f, and we are looking into the type of the object.
240 assert(!SS
.isSet() && "ObjectType and scope specifier cannot coexist");
241 LookupCtx
= computeDeclContext(ObjectType
);
242 isDependent
= ObjectType
->isDependentType();
243 assert((isDependent
|| !ObjectType
->isIncompleteType()) &&
244 "Caller should have completed object type");
245 } else if (SS
.isSet()) {
246 // This nested-name-specifier occurs after another nested-name-specifier,
247 // so long into the context associated with the prior nested-name-specifier.
248 LookupCtx
= computeDeclContext(SS
, EnteringContext
);
249 isDependent
= isDependentScopeSpecifier(SS
);
251 // The declaration context must be complete.
252 if (LookupCtx
&& RequireCompleteDeclContext(SS
, LookupCtx
))
256 bool ObjectTypeSearchedInScope
= false;
258 // Perform "qualified" name lookup into the declaration context we
259 // computed, which is either the type of the base of a member access
260 // expression or the declaration context associated with a prior
261 // nested-name-specifier.
262 LookupQualifiedName(Found
, LookupCtx
);
264 if (!ObjectType
.isNull() && Found
.empty()) {
265 // C++ [basic.lookup.classref]p1:
266 // In a class member access expression (5.2.5), if the . or -> token is
267 // immediately followed by an identifier followed by a <, the
268 // identifier must be looked up to determine whether the < is the
269 // beginning of a template argument list (14.2) or a less-than operator.
270 // The identifier is first looked up in the class of the object
271 // expression. If the identifier is not found, it is then looked up in
272 // the context of the entire postfix-expression and shall name a class
273 // or function template.
274 if (S
) LookupName(Found
, S
);
275 ObjectTypeSearchedInScope
= true;
277 } else if (isDependent
&& (!S
|| ObjectType
.isNull())) {
278 // We cannot look into a dependent object type or nested nme
280 MemberOfUnknownSpecialization
= true;
283 // Perform unqualified name lookup in the current scope.
284 LookupName(Found
, S
);
287 if (Found
.empty() && !isDependent
) {
288 // If we did not find any names, attempt to correct any typos.
289 DeclarationName Name
= Found
.getLookupName();
290 if (DeclarationName Corrected
= CorrectTypo(Found
, S
, &SS
, LookupCtx
,
291 false, CTC_CXXCasts
)) {
292 FilterAcceptableTemplateNames(Context
, Found
);
293 if (!Found
.empty()) {
295 Diag(Found
.getNameLoc(), diag::err_no_member_template_suggest
)
296 << Name
<< LookupCtx
<< Found
.getLookupName() << SS
.getRange()
297 << FixItHint::CreateReplacement(Found
.getNameLoc(),
298 Found
.getLookupName().getAsString());
300 Diag(Found
.getNameLoc(), diag::err_no_template_suggest
)
301 << Name
<< Found
.getLookupName()
302 << FixItHint::CreateReplacement(Found
.getNameLoc(),
303 Found
.getLookupName().getAsString());
304 if (TemplateDecl
*Template
= Found
.getAsSingle
<TemplateDecl
>())
305 Diag(Template
->getLocation(), diag::note_previous_decl
)
306 << Template
->getDeclName();
310 Found
.setLookupName(Name
);
314 FilterAcceptableTemplateNames(Context
, Found
);
317 MemberOfUnknownSpecialization
= true;
321 if (S
&& !ObjectType
.isNull() && !ObjectTypeSearchedInScope
) {
322 // C++ [basic.lookup.classref]p1:
323 // [...] If the lookup in the class of the object expression finds a
324 // template, the name is also looked up in the context of the entire
325 // postfix-expression and [...]
327 LookupResult
FoundOuter(*this, Found
.getLookupName(), Found
.getNameLoc(),
329 LookupName(FoundOuter
, S
);
330 FilterAcceptableTemplateNames(Context
, FoundOuter
);
332 if (FoundOuter
.empty()) {
333 // - if the name is not found, the name found in the class of the
334 // object expression is used, otherwise
335 } else if (!FoundOuter
.getAsSingle
<ClassTemplateDecl
>()) {
336 // - if the name is found in the context of the entire
337 // postfix-expression and does not name a class template, the name
338 // found in the class of the object expression is used, otherwise
339 } else if (!Found
.isSuppressingDiagnostics()) {
340 // - if the name found is a class template, it must refer to the same
341 // entity as the one found in the class of the object expression,
342 // otherwise the program is ill-formed.
343 if (!Found
.isSingleResult() ||
344 Found
.getFoundDecl()->getCanonicalDecl()
345 != FoundOuter
.getFoundDecl()->getCanonicalDecl()) {
346 Diag(Found
.getNameLoc(),
347 diag::ext_nested_name_member_ref_lookup_ambiguous
)
348 << Found
.getLookupName()
350 Diag(Found
.getRepresentativeDecl()->getLocation(),
351 diag::note_ambig_member_ref_object_type
)
353 Diag(FoundOuter
.getFoundDecl()->getLocation(),
354 diag::note_ambig_member_ref_scope
);
356 // Recover by taking the template that we found in the object
357 // expression's type.
363 /// ActOnDependentIdExpression - Handle a dependent id-expression that
364 /// was just parsed. This is only possible with an explicit scope
365 /// specifier naming a dependent type.
367 Sema::ActOnDependentIdExpression(const CXXScopeSpec
&SS
,
368 const DeclarationNameInfo
&NameInfo
,
369 bool isAddressOfOperand
,
370 const TemplateArgumentListInfo
*TemplateArgs
) {
371 NestedNameSpecifier
*Qualifier
372 = static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
374 DeclContext
*DC
= getFunctionLevelDeclContext();
376 if (!isAddressOfOperand
&&
377 isa
<CXXMethodDecl
>(DC
) &&
378 cast
<CXXMethodDecl
>(DC
)->isInstance()) {
379 QualType ThisType
= cast
<CXXMethodDecl
>(DC
)->getThisType(Context
);
381 // Since the 'this' expression is synthesized, we don't need to
382 // perform the double-lookup check.
383 NamedDecl
*FirstQualifierInScope
= 0;
385 return Owned(CXXDependentScopeMemberExpr::Create(Context
,
386 /*This*/ 0, ThisType
,
388 /*Op*/ SourceLocation(),
389 Qualifier
, SS
.getRange(),
390 FirstQualifierInScope
,
395 return BuildDependentDeclRefExpr(SS
, NameInfo
, TemplateArgs
);
399 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec
&SS
,
400 const DeclarationNameInfo
&NameInfo
,
401 const TemplateArgumentListInfo
*TemplateArgs
) {
402 return Owned(DependentScopeDeclRefExpr::Create(Context
,
403 static_cast<NestedNameSpecifier
*>(SS
.getScopeRep()),
409 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
410 /// that the template parameter 'PrevDecl' is being shadowed by a new
411 /// declaration at location Loc. Returns true to indicate that this is
412 /// an error, and false otherwise.
413 bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc
, Decl
*PrevDecl
) {
414 assert(PrevDecl
->isTemplateParameter() && "Not a template parameter");
416 // Microsoft Visual C++ permits template parameters to be shadowed.
417 if (getLangOptions().Microsoft
)
420 // C++ [temp.local]p4:
421 // A template-parameter shall not be redeclared within its
422 // scope (including nested scopes).
423 Diag(Loc
, diag::err_template_param_shadow
)
424 << cast
<NamedDecl
>(PrevDecl
)->getDeclName();
425 Diag(PrevDecl
->getLocation(), diag::note_template_param_here
);
429 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
430 /// the parameter D to reference the templated declaration and return a pointer
431 /// to the template declaration. Otherwise, do nothing to D and return null.
432 TemplateDecl
*Sema::AdjustDeclIfTemplate(Decl
*&D
) {
433 if (TemplateDecl
*Temp
= dyn_cast_or_null
<TemplateDecl
>(D
)) {
434 D
= Temp
->getTemplatedDecl();
440 static TemplateArgumentLoc
translateTemplateArgument(Sema
&SemaRef
,
441 const ParsedTemplateArgument
&Arg
) {
443 switch (Arg
.getKind()) {
444 case ParsedTemplateArgument::Type
: {
446 QualType T
= SemaRef
.GetTypeFromParser(Arg
.getAsType(), &DI
);
448 DI
= SemaRef
.Context
.getTrivialTypeSourceInfo(T
, Arg
.getLocation());
449 return TemplateArgumentLoc(TemplateArgument(T
), DI
);
452 case ParsedTemplateArgument::NonType
: {
453 Expr
*E
= static_cast<Expr
*>(Arg
.getAsExpr());
454 return TemplateArgumentLoc(TemplateArgument(E
), E
);
457 case ParsedTemplateArgument::Template
: {
458 TemplateName Template
= Arg
.getAsTemplate().get();
459 return TemplateArgumentLoc(TemplateArgument(Template
),
460 Arg
.getScopeSpec().getRange(),
465 llvm_unreachable("Unhandled parsed template argument");
466 return TemplateArgumentLoc();
469 /// \brief Translates template arguments as provided by the parser
470 /// into template arguments used by semantic analysis.
471 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr
&TemplateArgsIn
,
472 TemplateArgumentListInfo
&TemplateArgs
) {
473 for (unsigned I
= 0, Last
= TemplateArgsIn
.size(); I
!= Last
; ++I
)
474 TemplateArgs
.addArgument(translateTemplateArgument(*this,
478 /// ActOnTypeParameter - Called when a C++ template type parameter
479 /// (e.g., "typename T") has been parsed. Typename specifies whether
480 /// the keyword "typename" was used to declare the type parameter
481 /// (otherwise, "class" was used), and KeyLoc is the location of the
482 /// "class" or "typename" keyword. ParamName is the name of the
483 /// parameter (NULL indicates an unnamed template parameter) and
484 /// ParamName is the location of the parameter name (if any).
485 /// If the type parameter has a default argument, it will be added
486 /// later via ActOnTypeParameterDefault.
487 Decl
*Sema::ActOnTypeParameter(Scope
*S
, bool Typename
, bool Ellipsis
,
488 SourceLocation EllipsisLoc
,
489 SourceLocation KeyLoc
,
490 IdentifierInfo
*ParamName
,
491 SourceLocation ParamNameLoc
,
492 unsigned Depth
, unsigned Position
,
493 SourceLocation EqualLoc
,
494 ParsedType DefaultArg
) {
495 assert(S
->isTemplateParamScope() &&
496 "Template type parameter not in template parameter scope!");
497 bool Invalid
= false;
500 NamedDecl
*PrevDecl
= LookupSingleName(S
, ParamName
, ParamNameLoc
,
503 if (PrevDecl
&& PrevDecl
->isTemplateParameter())
504 Invalid
= Invalid
|| DiagnoseTemplateParameterShadow(ParamNameLoc
,
508 SourceLocation Loc
= ParamNameLoc
;
512 TemplateTypeParmDecl
*Param
513 = TemplateTypeParmDecl::Create(Context
, Context
.getTranslationUnitDecl(),
514 Loc
, Depth
, Position
, ParamName
, Typename
,
517 Param
->setInvalidDecl();
520 // Add the template parameter into the current scope.
522 IdResolver
.AddDecl(Param
);
525 // Handle the default argument, if provided.
527 TypeSourceInfo
*DefaultTInfo
;
528 GetTypeFromParser(DefaultArg
, &DefaultTInfo
);
530 assert(DefaultTInfo
&& "expected source information for type");
532 // C++0x [temp.param]p9:
533 // A default template-argument may be specified for any kind of
534 // template-parameter that is not a template parameter pack.
536 Diag(EqualLoc
, diag::err_template_param_pack_default_arg
);
540 // Check the template argument itself.
541 if (CheckTemplateArgument(Param
, DefaultTInfo
)) {
542 Param
->setInvalidDecl();
546 Param
->setDefaultArgument(DefaultTInfo
, false);
552 /// \brief Check that the type of a non-type template parameter is
555 /// \returns the (possibly-promoted) parameter type if valid;
556 /// otherwise, produces a diagnostic and returns a NULL type.
558 Sema::CheckNonTypeTemplateParameterType(QualType T
, SourceLocation Loc
) {
559 // We don't allow variably-modified types as the type of non-type template
561 if (T
->isVariablyModifiedType()) {
562 Diag(Loc
, diag::err_variably_modified_nontype_template_param
)
567 // C++ [temp.param]p4:
569 // A non-type template-parameter shall have one of the following
570 // (optionally cv-qualified) types:
572 // -- integral or enumeration type,
573 if (T
->isIntegralOrEnumerationType() ||
574 // -- pointer to object or pointer to function,
575 T
->isPointerType() ||
576 // -- reference to object or reference to function,
577 T
->isReferenceType() ||
578 // -- pointer to member.
579 T
->isMemberPointerType() ||
580 // If T is a dependent type, we can't do the check now, so we
581 // assume that it is well-formed.
582 T
->isDependentType())
584 // C++ [temp.param]p8:
586 // A non-type template-parameter of type "array of T" or
587 // "function returning T" is adjusted to be of type "pointer to
588 // T" or "pointer to function returning T", respectively.
589 else if (T
->isArrayType())
590 // FIXME: Keep the type prior to promotion?
591 return Context
.getArrayDecayedType(T
);
592 else if (T
->isFunctionType())
593 // FIXME: Keep the type prior to promotion?
594 return Context
.getPointerType(T
);
596 Diag(Loc
, diag::err_template_nontype_parm_bad_type
)
602 Decl
*Sema::ActOnNonTypeTemplateParameter(Scope
*S
, Declarator
&D
,
605 SourceLocation EqualLoc
,
607 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
608 QualType T
= TInfo
->getType();
610 assert(S
->isTemplateParamScope() &&
611 "Non-type template parameter not in template parameter scope!");
612 bool Invalid
= false;
614 IdentifierInfo
*ParamName
= D
.getIdentifier();
616 NamedDecl
*PrevDecl
= LookupSingleName(S
, ParamName
, D
.getIdentifierLoc(),
619 if (PrevDecl
&& PrevDecl
->isTemplateParameter())
620 Invalid
= Invalid
|| DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(),
624 T
= CheckNonTypeTemplateParameterType(T
, D
.getIdentifierLoc());
626 T
= Context
.IntTy
; // Recover with an 'int' type.
630 NonTypeTemplateParmDecl
*Param
631 = NonTypeTemplateParmDecl::Create(Context
, Context
.getTranslationUnitDecl(),
632 D
.getIdentifierLoc(),
633 Depth
, Position
, ParamName
, T
, TInfo
);
635 Param
->setInvalidDecl();
637 if (D
.getIdentifier()) {
638 // Add the template parameter into the current scope.
640 IdResolver
.AddDecl(Param
);
643 // Check the well-formedness of the default template argument, if provided.
645 TemplateArgument Converted
;
646 if (CheckTemplateArgument(Param
, Param
->getType(), Default
, Converted
)) {
647 Param
->setInvalidDecl();
651 Param
->setDefaultArgument(Default
, false);
657 /// ActOnTemplateTemplateParameter - Called when a C++ template template
658 /// parameter (e.g. T in template <template <typename> class T> class array)
659 /// has been parsed. S is the current scope.
660 Decl
*Sema::ActOnTemplateTemplateParameter(Scope
* S
,
661 SourceLocation TmpLoc
,
662 TemplateParamsTy
*Params
,
663 IdentifierInfo
*Name
,
664 SourceLocation NameLoc
,
667 SourceLocation EqualLoc
,
668 const ParsedTemplateArgument
&Default
) {
669 assert(S
->isTemplateParamScope() &&
670 "Template template parameter not in template parameter scope!");
672 // Construct the parameter object.
673 TemplateTemplateParmDecl
*Param
=
674 TemplateTemplateParmDecl::Create(Context
, Context
.getTranslationUnitDecl(),
675 NameLoc
.isInvalid()? TmpLoc
: NameLoc
,
676 Depth
, Position
, Name
,
679 // If the template template parameter has a name, then link the identifier
680 // into the scope and lookup mechanisms.
683 IdResolver
.AddDecl(Param
);
686 if (!Default
.isInvalid()) {
687 // Check only that we have a template template argument. We don't want to
688 // try to check well-formedness now, because our template template parameter
689 // might have dependent types in its template parameters, which we wouldn't
690 // be able to match now.
692 // If none of the template template parameter's template arguments mention
693 // other template parameters, we could actually perform more checking here.
694 // However, it isn't worth doing.
695 TemplateArgumentLoc DefaultArg
= translateTemplateArgument(*this, Default
);
696 if (DefaultArg
.getArgument().getAsTemplate().isNull()) {
697 Diag(DefaultArg
.getLocation(), diag::err_template_arg_not_class_template
)
698 << DefaultArg
.getSourceRange();
702 Param
->setDefaultArgument(DefaultArg
, false);
705 if (Params
->size() == 0) {
706 Diag(Param
->getLocation(), diag::err_template_template_parm_no_parms
)
707 << SourceRange(Params
->getLAngleLoc(), Params
->getRAngleLoc());
708 Param
->setInvalidDecl();
713 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
714 /// contains the template parameters in Params/NumParams.
715 Sema::TemplateParamsTy
*
716 Sema::ActOnTemplateParameterList(unsigned Depth
,
717 SourceLocation ExportLoc
,
718 SourceLocation TemplateLoc
,
719 SourceLocation LAngleLoc
,
720 Decl
**Params
, unsigned NumParams
,
721 SourceLocation RAngleLoc
) {
722 if (ExportLoc
.isValid())
723 Diag(ExportLoc
, diag::warn_template_export_unsupported
);
725 return TemplateParameterList::Create(Context
, TemplateLoc
, LAngleLoc
,
726 (NamedDecl
**)Params
, NumParams
,
730 static void SetNestedNameSpecifier(TagDecl
*T
, const CXXScopeSpec
&SS
) {
732 T
->setQualifierInfo(static_cast<NestedNameSpecifier
*>(SS
.getScopeRep()),
737 Sema::CheckClassTemplate(Scope
*S
, unsigned TagSpec
, TagUseKind TUK
,
738 SourceLocation KWLoc
, CXXScopeSpec
&SS
,
739 IdentifierInfo
*Name
, SourceLocation NameLoc
,
741 TemplateParameterList
*TemplateParams
,
742 AccessSpecifier AS
) {
743 assert(TemplateParams
&& TemplateParams
->size() > 0 &&
744 "No template parameters");
745 assert(TUK
!= TUK_Reference
&& "Can only declare or define class templates");
746 bool Invalid
= false;
748 // Check that we can declare a template here.
749 if (CheckTemplateDeclScope(S
, TemplateParams
))
752 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
753 assert(Kind
!= TTK_Enum
&& "can't build template of enumerated type");
755 // There is no such thing as an unnamed class template.
757 Diag(KWLoc
, diag::err_template_unnamed_class
);
761 // Find any previous declaration with this name.
762 DeclContext
*SemanticContext
;
763 LookupResult
Previous(*this, Name
, NameLoc
, LookupOrdinaryName
,
765 if (SS
.isNotEmpty() && !SS
.isInvalid()) {
766 SemanticContext
= computeDeclContext(SS
, true);
767 if (!SemanticContext
) {
768 // FIXME: Produce a reasonable diagnostic here
772 if (RequireCompleteDeclContext(SS
, SemanticContext
))
775 LookupQualifiedName(Previous
, SemanticContext
);
777 SemanticContext
= CurContext
;
778 LookupName(Previous
, S
);
781 if (Previous
.isAmbiguous())
784 NamedDecl
*PrevDecl
= 0;
785 if (Previous
.begin() != Previous
.end())
786 PrevDecl
= (*Previous
.begin())->getUnderlyingDecl();
788 // If there is a previous declaration with the same name, check
789 // whether this is a valid redeclaration.
790 ClassTemplateDecl
*PrevClassTemplate
791 = dyn_cast_or_null
<ClassTemplateDecl
>(PrevDecl
);
793 // We may have found the injected-class-name of a class template,
794 // class template partial specialization, or class template specialization.
795 // In these cases, grab the template that is being defined or specialized.
796 if (!PrevClassTemplate
&& PrevDecl
&& isa
<CXXRecordDecl
>(PrevDecl
) &&
797 cast
<CXXRecordDecl
>(PrevDecl
)->isInjectedClassName()) {
798 PrevDecl
= cast
<CXXRecordDecl
>(PrevDecl
->getDeclContext());
800 = cast
<CXXRecordDecl
>(PrevDecl
)->getDescribedClassTemplate();
801 if (!PrevClassTemplate
&& isa
<ClassTemplateSpecializationDecl
>(PrevDecl
)) {
803 = cast
<ClassTemplateSpecializationDecl
>(PrevDecl
)
804 ->getSpecializedTemplate();
808 if (TUK
== TUK_Friend
) {
809 // C++ [namespace.memdef]p3:
810 // [...] When looking for a prior declaration of a class or a function
811 // declared as a friend, and when the name of the friend class or
812 // function is neither a qualified name nor a template-id, scopes outside
813 // the innermost enclosing namespace scope are not considered.
815 DeclContext
*OutermostContext
= CurContext
;
816 while (!OutermostContext
->isFileContext())
817 OutermostContext
= OutermostContext
->getLookupParent();
820 (OutermostContext
->Equals(PrevDecl
->getDeclContext()) ||
821 OutermostContext
->Encloses(PrevDecl
->getDeclContext()))) {
822 SemanticContext
= PrevDecl
->getDeclContext();
824 // Declarations in outer scopes don't matter. However, the outermost
825 // context we computed is the semantic context for our new
827 PrevDecl
= PrevClassTemplate
= 0;
828 SemanticContext
= OutermostContext
;
832 if (CurContext
->isDependentContext()) {
833 // If this is a dependent context, we don't want to link the friend
834 // class template to the template in scope, because that would perform
835 // checking of the template parameter lists that can't be performed
836 // until the outer context is instantiated.
837 PrevDecl
= PrevClassTemplate
= 0;
839 } else if (PrevDecl
&& !isDeclInScope(PrevDecl
, SemanticContext
, S
))
840 PrevDecl
= PrevClassTemplate
= 0;
842 if (PrevClassTemplate
) {
843 // Ensure that the template parameter lists are compatible.
844 if (!TemplateParameterListsAreEqual(TemplateParams
,
845 PrevClassTemplate
->getTemplateParameters(),
850 // C++ [temp.class]p4:
851 // In a redeclaration, partial specialization, explicit
852 // specialization or explicit instantiation of a class template,
853 // the class-key shall agree in kind with the original class
854 // template declaration (7.1.5.3).
855 RecordDecl
*PrevRecordDecl
= PrevClassTemplate
->getTemplatedDecl();
856 if (!isAcceptableTagRedeclaration(PrevRecordDecl
, Kind
, KWLoc
, *Name
)) {
857 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
859 << FixItHint::CreateReplacement(KWLoc
, PrevRecordDecl
->getKindName());
860 Diag(PrevRecordDecl
->getLocation(), diag::note_previous_use
);
861 Kind
= PrevRecordDecl
->getTagKind();
864 // Check for redefinition of this class template.
865 if (TUK
== TUK_Definition
) {
866 if (TagDecl
*Def
= PrevRecordDecl
->getDefinition()) {
867 Diag(NameLoc
, diag::err_redefinition
) << Name
;
868 Diag(Def
->getLocation(), diag::note_previous_definition
);
869 // FIXME: Would it make sense to try to "forget" the previous
870 // definition, as part of error recovery?
874 } else if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
875 // Maybe we will complain about the shadowed template parameter.
876 DiagnoseTemplateParameterShadow(NameLoc
, PrevDecl
);
877 // Just pretend that we didn't see the previous declaration.
879 } else if (PrevDecl
) {
881 // A class template shall not have the same name as any other
882 // template, class, function, object, enumeration, enumerator,
883 // namespace, or type in the same scope (3.3), except as specified
885 Diag(NameLoc
, diag::err_redefinition_different_kind
) << Name
;
886 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
890 // Check the template parameter list of this declaration, possibly
891 // merging in the template parameter list from the previous class
892 // template declaration.
893 if (CheckTemplateParameterList(TemplateParams
,
894 PrevClassTemplate
? PrevClassTemplate
->getTemplateParameters() : 0,
899 // If the name of the template was qualified, we must be defining the
900 // template out-of-line.
901 if (!SS
.isInvalid() && !Invalid
&& !PrevClassTemplate
&&
902 !(TUK
== TUK_Friend
&& CurContext
->isDependentContext()))
903 Diag(NameLoc
, diag::err_member_def_does_not_match
)
904 << Name
<< SemanticContext
<< SS
.getRange();
907 CXXRecordDecl
*NewClass
=
908 CXXRecordDecl::Create(Context
, Kind
, SemanticContext
, NameLoc
, Name
, KWLoc
,
910 PrevClassTemplate
->getTemplatedDecl() : 0,
911 /*DelayTypeCreation=*/true);
912 SetNestedNameSpecifier(NewClass
, SS
);
914 ClassTemplateDecl
*NewTemplate
915 = ClassTemplateDecl::Create(Context
, SemanticContext
, NameLoc
,
916 DeclarationName(Name
), TemplateParams
,
917 NewClass
, PrevClassTemplate
);
918 NewClass
->setDescribedClassTemplate(NewTemplate
);
920 // Build the type for the class template declaration now.
921 QualType T
= NewTemplate
->getInjectedClassNameSpecialization();
922 T
= Context
.getInjectedClassNameType(NewClass
, T
);
923 assert(T
->isDependentType() && "Class template type is not dependent?");
926 // If we are providing an explicit specialization of a member that is a
927 // class template, make a note of that.
928 if (PrevClassTemplate
&&
929 PrevClassTemplate
->getInstantiatedFromMemberTemplate())
930 PrevClassTemplate
->setMemberSpecialization();
932 // Set the access specifier.
933 if (!Invalid
&& TUK
!= TUK_Friend
)
934 SetMemberAccessSpecifier(NewTemplate
, PrevClassTemplate
, AS
);
936 // Set the lexical context of these templates
937 NewClass
->setLexicalDeclContext(CurContext
);
938 NewTemplate
->setLexicalDeclContext(CurContext
);
940 if (TUK
== TUK_Definition
)
941 NewClass
->startDefinition();
944 ProcessDeclAttributeList(S
, NewClass
, Attr
);
946 if (TUK
!= TUK_Friend
)
947 PushOnScopeChains(NewTemplate
, S
);
949 if (PrevClassTemplate
&& PrevClassTemplate
->getAccess() != AS_none
) {
950 NewTemplate
->setAccess(PrevClassTemplate
->getAccess());
951 NewClass
->setAccess(PrevClassTemplate
->getAccess());
954 NewTemplate
->setObjectOfFriendDecl(/* PreviouslyDeclared = */
955 PrevClassTemplate
!= NULL
);
957 // Friend templates are visible in fairly strange ways.
958 if (!CurContext
->isDependentContext()) {
959 DeclContext
*DC
= SemanticContext
->getRedeclContext();
960 DC
->makeDeclVisibleInContext(NewTemplate
, /* Recoverable = */ false);
961 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
962 PushOnScopeChains(NewTemplate
, EnclosingScope
,
963 /* AddToContext = */ false);
966 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
,
967 NewClass
->getLocation(),
969 /*FIXME:*/NewClass
->getLocation());
970 Friend
->setAccess(AS_public
);
971 CurContext
->addDecl(Friend
);
975 NewTemplate
->setInvalidDecl();
976 NewClass
->setInvalidDecl();
981 /// \brief Diagnose the presence of a default template argument on a
982 /// template parameter, which is ill-formed in certain contexts.
984 /// \returns true if the default template argument should be dropped.
985 static bool DiagnoseDefaultTemplateArgument(Sema
&S
,
986 Sema::TemplateParamListContext TPC
,
987 SourceLocation ParamLoc
,
988 SourceRange DefArgRange
) {
990 case Sema::TPC_ClassTemplate
:
993 case Sema::TPC_FunctionTemplate
:
994 // C++ [temp.param]p9:
995 // A default template-argument shall not be specified in a
996 // function template declaration or a function template
998 // (This sentence is not in C++0x, per DR226).
999 if (!S
.getLangOptions().CPlusPlus0x
)
1001 diag::err_template_parameter_default_in_function_template
)
1005 case Sema::TPC_ClassTemplateMember
:
1006 // C++0x [temp.param]p9:
1007 // A default template-argument shall not be specified in the
1008 // template-parameter-lists of the definition of a member of a
1009 // class template that appears outside of the member's class.
1010 S
.Diag(ParamLoc
, diag::err_template_parameter_default_template_member
)
1014 case Sema::TPC_FriendFunctionTemplate
:
1015 // C++ [temp.param]p9:
1016 // A default template-argument shall not be specified in a
1017 // friend template declaration.
1018 S
.Diag(ParamLoc
, diag::err_template_parameter_default_friend_template
)
1022 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1023 // for friend function templates if there is only a single
1024 // declaration (and it is a definition). Strange!
1030 /// \brief Checks the validity of a template parameter list, possibly
1031 /// considering the template parameter list from a previous
1034 /// If an "old" template parameter list is provided, it must be
1035 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1036 /// template parameter list.
1038 /// \param NewParams Template parameter list for a new template
1039 /// declaration. This template parameter list will be updated with any
1040 /// default arguments that are carried through from the previous
1041 /// template parameter list.
1043 /// \param OldParams If provided, template parameter list from a
1044 /// previous declaration of the same template. Default template
1045 /// arguments will be merged from the old template parameter list to
1046 /// the new template parameter list.
1048 /// \param TPC Describes the context in which we are checking the given
1049 /// template parameter list.
1051 /// \returns true if an error occurred, false otherwise.
1052 bool Sema::CheckTemplateParameterList(TemplateParameterList
*NewParams
,
1053 TemplateParameterList
*OldParams
,
1054 TemplateParamListContext TPC
) {
1055 bool Invalid
= false;
1057 // C++ [temp.param]p10:
1058 // The set of default template-arguments available for use with a
1059 // template declaration or definition is obtained by merging the
1060 // default arguments from the definition (if in scope) and all
1061 // declarations in scope in the same way default function
1062 // arguments are (8.3.6).
1063 bool SawDefaultArgument
= false;
1064 SourceLocation PreviousDefaultArgLoc
;
1066 bool SawParameterPack
= false;
1067 SourceLocation ParameterPackLoc
;
1069 // Dummy initialization to avoid warnings.
1070 TemplateParameterList::iterator OldParam
= NewParams
->end();
1072 OldParam
= OldParams
->begin();
1074 for (TemplateParameterList::iterator NewParam
= NewParams
->begin(),
1075 NewParamEnd
= NewParams
->end();
1076 NewParam
!= NewParamEnd
; ++NewParam
) {
1077 // Variables used to diagnose redundant default arguments
1078 bool RedundantDefaultArg
= false;
1079 SourceLocation OldDefaultLoc
;
1080 SourceLocation NewDefaultLoc
;
1082 // Variables used to diagnose missing default arguments
1083 bool MissingDefaultArg
= false;
1085 // C++0x [temp.param]p11:
1086 // If a template parameter of a class template is a template parameter pack,
1087 // it must be the last template parameter.
1088 if (SawParameterPack
) {
1089 Diag(ParameterPackLoc
,
1090 diag::err_template_param_pack_must_be_last_template_parameter
);
1094 if (TemplateTypeParmDecl
*NewTypeParm
1095 = dyn_cast
<TemplateTypeParmDecl
>(*NewParam
)) {
1096 // Check the presence of a default argument here.
1097 if (NewTypeParm
->hasDefaultArgument() &&
1098 DiagnoseDefaultTemplateArgument(*this, TPC
,
1099 NewTypeParm
->getLocation(),
1100 NewTypeParm
->getDefaultArgumentInfo()->getTypeLoc()
1102 NewTypeParm
->removeDefaultArgument();
1104 // Merge default arguments for template type parameters.
1105 TemplateTypeParmDecl
*OldTypeParm
1106 = OldParams
? cast
<TemplateTypeParmDecl
>(*OldParam
) : 0;
1108 if (NewTypeParm
->isParameterPack()) {
1109 assert(!NewTypeParm
->hasDefaultArgument() &&
1110 "Parameter packs can't have a default argument!");
1111 SawParameterPack
= true;
1112 ParameterPackLoc
= NewTypeParm
->getLocation();
1113 } else if (OldTypeParm
&& OldTypeParm
->hasDefaultArgument() &&
1114 NewTypeParm
->hasDefaultArgument()) {
1115 OldDefaultLoc
= OldTypeParm
->getDefaultArgumentLoc();
1116 NewDefaultLoc
= NewTypeParm
->getDefaultArgumentLoc();
1117 SawDefaultArgument
= true;
1118 RedundantDefaultArg
= true;
1119 PreviousDefaultArgLoc
= NewDefaultLoc
;
1120 } else if (OldTypeParm
&& OldTypeParm
->hasDefaultArgument()) {
1121 // Merge the default argument from the old declaration to the
1123 SawDefaultArgument
= true;
1124 NewTypeParm
->setDefaultArgument(OldTypeParm
->getDefaultArgumentInfo(),
1126 PreviousDefaultArgLoc
= OldTypeParm
->getDefaultArgumentLoc();
1127 } else if (NewTypeParm
->hasDefaultArgument()) {
1128 SawDefaultArgument
= true;
1129 PreviousDefaultArgLoc
= NewTypeParm
->getDefaultArgumentLoc();
1130 } else if (SawDefaultArgument
)
1131 MissingDefaultArg
= true;
1132 } else if (NonTypeTemplateParmDecl
*NewNonTypeParm
1133 = dyn_cast
<NonTypeTemplateParmDecl
>(*NewParam
)) {
1134 // Check the presence of a default argument here.
1135 if (NewNonTypeParm
->hasDefaultArgument() &&
1136 DiagnoseDefaultTemplateArgument(*this, TPC
,
1137 NewNonTypeParm
->getLocation(),
1138 NewNonTypeParm
->getDefaultArgument()->getSourceRange())) {
1139 NewNonTypeParm
->removeDefaultArgument();
1142 // Merge default arguments for non-type template parameters
1143 NonTypeTemplateParmDecl
*OldNonTypeParm
1144 = OldParams
? cast
<NonTypeTemplateParmDecl
>(*OldParam
) : 0;
1145 if (OldNonTypeParm
&& OldNonTypeParm
->hasDefaultArgument() &&
1146 NewNonTypeParm
->hasDefaultArgument()) {
1147 OldDefaultLoc
= OldNonTypeParm
->getDefaultArgumentLoc();
1148 NewDefaultLoc
= NewNonTypeParm
->getDefaultArgumentLoc();
1149 SawDefaultArgument
= true;
1150 RedundantDefaultArg
= true;
1151 PreviousDefaultArgLoc
= NewDefaultLoc
;
1152 } else if (OldNonTypeParm
&& OldNonTypeParm
->hasDefaultArgument()) {
1153 // Merge the default argument from the old declaration to the
1155 SawDefaultArgument
= true;
1156 // FIXME: We need to create a new kind of "default argument"
1157 // expression that points to a previous template template
1159 NewNonTypeParm
->setDefaultArgument(
1160 OldNonTypeParm
->getDefaultArgument(),
1161 /*Inherited=*/ true);
1162 PreviousDefaultArgLoc
= OldNonTypeParm
->getDefaultArgumentLoc();
1163 } else if (NewNonTypeParm
->hasDefaultArgument()) {
1164 SawDefaultArgument
= true;
1165 PreviousDefaultArgLoc
= NewNonTypeParm
->getDefaultArgumentLoc();
1166 } else if (SawDefaultArgument
)
1167 MissingDefaultArg
= true;
1169 // Check the presence of a default argument here.
1170 TemplateTemplateParmDecl
*NewTemplateParm
1171 = cast
<TemplateTemplateParmDecl
>(*NewParam
);
1172 if (NewTemplateParm
->hasDefaultArgument() &&
1173 DiagnoseDefaultTemplateArgument(*this, TPC
,
1174 NewTemplateParm
->getLocation(),
1175 NewTemplateParm
->getDefaultArgument().getSourceRange()))
1176 NewTemplateParm
->removeDefaultArgument();
1178 // Merge default arguments for template template parameters
1179 TemplateTemplateParmDecl
*OldTemplateParm
1180 = OldParams
? cast
<TemplateTemplateParmDecl
>(*OldParam
) : 0;
1181 if (OldTemplateParm
&& OldTemplateParm
->hasDefaultArgument() &&
1182 NewTemplateParm
->hasDefaultArgument()) {
1183 OldDefaultLoc
= OldTemplateParm
->getDefaultArgument().getLocation();
1184 NewDefaultLoc
= NewTemplateParm
->getDefaultArgument().getLocation();
1185 SawDefaultArgument
= true;
1186 RedundantDefaultArg
= true;
1187 PreviousDefaultArgLoc
= NewDefaultLoc
;
1188 } else if (OldTemplateParm
&& OldTemplateParm
->hasDefaultArgument()) {
1189 // Merge the default argument from the old declaration to the
1191 SawDefaultArgument
= true;
1192 // FIXME: We need to create a new kind of "default argument" expression
1193 // that points to a previous template template parameter.
1194 NewTemplateParm
->setDefaultArgument(
1195 OldTemplateParm
->getDefaultArgument(),
1196 /*Inherited=*/ true);
1197 PreviousDefaultArgLoc
1198 = OldTemplateParm
->getDefaultArgument().getLocation();
1199 } else if (NewTemplateParm
->hasDefaultArgument()) {
1200 SawDefaultArgument
= true;
1201 PreviousDefaultArgLoc
1202 = NewTemplateParm
->getDefaultArgument().getLocation();
1203 } else if (SawDefaultArgument
)
1204 MissingDefaultArg
= true;
1207 if (RedundantDefaultArg
) {
1208 // C++ [temp.param]p12:
1209 // A template-parameter shall not be given default arguments
1210 // by two different declarations in the same scope.
1211 Diag(NewDefaultLoc
, diag::err_template_param_default_arg_redefinition
);
1212 Diag(OldDefaultLoc
, diag::note_template_param_prev_default_arg
);
1214 } else if (MissingDefaultArg
) {
1215 // C++ [temp.param]p11:
1216 // If a template-parameter has a default template-argument,
1217 // all subsequent template-parameters shall have a default
1218 // template-argument supplied.
1219 Diag((*NewParam
)->getLocation(),
1220 diag::err_template_param_default_arg_missing
);
1221 Diag(PreviousDefaultArgLoc
, diag::note_template_param_prev_default_arg
);
1225 // If we have an old template parameter list that we're merging
1226 // in, move on to the next parameter.
1236 /// A class which looks for a use of a certain level of template
1238 struct DependencyChecker
: RecursiveASTVisitor
<DependencyChecker
> {
1239 typedef RecursiveASTVisitor
<DependencyChecker
> super
;
1244 DependencyChecker(TemplateParameterList
*Params
) : Match(false) {
1245 NamedDecl
*ND
= Params
->getParam(0);
1246 if (TemplateTypeParmDecl
*PD
= dyn_cast
<TemplateTypeParmDecl
>(ND
)) {
1247 Depth
= PD
->getDepth();
1248 } else if (NonTypeTemplateParmDecl
*PD
=
1249 dyn_cast
<NonTypeTemplateParmDecl
>(ND
)) {
1250 Depth
= PD
->getDepth();
1252 Depth
= cast
<TemplateTemplateParmDecl
>(ND
)->getDepth();
1256 bool Matches(unsigned ParmDepth
) {
1257 if (ParmDepth
>= Depth
) {
1264 bool VisitTemplateTypeParmType(const TemplateTypeParmType
*T
) {
1265 return !Matches(T
->getDepth());
1268 bool TraverseTemplateName(TemplateName N
) {
1269 if (TemplateTemplateParmDecl
*PD
=
1270 dyn_cast_or_null
<TemplateTemplateParmDecl
>(N
.getAsTemplateDecl()))
1271 if (Matches(PD
->getDepth())) return false;
1272 return super::TraverseTemplateName(N
);
1275 bool VisitDeclRefExpr(DeclRefExpr
*E
) {
1276 if (NonTypeTemplateParmDecl
*PD
=
1277 dyn_cast
<NonTypeTemplateParmDecl
>(E
->getDecl())) {
1278 if (PD
->getDepth() == Depth
) {
1283 return super::VisitDeclRefExpr(E
);
1288 /// Determines whether a template-id depends on the given parameter
1291 DependsOnTemplateParameters(const TemplateSpecializationType
*TemplateId
,
1292 TemplateParameterList
*Params
) {
1293 DependencyChecker
Checker(Params
);
1294 Checker
.TraverseType(QualType(TemplateId
, 0));
1295 return Checker
.Match
;
1298 /// \brief Match the given template parameter lists to the given scope
1299 /// specifier, returning the template parameter list that applies to the
1302 /// \param DeclStartLoc the start of the declaration that has a scope
1303 /// specifier or a template parameter list.
1305 /// \param SS the scope specifier that will be matched to the given template
1306 /// parameter lists. This scope specifier precedes a qualified name that is
1309 /// \param ParamLists the template parameter lists, from the outermost to the
1310 /// innermost template parameter lists.
1312 /// \param NumParamLists the number of template parameter lists in ParamLists.
1314 /// \param IsFriend Whether to apply the slightly different rules for
1315 /// matching template parameters to scope specifiers in friend
1318 /// \param IsExplicitSpecialization will be set true if the entity being
1319 /// declared is an explicit specialization, false otherwise.
1321 /// \returns the template parameter list, if any, that corresponds to the
1322 /// name that is preceded by the scope specifier @p SS. This template
1323 /// parameter list may be have template parameters (if we're declaring a
1324 /// template) or may have no template parameters (if we're declaring a
1325 /// template specialization), or may be NULL (if we were's declaring isn't
1326 /// itself a template).
1327 TemplateParameterList
*
1328 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc
,
1329 const CXXScopeSpec
&SS
,
1330 TemplateParameterList
**ParamLists
,
1331 unsigned NumParamLists
,
1333 bool &IsExplicitSpecialization
,
1335 IsExplicitSpecialization
= false;
1337 // Find the template-ids that occur within the nested-name-specifier. These
1338 // template-ids will match up with the template parameter lists.
1339 llvm::SmallVector
<const TemplateSpecializationType
*, 4>
1340 TemplateIdsInSpecifier
;
1341 llvm::SmallVector
<ClassTemplateSpecializationDecl
*, 4>
1342 ExplicitSpecializationsInSpecifier
;
1343 for (NestedNameSpecifier
*NNS
= (NestedNameSpecifier
*)SS
.getScopeRep();
1344 NNS
; NNS
= NNS
->getPrefix()) {
1345 const Type
*T
= NNS
->getAsType();
1348 // C++0x [temp.expl.spec]p17:
1349 // A member or a member template may be nested within many
1350 // enclosing class templates. In an explicit specialization for
1351 // such a member, the member declaration shall be preceded by a
1352 // template<> for each enclosing class template that is
1353 // explicitly specialized.
1355 // Following the existing practice of GNU and EDG, we allow a typedef of a
1356 // template specialization type.
1357 if (const TypedefType
*TT
= dyn_cast
<TypedefType
>(T
))
1358 T
= TT
->LookThroughTypedefs().getTypePtr();
1360 if (const TemplateSpecializationType
*SpecType
1361 = dyn_cast
<TemplateSpecializationType
>(T
)) {
1362 TemplateDecl
*Template
= SpecType
->getTemplateName().getAsTemplateDecl();
1364 continue; // FIXME: should this be an error? probably...
1366 if (const RecordType
*Record
= SpecType
->getAs
<RecordType
>()) {
1367 ClassTemplateSpecializationDecl
*SpecDecl
1368 = cast
<ClassTemplateSpecializationDecl
>(Record
->getDecl());
1369 // If the nested name specifier refers to an explicit specialization,
1370 // we don't need a template<> header.
1371 if (SpecDecl
->getSpecializationKind() == TSK_ExplicitSpecialization
) {
1372 ExplicitSpecializationsInSpecifier
.push_back(SpecDecl
);
1377 TemplateIdsInSpecifier
.push_back(SpecType
);
1381 // Reverse the list of template-ids in the scope specifier, so that we can
1382 // more easily match up the template-ids and the template parameter lists.
1383 std::reverse(TemplateIdsInSpecifier
.begin(), TemplateIdsInSpecifier
.end());
1385 SourceLocation FirstTemplateLoc
= DeclStartLoc
;
1387 FirstTemplateLoc
= ParamLists
[0]->getTemplateLoc();
1389 // Match the template-ids found in the specifier to the template parameter
1391 unsigned ParamIdx
= 0, TemplateIdx
= 0;
1392 for (unsigned NumTemplateIds
= TemplateIdsInSpecifier
.size();
1393 TemplateIdx
!= NumTemplateIds
; ++TemplateIdx
) {
1394 const TemplateSpecializationType
*TemplateId
1395 = TemplateIdsInSpecifier
[TemplateIdx
];
1396 bool DependentTemplateId
= TemplateId
->isDependentType();
1398 // In friend declarations we can have template-ids which don't
1399 // depend on the corresponding template parameter lists. But
1400 // assume that empty parameter lists are supposed to match this
1402 if (IsFriend
&& ParamIdx
< NumParamLists
&& ParamLists
[ParamIdx
]->size()) {
1403 if (!DependentTemplateId
||
1404 !DependsOnTemplateParameters(TemplateId
, ParamLists
[ParamIdx
]))
1408 if (ParamIdx
>= NumParamLists
) {
1409 // We have a template-id without a corresponding template parameter
1412 // ...which is fine if this is a friend declaration.
1414 IsExplicitSpecialization
= true;
1418 if (DependentTemplateId
) {
1419 // FIXME: the location information here isn't great.
1420 Diag(SS
.getRange().getBegin(),
1421 diag::err_template_spec_needs_template_parameters
)
1422 << QualType(TemplateId
, 0)
1426 Diag(SS
.getRange().getBegin(), diag::err_template_spec_needs_header
)
1428 << FixItHint::CreateInsertion(FirstTemplateLoc
, "template<> ");
1429 IsExplicitSpecialization
= true;
1434 // Check the template parameter list against its corresponding template-id.
1435 if (DependentTemplateId
) {
1436 TemplateParameterList
*ExpectedTemplateParams
= 0;
1438 // Are there cases in (e.g.) friends where this won't match?
1439 if (const InjectedClassNameType
*Injected
1440 = TemplateId
->getAs
<InjectedClassNameType
>()) {
1441 CXXRecordDecl
*Record
= Injected
->getDecl();
1442 if (ClassTemplatePartialSpecializationDecl
*Partial
=
1443 dyn_cast
<ClassTemplatePartialSpecializationDecl
>(Record
))
1444 ExpectedTemplateParams
= Partial
->getTemplateParameters();
1446 ExpectedTemplateParams
= Record
->getDescribedClassTemplate()
1447 ->getTemplateParameters();
1450 if (ExpectedTemplateParams
)
1451 TemplateParameterListsAreEqual(ParamLists
[ParamIdx
],
1452 ExpectedTemplateParams
,
1453 true, TPL_TemplateMatch
);
1455 CheckTemplateParameterList(ParamLists
[ParamIdx
], 0,
1456 TPC_ClassTemplateMember
);
1457 } else if (ParamLists
[ParamIdx
]->size() > 0)
1458 Diag(ParamLists
[ParamIdx
]->getTemplateLoc(),
1459 diag::err_template_param_list_matches_nontemplate
)
1461 << ParamLists
[ParamIdx
]->getSourceRange();
1463 IsExplicitSpecialization
= true;
1468 // If there were at least as many template-ids as there were template
1469 // parameter lists, then there are no template parameter lists remaining for
1470 // the declaration itself.
1471 if (ParamIdx
>= NumParamLists
)
1474 // If there were too many template parameter lists, complain about that now.
1475 if (ParamIdx
!= NumParamLists
- 1) {
1476 while (ParamIdx
< NumParamLists
- 1) {
1477 bool isExplicitSpecHeader
= ParamLists
[ParamIdx
]->size() == 0;
1478 Diag(ParamLists
[ParamIdx
]->getTemplateLoc(),
1479 isExplicitSpecHeader
? diag::warn_template_spec_extra_headers
1480 : diag::err_template_spec_extra_headers
)
1481 << SourceRange(ParamLists
[ParamIdx
]->getTemplateLoc(),
1482 ParamLists
[ParamIdx
]->getRAngleLoc());
1484 if (isExplicitSpecHeader
&& !ExplicitSpecializationsInSpecifier
.empty()) {
1485 Diag(ExplicitSpecializationsInSpecifier
.back()->getLocation(),
1486 diag::note_explicit_template_spec_does_not_need_header
)
1487 << ExplicitSpecializationsInSpecifier
.back();
1488 ExplicitSpecializationsInSpecifier
.pop_back();
1491 // We have a template parameter list with no corresponding scope, which
1492 // means that the resulting template declaration can't be instantiated
1493 // properly (we'll end up with dependent nodes when we shouldn't).
1494 if (!isExplicitSpecHeader
)
1501 // Return the last template parameter list, which corresponds to the
1502 // entity being declared.
1503 return ParamLists
[NumParamLists
- 1];
1506 QualType
Sema::CheckTemplateIdType(TemplateName Name
,
1507 SourceLocation TemplateLoc
,
1508 const TemplateArgumentListInfo
&TemplateArgs
) {
1509 TemplateDecl
*Template
= Name
.getAsTemplateDecl();
1511 // The template name does not resolve to a template, so we just
1512 // build a dependent template-id type.
1513 return Context
.getTemplateSpecializationType(Name
, TemplateArgs
);
1516 // Check that the template argument list is well-formed for this
1518 llvm::SmallVector
<TemplateArgument
, 4> Converted
;
1519 if (CheckTemplateArgumentList(Template
, TemplateLoc
, TemplateArgs
,
1523 assert((Converted
.size() == Template
->getTemplateParameters()->size()) &&
1524 "Converted template argument list is too short!");
1528 if (Name
.isDependent() ||
1529 TemplateSpecializationType::anyDependentTemplateArguments(
1531 // This class template specialization is a dependent
1532 // type. Therefore, its canonical type is another class template
1533 // specialization type that contains all of the converted
1534 // arguments in canonical form. This ensures that, e.g., A<T> and
1535 // A<T, T> have identical types when A is declared as:
1537 // template<typename T, typename U = T> struct A;
1538 TemplateName CanonName
= Context
.getCanonicalTemplateName(Name
);
1539 CanonType
= Context
.getTemplateSpecializationType(CanonName
,
1543 // FIXME: CanonType is not actually the canonical type, and unfortunately
1544 // it is a TemplateSpecializationType that we will never use again.
1545 // In the future, we need to teach getTemplateSpecializationType to only
1546 // build the canonical type and return that to us.
1547 CanonType
= Context
.getCanonicalType(CanonType
);
1549 // This might work out to be a current instantiation, in which
1550 // case the canonical type needs to be the InjectedClassNameType.
1552 // TODO: in theory this could be a simple hashtable lookup; most
1553 // changes to CurContext don't change the set of current
1555 if (isa
<ClassTemplateDecl
>(Template
)) {
1556 for (DeclContext
*Ctx
= CurContext
; Ctx
; Ctx
= Ctx
->getLookupParent()) {
1557 // If we get out to a namespace, we're done.
1558 if (Ctx
->isFileContext()) break;
1560 // If this isn't a record, keep looking.
1561 CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Ctx
);
1562 if (!Record
) continue;
1564 // Look for one of the two cases with InjectedClassNameTypes
1565 // and check whether it's the same template.
1566 if (!isa
<ClassTemplatePartialSpecializationDecl
>(Record
) &&
1567 !Record
->getDescribedClassTemplate())
1570 // Fetch the injected class name type and check whether its
1571 // injected type is equal to the type we just built.
1572 QualType ICNT
= Context
.getTypeDeclType(Record
);
1573 QualType Injected
= cast
<InjectedClassNameType
>(ICNT
)
1574 ->getInjectedSpecializationType();
1576 if (CanonType
!= Injected
->getCanonicalTypeInternal())
1579 // If so, the canonical type of this TST is the injected
1580 // class name type of the record we just found.
1581 assert(ICNT
.isCanonical());
1586 } else if (ClassTemplateDecl
*ClassTemplate
1587 = dyn_cast
<ClassTemplateDecl
>(Template
)) {
1588 // Find the class template specialization declaration that
1589 // corresponds to these arguments.
1590 void *InsertPos
= 0;
1591 ClassTemplateSpecializationDecl
*Decl
1592 = ClassTemplate
->findSpecialization(Converted
.data(), Converted
.size(),
1595 // This is the first time we have referenced this class template
1596 // specialization. Create the canonical declaration and add it to
1597 // the set of specializations.
1598 Decl
= ClassTemplateSpecializationDecl::Create(Context
,
1599 ClassTemplate
->getTemplatedDecl()->getTagKind(),
1600 ClassTemplate
->getDeclContext(),
1601 ClassTemplate
->getLocation(),
1604 Converted
.size(), 0);
1605 ClassTemplate
->AddSpecialization(Decl
, InsertPos
);
1606 Decl
->setLexicalDeclContext(CurContext
);
1609 CanonType
= Context
.getTypeDeclType(Decl
);
1610 assert(isa
<RecordType
>(CanonType
) &&
1611 "type of non-dependent specialization is not a RecordType");
1614 // Build the fully-sugared type for this class template
1615 // specialization, which refers back to the class template
1616 // specialization we created or found.
1617 return Context
.getTemplateSpecializationType(Name
, TemplateArgs
, CanonType
);
1621 Sema::ActOnTemplateIdType(TemplateTy TemplateD
, SourceLocation TemplateLoc
,
1622 SourceLocation LAngleLoc
,
1623 ASTTemplateArgsPtr TemplateArgsIn
,
1624 SourceLocation RAngleLoc
) {
1625 TemplateName Template
= TemplateD
.getAsVal
<TemplateName
>();
1627 // Translate the parser's template argument list in our AST format.
1628 TemplateArgumentListInfo
TemplateArgs(LAngleLoc
, RAngleLoc
);
1629 translateTemplateArguments(TemplateArgsIn
, TemplateArgs
);
1631 QualType Result
= CheckTemplateIdType(Template
, TemplateLoc
, TemplateArgs
);
1632 TemplateArgsIn
.release();
1634 if (Result
.isNull())
1637 TypeSourceInfo
*DI
= Context
.CreateTypeSourceInfo(Result
);
1638 TemplateSpecializationTypeLoc TL
1639 = cast
<TemplateSpecializationTypeLoc
>(DI
->getTypeLoc());
1640 TL
.setTemplateNameLoc(TemplateLoc
);
1641 TL
.setLAngleLoc(LAngleLoc
);
1642 TL
.setRAngleLoc(RAngleLoc
);
1643 for (unsigned i
= 0, e
= TL
.getNumArgs(); i
!= e
; ++i
)
1644 TL
.setArgLocInfo(i
, TemplateArgs
[i
].getLocInfo());
1646 return CreateParsedType(Result
, DI
);
1649 TypeResult
Sema::ActOnTagTemplateIdType(TypeResult TypeResult
,
1651 TypeSpecifierType TagSpec
,
1652 SourceLocation TagLoc
) {
1653 if (TypeResult
.isInvalid())
1654 return ::TypeResult();
1656 // FIXME: preserve source info, ideally without copying the DI.
1658 QualType Type
= GetTypeFromParser(TypeResult
.get(), &DI
);
1660 // Verify the tag specifier.
1661 TagTypeKind TagKind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
1663 if (const RecordType
*RT
= Type
->getAs
<RecordType
>()) {
1664 RecordDecl
*D
= RT
->getDecl();
1666 IdentifierInfo
*Id
= D
->getIdentifier();
1667 assert(Id
&& "templated class must have an identifier");
1669 if (!isAcceptableTagRedeclaration(D
, TagKind
, TagLoc
, *Id
)) {
1670 Diag(TagLoc
, diag::err_use_with_wrong_tag
)
1672 << FixItHint::CreateReplacement(SourceRange(TagLoc
), D
->getKindName());
1673 Diag(D
->getLocation(), diag::note_previous_use
);
1677 ElaboratedTypeKeyword Keyword
1678 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind
);
1679 QualType ElabType
= Context
.getElaboratedType(Keyword
, /*NNS=*/0, Type
);
1681 return ParsedType::make(ElabType
);
1684 ExprResult
Sema::BuildTemplateIdExpr(const CXXScopeSpec
&SS
,
1687 const TemplateArgumentListInfo
&TemplateArgs
) {
1688 // FIXME: Can we do any checking at this point? I guess we could check the
1689 // template arguments that we have against the template name, if the template
1690 // name refers to a single template. That's not a terribly common case,
1693 // These should be filtered out by our callers.
1694 assert(!R
.empty() && "empty lookup results when building templateid");
1695 assert(!R
.isAmbiguous() && "ambiguous lookup when building templateid");
1697 NestedNameSpecifier
*Qualifier
= 0;
1698 SourceRange QualifierRange
;
1700 Qualifier
= static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
1701 QualifierRange
= SS
.getRange();
1704 // We don't want lookup warnings at this point.
1705 R
.suppressDiagnostics();
1708 = UnresolvedLookupExpr::ComputeDependence(R
.begin(), R
.end(),
1710 UnresolvedLookupExpr
*ULE
1711 = UnresolvedLookupExpr::Create(Context
, Dependent
, R
.getNamingClass(),
1712 Qualifier
, QualifierRange
,
1713 R
.getLookupNameInfo(),
1714 RequiresADL
, TemplateArgs
,
1715 R
.begin(), R
.end());
1720 // We actually only call this from template instantiation.
1722 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec
&SS
,
1723 const DeclarationNameInfo
&NameInfo
,
1724 const TemplateArgumentListInfo
&TemplateArgs
) {
1726 if (!(DC
= computeDeclContext(SS
, false)) ||
1727 DC
->isDependentContext() ||
1728 RequireCompleteDeclContext(SS
, DC
))
1729 return BuildDependentDeclRefExpr(SS
, NameInfo
, &TemplateArgs
);
1731 bool MemberOfUnknownSpecialization
;
1732 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
1733 LookupTemplateName(R
, (Scope
*) 0, SS
, QualType(), /*Entering*/ false,
1734 MemberOfUnknownSpecialization
);
1736 if (R
.isAmbiguous())
1740 Diag(NameInfo
.getLoc(), diag::err_template_kw_refers_to_non_template
)
1741 << NameInfo
.getName() << SS
.getRange();
1745 if (ClassTemplateDecl
*Temp
= R
.getAsSingle
<ClassTemplateDecl
>()) {
1746 Diag(NameInfo
.getLoc(), diag::err_template_kw_refers_to_class_template
)
1747 << (NestedNameSpecifier
*) SS
.getScopeRep()
1748 << NameInfo
.getName() << SS
.getRange();
1749 Diag(Temp
->getLocation(), diag::note_referenced_class_template
);
1753 return BuildTemplateIdExpr(SS
, R
, /* ADL */ false, TemplateArgs
);
1756 /// \brief Form a dependent template name.
1758 /// This action forms a dependent template name given the template
1759 /// name and its (presumably dependent) scope specifier. For
1760 /// example, given "MetaFun::template apply", the scope specifier \p
1761 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1762 /// of the "template" keyword, and "apply" is the \p Name.
1763 TemplateNameKind
Sema::ActOnDependentTemplateName(Scope
*S
,
1764 SourceLocation TemplateKWLoc
,
1766 UnqualifiedId
&Name
,
1767 ParsedType ObjectType
,
1768 bool EnteringContext
,
1769 TemplateTy
&Result
) {
1770 if (TemplateKWLoc
.isValid() && S
&& !S
->getTemplateParamParent() &&
1771 !getLangOptions().CPlusPlus0x
)
1772 Diag(TemplateKWLoc
, diag::ext_template_outside_of_template
)
1773 << FixItHint::CreateRemoval(TemplateKWLoc
);
1775 DeclContext
*LookupCtx
= 0;
1777 LookupCtx
= computeDeclContext(SS
, EnteringContext
);
1778 if (!LookupCtx
&& ObjectType
)
1779 LookupCtx
= computeDeclContext(ObjectType
.get());
1781 // C++0x [temp.names]p5:
1782 // If a name prefixed by the keyword template is not the name of
1783 // a template, the program is ill-formed. [Note: the keyword
1784 // template may not be applied to non-template members of class
1785 // templates. -end note ] [ Note: as is the case with the
1786 // typename prefix, the template prefix is allowed in cases
1787 // where it is not strictly necessary; i.e., when the
1788 // nested-name-specifier or the expression on the left of the ->
1789 // or . is not dependent on a template-parameter, or the use
1790 // does not appear in the scope of a template. -end note]
1792 // Note: C++03 was more strict here, because it banned the use of
1793 // the "template" keyword prior to a template-name that was not a
1794 // dependent name. C++ DR468 relaxed this requirement (the
1795 // "template" keyword is now permitted). We follow the C++0x
1796 // rules, even in C++03 mode with a warning, retroactively applying the DR.
1797 bool MemberOfUnknownSpecialization
;
1798 TemplateNameKind TNK
= isTemplateName(0, SS
, TemplateKWLoc
.isValid(), Name
,
1799 ObjectType
, EnteringContext
, Result
,
1800 MemberOfUnknownSpecialization
);
1801 if (TNK
== TNK_Non_template
&& LookupCtx
->isDependentContext() &&
1802 isa
<CXXRecordDecl
>(LookupCtx
) &&
1803 cast
<CXXRecordDecl
>(LookupCtx
)->hasAnyDependentBases()) {
1804 // This is a dependent template. Handle it below.
1805 } else if (TNK
== TNK_Non_template
) {
1806 Diag(Name
.getSourceRange().getBegin(),
1807 diag::err_template_kw_refers_to_non_template
)
1808 << GetNameFromUnqualifiedId(Name
).getName()
1809 << Name
.getSourceRange()
1811 return TNK_Non_template
;
1813 // We found something; return it.
1818 NestedNameSpecifier
*Qualifier
1819 = static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
1821 switch (Name
.getKind()) {
1822 case UnqualifiedId::IK_Identifier
:
1823 Result
= TemplateTy::make(Context
.getDependentTemplateName(Qualifier
,
1825 return TNK_Dependent_template_name
;
1827 case UnqualifiedId::IK_OperatorFunctionId
:
1828 Result
= TemplateTy::make(Context
.getDependentTemplateName(Qualifier
,
1829 Name
.OperatorFunctionId
.Operator
));
1830 return TNK_Dependent_template_name
;
1832 case UnqualifiedId::IK_LiteralOperatorId
:
1833 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1839 Diag(Name
.getSourceRange().getBegin(),
1840 diag::err_template_kw_refers_to_non_template
)
1841 << GetNameFromUnqualifiedId(Name
).getName()
1842 << Name
.getSourceRange()
1844 return TNK_Non_template
;
1847 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl
*Param
,
1848 const TemplateArgumentLoc
&AL
,
1849 llvm::SmallVectorImpl
<TemplateArgument
> &Converted
) {
1850 const TemplateArgument
&Arg
= AL
.getArgument();
1852 // Check template type parameter.
1853 switch(Arg
.getKind()) {
1854 case TemplateArgument::Type
:
1855 // C++ [temp.arg.type]p1:
1856 // A template-argument for a template-parameter which is a
1857 // type shall be a type-id.
1859 case TemplateArgument::Template
: {
1860 // We have a template type parameter but the template argument
1861 // is a template without any arguments.
1862 SourceRange SR
= AL
.getSourceRange();
1863 TemplateName Name
= Arg
.getAsTemplate();
1864 Diag(SR
.getBegin(), diag::err_template_missing_args
)
1866 if (TemplateDecl
*Decl
= Name
.getAsTemplateDecl())
1867 Diag(Decl
->getLocation(), diag::note_template_decl_here
);
1872 // We have a template type parameter but the template argument
1874 SourceRange SR
= AL
.getSourceRange();
1875 Diag(SR
.getBegin(), diag::err_template_arg_must_be_type
) << SR
;
1876 Diag(Param
->getLocation(), diag::note_template_param_here
);
1882 if (CheckTemplateArgument(Param
, AL
.getTypeSourceInfo()))
1885 // Add the converted template type argument.
1886 Converted
.push_back(
1887 TemplateArgument(Context
.getCanonicalType(Arg
.getAsType())));
1891 /// \brief Substitute template arguments into the default template argument for
1892 /// the given template type parameter.
1894 /// \param SemaRef the semantic analysis object for which we are performing
1895 /// the substitution.
1897 /// \param Template the template that we are synthesizing template arguments
1900 /// \param TemplateLoc the location of the template name that started the
1901 /// template-id we are checking.
1903 /// \param RAngleLoc the location of the right angle bracket ('>') that
1904 /// terminates the template-id.
1906 /// \param Param the template template parameter whose default we are
1907 /// substituting into.
1909 /// \param Converted the list of template arguments provided for template
1910 /// parameters that precede \p Param in the template parameter list.
1912 /// \returns the substituted template argument, or NULL if an error occurred.
1913 static TypeSourceInfo
*
1914 SubstDefaultTemplateArgument(Sema
&SemaRef
,
1915 TemplateDecl
*Template
,
1916 SourceLocation TemplateLoc
,
1917 SourceLocation RAngleLoc
,
1918 TemplateTypeParmDecl
*Param
,
1919 llvm::SmallVectorImpl
<TemplateArgument
> &Converted
) {
1920 TypeSourceInfo
*ArgType
= Param
->getDefaultArgumentInfo();
1922 // If the argument type is dependent, instantiate it now based
1923 // on the previously-computed template arguments.
1924 if (ArgType
->getType()->isDependentType()) {
1925 TemplateArgumentList
TemplateArgs(TemplateArgumentList::OnStack
,
1926 Converted
.data(), Converted
.size());
1928 MultiLevelTemplateArgumentList AllTemplateArgs
1929 = SemaRef
.getTemplateInstantiationArgs(Template
, &TemplateArgs
);
1931 Sema::InstantiatingTemplate
Inst(SemaRef
, TemplateLoc
,
1932 Template
, Converted
.data(),
1934 SourceRange(TemplateLoc
, RAngleLoc
));
1936 ArgType
= SemaRef
.SubstType(ArgType
, AllTemplateArgs
,
1937 Param
->getDefaultArgumentLoc(),
1938 Param
->getDeclName());
1944 /// \brief Substitute template arguments into the default template argument for
1945 /// the given non-type template parameter.
1947 /// \param SemaRef the semantic analysis object for which we are performing
1948 /// the substitution.
1950 /// \param Template the template that we are synthesizing template arguments
1953 /// \param TemplateLoc the location of the template name that started the
1954 /// template-id we are checking.
1956 /// \param RAngleLoc the location of the right angle bracket ('>') that
1957 /// terminates the template-id.
1959 /// \param Param the non-type template parameter whose default we are
1960 /// substituting into.
1962 /// \param Converted the list of template arguments provided for template
1963 /// parameters that precede \p Param in the template parameter list.
1965 /// \returns the substituted template argument, or NULL if an error occurred.
1967 SubstDefaultTemplateArgument(Sema
&SemaRef
,
1968 TemplateDecl
*Template
,
1969 SourceLocation TemplateLoc
,
1970 SourceLocation RAngleLoc
,
1971 NonTypeTemplateParmDecl
*Param
,
1972 llvm::SmallVectorImpl
<TemplateArgument
> &Converted
) {
1973 TemplateArgumentList
TemplateArgs(TemplateArgumentList::OnStack
,
1974 Converted
.data(), Converted
.size());
1976 MultiLevelTemplateArgumentList AllTemplateArgs
1977 = SemaRef
.getTemplateInstantiationArgs(Template
, &TemplateArgs
);
1979 Sema::InstantiatingTemplate
Inst(SemaRef
, TemplateLoc
,
1980 Template
, Converted
.data(),
1982 SourceRange(TemplateLoc
, RAngleLoc
));
1984 return SemaRef
.SubstExpr(Param
->getDefaultArgument(), AllTemplateArgs
);
1987 /// \brief Substitute template arguments into the default template argument for
1988 /// the given template template parameter.
1990 /// \param SemaRef the semantic analysis object for which we are performing
1991 /// the substitution.
1993 /// \param Template the template that we are synthesizing template arguments
1996 /// \param TemplateLoc the location of the template name that started the
1997 /// template-id we are checking.
1999 /// \param RAngleLoc the location of the right angle bracket ('>') that
2000 /// terminates the template-id.
2002 /// \param Param the template template parameter whose default we are
2003 /// substituting into.
2005 /// \param Converted the list of template arguments provided for template
2006 /// parameters that precede \p Param in the template parameter list.
2008 /// \returns the substituted template argument, or NULL if an error occurred.
2010 SubstDefaultTemplateArgument(Sema
&SemaRef
,
2011 TemplateDecl
*Template
,
2012 SourceLocation TemplateLoc
,
2013 SourceLocation RAngleLoc
,
2014 TemplateTemplateParmDecl
*Param
,
2015 llvm::SmallVectorImpl
<TemplateArgument
> &Converted
) {
2016 TemplateArgumentList
TemplateArgs(TemplateArgumentList::OnStack
,
2017 Converted
.data(), Converted
.size());
2019 MultiLevelTemplateArgumentList AllTemplateArgs
2020 = SemaRef
.getTemplateInstantiationArgs(Template
, &TemplateArgs
);
2022 Sema::InstantiatingTemplate
Inst(SemaRef
, TemplateLoc
,
2023 Template
, Converted
.data(),
2025 SourceRange(TemplateLoc
, RAngleLoc
));
2027 return SemaRef
.SubstTemplateName(
2028 Param
->getDefaultArgument().getArgument().getAsTemplate(),
2029 Param
->getDefaultArgument().getTemplateNameLoc(),
2033 /// \brief If the given template parameter has a default template
2034 /// argument, substitute into that default template argument and
2035 /// return the corresponding template argument.
2037 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl
*Template
,
2038 SourceLocation TemplateLoc
,
2039 SourceLocation RAngleLoc
,
2041 llvm::SmallVectorImpl
<TemplateArgument
> &Converted
) {
2042 if (TemplateTypeParmDecl
*TypeParm
= dyn_cast
<TemplateTypeParmDecl
>(Param
)) {
2043 if (!TypeParm
->hasDefaultArgument())
2044 return TemplateArgumentLoc();
2046 TypeSourceInfo
*DI
= SubstDefaultTemplateArgument(*this, Template
,
2052 return TemplateArgumentLoc(TemplateArgument(DI
->getType()), DI
);
2054 return TemplateArgumentLoc();
2057 if (NonTypeTemplateParmDecl
*NonTypeParm
2058 = dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
2059 if (!NonTypeParm
->hasDefaultArgument())
2060 return TemplateArgumentLoc();
2062 ExprResult Arg
= SubstDefaultTemplateArgument(*this, Template
,
2067 if (Arg
.isInvalid())
2068 return TemplateArgumentLoc();
2070 Expr
*ArgE
= Arg
.takeAs
<Expr
>();
2071 return TemplateArgumentLoc(TemplateArgument(ArgE
), ArgE
);
2074 TemplateTemplateParmDecl
*TempTempParm
2075 = cast
<TemplateTemplateParmDecl
>(Param
);
2076 if (!TempTempParm
->hasDefaultArgument())
2077 return TemplateArgumentLoc();
2079 TemplateName TName
= SubstDefaultTemplateArgument(*this, Template
,
2085 return TemplateArgumentLoc();
2087 return TemplateArgumentLoc(TemplateArgument(TName
),
2088 TempTempParm
->getDefaultArgument().getTemplateQualifierRange(),
2089 TempTempParm
->getDefaultArgument().getTemplateNameLoc());
2092 /// \brief Check that the given template argument corresponds to the given
2093 /// template parameter.
2094 bool Sema::CheckTemplateArgument(NamedDecl
*Param
,
2095 const TemplateArgumentLoc
&Arg
,
2096 TemplateDecl
*Template
,
2097 SourceLocation TemplateLoc
,
2098 SourceLocation RAngleLoc
,
2099 llvm::SmallVectorImpl
<TemplateArgument
> &Converted
,
2100 CheckTemplateArgumentKind CTAK
) {
2101 // Check template type parameters.
2102 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(Param
))
2103 return CheckTemplateTypeArgument(TTP
, Arg
, Converted
);
2105 // Check non-type template parameters.
2106 if (NonTypeTemplateParmDecl
*NTTP
=dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
2107 // Do substitution on the type of the non-type template parameter
2108 // with the template arguments we've seen thus far.
2109 QualType NTTPType
= NTTP
->getType();
2110 if (NTTPType
->isDependentType()) {
2111 // Do substitution on the type of the non-type template parameter.
2112 InstantiatingTemplate
Inst(*this, TemplateLoc
, Template
,
2113 NTTP
, Converted
.data(), Converted
.size(),
2114 SourceRange(TemplateLoc
, RAngleLoc
));
2116 TemplateArgumentList
TemplateArgs(TemplateArgumentList::OnStack
,
2117 Converted
.data(), Converted
.size());
2118 NTTPType
= SubstType(NTTPType
,
2119 MultiLevelTemplateArgumentList(TemplateArgs
),
2120 NTTP
->getLocation(),
2121 NTTP
->getDeclName());
2122 // If that worked, check the non-type template parameter type
2124 if (!NTTPType
.isNull())
2125 NTTPType
= CheckNonTypeTemplateParameterType(NTTPType
,
2126 NTTP
->getLocation());
2127 if (NTTPType
.isNull())
2131 switch (Arg
.getArgument().getKind()) {
2132 case TemplateArgument::Null
:
2133 assert(false && "Should never see a NULL template argument here");
2136 case TemplateArgument::Expression
: {
2137 Expr
*E
= Arg
.getArgument().getAsExpr();
2138 TemplateArgument Result
;
2139 if (CheckTemplateArgument(NTTP
, NTTPType
, E
, Result
, CTAK
))
2142 Converted
.push_back(Result
);
2146 case TemplateArgument::Declaration
:
2147 case TemplateArgument::Integral
:
2148 // We've already checked this template argument, so just copy
2149 // it to the list of converted arguments.
2150 Converted
.push_back(Arg
.getArgument());
2153 case TemplateArgument::Template
:
2154 // We were given a template template argument. It may not be ill-formed;
2156 if (DependentTemplateName
*DTN
2157 = Arg
.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2158 // We have a template argument such as \c T::template X, which we
2159 // parsed as a template template argument. However, since we now
2160 // know that we need a non-type template argument, convert this
2161 // template name into an expression.
2163 DeclarationNameInfo
NameInfo(DTN
->getIdentifier(),
2164 Arg
.getTemplateNameLoc());
2166 Expr
*E
= DependentScopeDeclRefExpr::Create(Context
,
2167 DTN
->getQualifier(),
2168 Arg
.getTemplateQualifierRange(),
2171 TemplateArgument Result
;
2172 if (CheckTemplateArgument(NTTP
, NTTPType
, E
, Result
))
2175 Converted
.push_back(Result
);
2179 // We have a template argument that actually does refer to a class
2180 // template, template alias, or template template parameter, and
2181 // therefore cannot be a non-type template argument.
2182 Diag(Arg
.getLocation(), diag::err_template_arg_must_be_expr
)
2183 << Arg
.getSourceRange();
2185 Diag(Param
->getLocation(), diag::note_template_param_here
);
2188 case TemplateArgument::Type
: {
2189 // We have a non-type template parameter but the template
2190 // argument is a type.
2192 // C++ [temp.arg]p2:
2193 // In a template-argument, an ambiguity between a type-id and
2194 // an expression is resolved to a type-id, regardless of the
2195 // form of the corresponding template-parameter.
2197 // We warn specifically about this case, since it can be rather
2198 // confusing for users.
2199 QualType T
= Arg
.getArgument().getAsType();
2200 SourceRange SR
= Arg
.getSourceRange();
2201 if (T
->isFunctionType())
2202 Diag(SR
.getBegin(), diag::err_template_arg_nontype_ambig
) << SR
<< T
;
2204 Diag(SR
.getBegin(), diag::err_template_arg_must_be_expr
) << SR
;
2205 Diag(Param
->getLocation(), diag::note_template_param_here
);
2209 case TemplateArgument::Pack
:
2210 llvm_unreachable("Caller must expand template argument packs");
2218 // Check template template parameters.
2219 TemplateTemplateParmDecl
*TempParm
= cast
<TemplateTemplateParmDecl
>(Param
);
2221 // Substitute into the template parameter list of the template
2222 // template parameter, since previously-supplied template arguments
2223 // may appear within the template template parameter.
2225 // Set up a template instantiation context.
2226 LocalInstantiationScope
Scope(*this);
2227 InstantiatingTemplate
Inst(*this, TemplateLoc
, Template
,
2228 TempParm
, Converted
.data(), Converted
.size(),
2229 SourceRange(TemplateLoc
, RAngleLoc
));
2231 TemplateArgumentList
TemplateArgs(TemplateArgumentList::OnStack
,
2232 Converted
.data(), Converted
.size());
2233 TempParm
= cast_or_null
<TemplateTemplateParmDecl
>(
2234 SubstDecl(TempParm
, CurContext
,
2235 MultiLevelTemplateArgumentList(TemplateArgs
)));
2239 // FIXME: TempParam is leaked.
2242 switch (Arg
.getArgument().getKind()) {
2243 case TemplateArgument::Null
:
2244 assert(false && "Should never see a NULL template argument here");
2247 case TemplateArgument::Template
:
2248 if (CheckTemplateArgument(TempParm
, Arg
))
2251 Converted
.push_back(Arg
.getArgument());
2254 case TemplateArgument::Expression
:
2255 case TemplateArgument::Type
:
2256 // We have a template template parameter but the template
2257 // argument does not refer to a template.
2258 Diag(Arg
.getLocation(), diag::err_template_arg_must_be_template
);
2261 case TemplateArgument::Declaration
:
2263 "Declaration argument with template template parameter");
2265 case TemplateArgument::Integral
:
2267 "Integral argument with template template parameter");
2270 case TemplateArgument::Pack
:
2271 llvm_unreachable("Caller must expand template argument packs");
2278 /// \brief Check that the given template argument list is well-formed
2279 /// for specializing the given template.
2280 bool Sema::CheckTemplateArgumentList(TemplateDecl
*Template
,
2281 SourceLocation TemplateLoc
,
2282 const TemplateArgumentListInfo
&TemplateArgs
,
2283 bool PartialTemplateArgs
,
2284 llvm::SmallVectorImpl
<TemplateArgument
> &Converted
) {
2285 TemplateParameterList
*Params
= Template
->getTemplateParameters();
2286 unsigned NumParams
= Params
->size();
2287 unsigned NumArgs
= TemplateArgs
.size();
2288 bool Invalid
= false;
2290 SourceLocation RAngleLoc
= TemplateArgs
.getRAngleLoc();
2292 bool HasParameterPack
=
2293 NumParams
> 0 && Params
->getParam(NumParams
- 1)->isTemplateParameterPack();
2295 if ((NumArgs
> NumParams
&& !HasParameterPack
) ||
2296 (NumArgs
< Params
->getMinRequiredArguments() &&
2297 !PartialTemplateArgs
)) {
2298 // FIXME: point at either the first arg beyond what we can handle,
2299 // or the '>', depending on whether we have too many or too few
2302 if (NumArgs
> NumParams
)
2303 Range
= SourceRange(TemplateArgs
[NumParams
].getLocation(), RAngleLoc
);
2304 Diag(TemplateLoc
, diag::err_template_arg_list_different_arity
)
2305 << (NumArgs
> NumParams
)
2306 << (isa
<ClassTemplateDecl
>(Template
)? 0 :
2307 isa
<FunctionTemplateDecl
>(Template
)? 1 :
2308 isa
<TemplateTemplateParmDecl
>(Template
)? 2 : 3)
2309 << Template
<< Range
;
2310 Diag(Template
->getLocation(), diag::note_template_decl_here
)
2311 << Params
->getSourceRange();
2315 // C++ [temp.arg]p1:
2316 // [...] The type and form of each template-argument specified in
2317 // a template-id shall match the type and form specified for the
2318 // corresponding parameter declared by the template in its
2319 // template-parameter-list.
2320 unsigned ArgIdx
= 0;
2321 for (TemplateParameterList::iterator Param
= Params
->begin(),
2322 ParamEnd
= Params
->end();
2323 Param
!= ParamEnd
; ++Param
, ++ArgIdx
) {
2324 if (ArgIdx
> NumArgs
&& PartialTemplateArgs
)
2327 // If we have a template parameter pack, check every remaining template
2328 // argument against that template parameter pack.
2329 if ((*Param
)->isTemplateParameterPack()) {
2330 Diag(TemplateLoc
, diag::err_variadic_templates_unsupported
);
2334 if (ArgIdx
< NumArgs
) {
2335 // Check the template argument we were given.
2336 if (CheckTemplateArgument(*Param
, TemplateArgs
[ArgIdx
], Template
,
2337 TemplateLoc
, RAngleLoc
, Converted
))
2343 // We have a default template argument that we will use.
2344 TemplateArgumentLoc Arg
;
2346 // Retrieve the default template argument from the template
2347 // parameter. For each kind of template parameter, we substitute the
2348 // template arguments provided thus far and any "outer" template arguments
2349 // (when the template parameter was part of a nested template) into
2350 // the default argument.
2351 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(*Param
)) {
2352 if (!TTP
->hasDefaultArgument()) {
2353 assert((Invalid
|| PartialTemplateArgs
) && "Missing default argument");
2357 TypeSourceInfo
*ArgType
= SubstDefaultTemplateArgument(*this,
2366 Arg
= TemplateArgumentLoc(TemplateArgument(ArgType
->getType()),
2368 } else if (NonTypeTemplateParmDecl
*NTTP
2369 = dyn_cast
<NonTypeTemplateParmDecl
>(*Param
)) {
2370 if (!NTTP
->hasDefaultArgument()) {
2371 assert((Invalid
|| PartialTemplateArgs
) && "Missing default argument");
2375 ExprResult E
= SubstDefaultTemplateArgument(*this, Template
,
2383 Expr
*Ex
= E
.takeAs
<Expr
>();
2384 Arg
= TemplateArgumentLoc(TemplateArgument(Ex
), Ex
);
2386 TemplateTemplateParmDecl
*TempParm
2387 = cast
<TemplateTemplateParmDecl
>(*Param
);
2389 if (!TempParm
->hasDefaultArgument()) {
2390 assert((Invalid
|| PartialTemplateArgs
) && "Missing default argument");
2394 TemplateName Name
= SubstDefaultTemplateArgument(*this, Template
,
2402 Arg
= TemplateArgumentLoc(TemplateArgument(Name
),
2403 TempParm
->getDefaultArgument().getTemplateQualifierRange(),
2404 TempParm
->getDefaultArgument().getTemplateNameLoc());
2407 // Introduce an instantiation record that describes where we are using
2408 // the default template argument.
2409 InstantiatingTemplate
Instantiating(*this, RAngleLoc
, Template
, *Param
,
2410 Converted
.data(), Converted
.size(),
2411 SourceRange(TemplateLoc
, RAngleLoc
));
2413 // Check the default template argument.
2414 if (CheckTemplateArgument(*Param
, Arg
, Template
, TemplateLoc
,
2415 RAngleLoc
, Converted
))
2423 class UnnamedLocalNoLinkageFinder
2424 : public TypeVisitor
<UnnamedLocalNoLinkageFinder
, bool>
2429 typedef TypeVisitor
<UnnamedLocalNoLinkageFinder
, bool> inherited
;
2432 UnnamedLocalNoLinkageFinder(Sema
&S
, SourceRange SR
) : S(S
), SR(SR
) { }
2434 bool Visit(QualType T
) {
2435 return inherited::Visit(T
.getTypePtr());
2438 #define TYPE(Class, Parent) \
2439 bool Visit##Class##Type(const Class##Type *);
2440 #define ABSTRACT_TYPE(Class, Parent) \
2441 bool Visit##Class##Type(const Class##Type *) { return false; }
2442 #define NON_CANONICAL_TYPE(Class, Parent) \
2443 bool Visit##Class##Type(const Class##Type *) { return false; }
2444 #include "clang/AST/TypeNodes.def"
2446 bool VisitTagDecl(const TagDecl
*Tag
);
2447 bool VisitNestedNameSpecifier(NestedNameSpecifier
*NNS
);
2451 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType
*) {
2455 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType
* T
) {
2456 return Visit(T
->getElementType());
2459 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType
* T
) {
2460 return Visit(T
->getPointeeType());
2463 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2464 const BlockPointerType
* T
) {
2465 return Visit(T
->getPointeeType());
2468 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2469 const LValueReferenceType
* T
) {
2470 return Visit(T
->getPointeeType());
2473 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2474 const RValueReferenceType
* T
) {
2475 return Visit(T
->getPointeeType());
2478 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2479 const MemberPointerType
* T
) {
2480 return Visit(T
->getPointeeType()) || Visit(QualType(T
->getClass(), 0));
2483 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2484 const ConstantArrayType
* T
) {
2485 return Visit(T
->getElementType());
2488 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2489 const IncompleteArrayType
* T
) {
2490 return Visit(T
->getElementType());
2493 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2494 const VariableArrayType
* T
) {
2495 return Visit(T
->getElementType());
2498 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2499 const DependentSizedArrayType
* T
) {
2500 return Visit(T
->getElementType());
2503 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2504 const DependentSizedExtVectorType
* T
) {
2505 return Visit(T
->getElementType());
2508 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType
* T
) {
2509 return Visit(T
->getElementType());
2512 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType
* T
) {
2513 return Visit(T
->getElementType());
2516 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2517 const FunctionProtoType
* T
) {
2518 for (FunctionProtoType::arg_type_iterator A
= T
->arg_type_begin(),
2519 AEnd
= T
->arg_type_end();
2525 return Visit(T
->getResultType());
2528 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2529 const FunctionNoProtoType
* T
) {
2530 return Visit(T
->getResultType());
2533 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2534 const UnresolvedUsingType
*) {
2538 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType
*) {
2542 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType
* T
) {
2543 return Visit(T
->getUnderlyingType());
2546 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType
*) {
2550 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType
* T
) {
2551 return VisitTagDecl(T
->getDecl());
2554 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType
* T
) {
2555 return VisitTagDecl(T
->getDecl());
2558 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2559 const TemplateTypeParmType
*) {
2563 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2564 const TemplateSpecializationType
*) {
2568 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2569 const InjectedClassNameType
* T
) {
2570 return VisitTagDecl(T
->getDecl());
2573 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2574 const DependentNameType
* T
) {
2575 return VisitNestedNameSpecifier(T
->getQualifier());
2578 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2579 const DependentTemplateSpecializationType
* T
) {
2580 return VisitNestedNameSpecifier(T
->getQualifier());
2583 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType
*) {
2587 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2588 const ObjCInterfaceType
*) {
2592 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2593 const ObjCObjectPointerType
*) {
2597 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl
*Tag
) {
2598 if (Tag
->getDeclContext()->isFunctionOrMethod()) {
2599 S
.Diag(SR
.getBegin(), diag::ext_template_arg_local_type
)
2600 << S
.Context
.getTypeDeclType(Tag
) << SR
;
2604 if (!Tag
->getDeclName() && !Tag
->getTypedefForAnonDecl()) {
2605 S
.Diag(SR
.getBegin(), diag::ext_template_arg_unnamed_type
) << SR
;
2606 S
.Diag(Tag
->getLocation(), diag::note_template_unnamed_type_here
);
2613 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2614 NestedNameSpecifier
*NNS
) {
2615 if (NNS
->getPrefix() && VisitNestedNameSpecifier(NNS
->getPrefix()))
2618 switch (NNS
->getKind()) {
2619 case NestedNameSpecifier::Identifier
:
2620 case NestedNameSpecifier::Namespace
:
2621 case NestedNameSpecifier::Global
:
2624 case NestedNameSpecifier::TypeSpec
:
2625 case NestedNameSpecifier::TypeSpecWithTemplate
:
2626 return Visit(QualType(NNS
->getAsType(), 0));
2632 /// \brief Check a template argument against its corresponding
2633 /// template type parameter.
2635 /// This routine implements the semantics of C++ [temp.arg.type]. It
2636 /// returns true if an error occurred, and false otherwise.
2637 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl
*Param
,
2638 TypeSourceInfo
*ArgInfo
) {
2639 assert(ArgInfo
&& "invalid TypeSourceInfo");
2640 QualType Arg
= ArgInfo
->getType();
2641 SourceRange SR
= ArgInfo
->getTypeLoc().getSourceRange();
2643 if (Arg
->isVariablyModifiedType()) {
2644 return Diag(SR
.getBegin(), diag::err_variably_modified_template_arg
) << Arg
;
2645 } else if (Context
.hasSameUnqualifiedType(Arg
, Context
.OverloadTy
)) {
2646 return Diag(SR
.getBegin(), diag::err_template_arg_overload_type
) << SR
;
2649 // C++03 [temp.arg.type]p2:
2650 // A local type, a type with no linkage, an unnamed type or a type
2651 // compounded from any of these types shall not be used as a
2652 // template-argument for a template type-parameter.
2654 // C++0x allows these, and even in C++03 we allow them as an extension with
2656 if (!LangOpts
.CPlusPlus0x
&& Arg
->hasUnnamedOrLocalType()) {
2657 UnnamedLocalNoLinkageFinder
Finder(*this, SR
);
2658 (void)Finder
.Visit(Context
.getCanonicalType(Arg
));
2664 /// \brief Checks whether the given template argument is the address
2665 /// of an object or function according to C++ [temp.arg.nontype]p1.
2667 CheckTemplateArgumentAddressOfObjectOrFunction(Sema
&S
,
2668 NonTypeTemplateParmDecl
*Param
,
2671 TemplateArgument
&Converted
) {
2672 bool Invalid
= false;
2674 QualType ArgType
= Arg
->getType();
2676 // See through any implicit casts we added to fix the type.
2677 while (ImplicitCastExpr
*Cast
= dyn_cast
<ImplicitCastExpr
>(Arg
))
2678 Arg
= Cast
->getSubExpr();
2680 // C++ [temp.arg.nontype]p1:
2682 // A template-argument for a non-type, non-template
2683 // template-parameter shall be one of: [...]
2685 // -- the address of an object or function with external
2686 // linkage, including function templates and function
2687 // template-ids but excluding non-static class members,
2688 // expressed as & id-expression where the & is optional if
2689 // the name refers to a function or array, or if the
2690 // corresponding template-parameter is a reference; or
2691 DeclRefExpr
*DRE
= 0;
2693 // In C++98/03 mode, give an extension warning on any extra parentheses.
2694 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2695 bool ExtraParens
= false;
2696 while (ParenExpr
*Parens
= dyn_cast
<ParenExpr
>(Arg
)) {
2697 if (!Invalid
&& !ExtraParens
&& !S
.getLangOptions().CPlusPlus0x
) {
2698 S
.Diag(Arg
->getSourceRange().getBegin(),
2699 diag::ext_template_arg_extra_parens
)
2700 << Arg
->getSourceRange();
2704 Arg
= Parens
->getSubExpr();
2707 bool AddressTaken
= false;
2708 SourceLocation AddrOpLoc
;
2709 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(Arg
)) {
2710 if (UnOp
->getOpcode() == UO_AddrOf
) {
2711 DRE
= dyn_cast
<DeclRefExpr
>(UnOp
->getSubExpr());
2712 AddressTaken
= true;
2713 AddrOpLoc
= UnOp
->getOperatorLoc();
2716 DRE
= dyn_cast
<DeclRefExpr
>(Arg
);
2719 S
.Diag(Arg
->getLocStart(), diag::err_template_arg_not_decl_ref
)
2720 << Arg
->getSourceRange();
2721 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2725 // Stop checking the precise nature of the argument if it is value dependent,
2726 // it should be checked when instantiated.
2727 if (Arg
->isValueDependent()) {
2728 Converted
= TemplateArgument(ArgIn
);
2732 if (!isa
<ValueDecl
>(DRE
->getDecl())) {
2733 S
.Diag(Arg
->getSourceRange().getBegin(),
2734 diag::err_template_arg_not_object_or_func_form
)
2735 << Arg
->getSourceRange();
2736 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2740 NamedDecl
*Entity
= 0;
2742 // Cannot refer to non-static data members
2743 if (FieldDecl
*Field
= dyn_cast
<FieldDecl
>(DRE
->getDecl())) {
2744 S
.Diag(Arg
->getSourceRange().getBegin(), diag::err_template_arg_field
)
2745 << Field
<< Arg
->getSourceRange();
2746 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2750 // Cannot refer to non-static member functions
2751 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(DRE
->getDecl()))
2752 if (!Method
->isStatic()) {
2753 S
.Diag(Arg
->getSourceRange().getBegin(), diag::err_template_arg_method
)
2754 << Method
<< Arg
->getSourceRange();
2755 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2759 // Functions must have external linkage.
2760 if (FunctionDecl
*Func
= dyn_cast
<FunctionDecl
>(DRE
->getDecl())) {
2761 if (!isExternalLinkage(Func
->getLinkage())) {
2762 S
.Diag(Arg
->getSourceRange().getBegin(),
2763 diag::err_template_arg_function_not_extern
)
2764 << Func
<< Arg
->getSourceRange();
2765 S
.Diag(Func
->getLocation(), diag::note_template_arg_internal_object
)
2770 // Okay: we've named a function with external linkage.
2773 // If the template parameter has pointer type, the function decays.
2774 if (ParamType
->isPointerType() && !AddressTaken
)
2775 ArgType
= S
.Context
.getPointerType(Func
->getType());
2776 else if (AddressTaken
&& ParamType
->isReferenceType()) {
2777 // If we originally had an address-of operator, but the
2778 // parameter has reference type, complain and (if things look
2779 // like they will work) drop the address-of operator.
2780 if (!S
.Context
.hasSameUnqualifiedType(Func
->getType(),
2781 ParamType
.getNonReferenceType())) {
2782 S
.Diag(AddrOpLoc
, diag::err_template_arg_address_of_non_pointer
)
2784 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2788 S
.Diag(AddrOpLoc
, diag::err_template_arg_address_of_non_pointer
)
2790 << FixItHint::CreateRemoval(AddrOpLoc
);
2791 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2793 ArgType
= Func
->getType();
2795 } else if (VarDecl
*Var
= dyn_cast
<VarDecl
>(DRE
->getDecl())) {
2796 if (!isExternalLinkage(Var
->getLinkage())) {
2797 S
.Diag(Arg
->getSourceRange().getBegin(),
2798 diag::err_template_arg_object_not_extern
)
2799 << Var
<< Arg
->getSourceRange();
2800 S
.Diag(Var
->getLocation(), diag::note_template_arg_internal_object
)
2805 // A value of reference type is not an object.
2806 if (Var
->getType()->isReferenceType()) {
2807 S
.Diag(Arg
->getSourceRange().getBegin(),
2808 diag::err_template_arg_reference_var
)
2809 << Var
->getType() << Arg
->getSourceRange();
2810 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2814 // Okay: we've named an object with external linkage
2817 // If the template parameter has pointer type, we must have taken
2818 // the address of this object.
2819 if (ParamType
->isReferenceType()) {
2821 // If we originally had an address-of operator, but the
2822 // parameter has reference type, complain and (if things look
2823 // like they will work) drop the address-of operator.
2824 if (!S
.Context
.hasSameUnqualifiedType(Var
->getType(),
2825 ParamType
.getNonReferenceType())) {
2826 S
.Diag(AddrOpLoc
, diag::err_template_arg_address_of_non_pointer
)
2828 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2832 S
.Diag(AddrOpLoc
, diag::err_template_arg_address_of_non_pointer
)
2834 << FixItHint::CreateRemoval(AddrOpLoc
);
2835 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2837 ArgType
= Var
->getType();
2839 } else if (!AddressTaken
&& ParamType
->isPointerType()) {
2840 if (Var
->getType()->isArrayType()) {
2841 // Array-to-pointer decay.
2842 ArgType
= S
.Context
.getArrayDecayedType(Var
->getType());
2844 // If the template parameter has pointer type but the address of
2845 // this object was not taken, complain and (possibly) recover by
2846 // taking the address of the entity.
2847 ArgType
= S
.Context
.getPointerType(Var
->getType());
2848 if (!S
.Context
.hasSameUnqualifiedType(ArgType
, ParamType
)) {
2849 S
.Diag(Arg
->getLocStart(), diag::err_template_arg_not_address_of
)
2851 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2855 S
.Diag(Arg
->getLocStart(), diag::err_template_arg_not_address_of
)
2857 << FixItHint::CreateInsertion(Arg
->getLocStart(), "&");
2859 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2863 // We found something else, but we don't know specifically what it is.
2864 S
.Diag(Arg
->getSourceRange().getBegin(),
2865 diag::err_template_arg_not_object_or_func
)
2866 << Arg
->getSourceRange();
2867 S
.Diag(DRE
->getDecl()->getLocation(), diag::note_template_arg_refers_here
);
2871 if (ParamType
->isPointerType() &&
2872 !ParamType
->getAs
<PointerType
>()->getPointeeType()->isFunctionType() &&
2873 S
.IsQualificationConversion(ArgType
, ParamType
)) {
2874 // For pointer-to-object types, qualification conversions are
2877 if (const ReferenceType
*ParamRef
= ParamType
->getAs
<ReferenceType
>()) {
2878 if (!ParamRef
->getPointeeType()->isFunctionType()) {
2879 // C++ [temp.arg.nontype]p5b3:
2880 // For a non-type template-parameter of type reference to
2881 // object, no conversions apply. The type referred to by the
2882 // reference may be more cv-qualified than the (otherwise
2883 // identical) type of the template- argument. The
2884 // template-parameter is bound directly to the
2885 // template-argument, which shall be an lvalue.
2887 // FIXME: Other qualifiers?
2888 unsigned ParamQuals
= ParamRef
->getPointeeType().getCVRQualifiers();
2889 unsigned ArgQuals
= ArgType
.getCVRQualifiers();
2891 if ((ParamQuals
| ArgQuals
) != ParamQuals
) {
2892 S
.Diag(Arg
->getSourceRange().getBegin(),
2893 diag::err_template_arg_ref_bind_ignores_quals
)
2894 << ParamType
<< Arg
->getType()
2895 << Arg
->getSourceRange();
2896 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2902 // At this point, the template argument refers to an object or
2903 // function with external linkage. We now need to check whether the
2904 // argument and parameter types are compatible.
2905 if (!S
.Context
.hasSameUnqualifiedType(ArgType
,
2906 ParamType
.getNonReferenceType())) {
2907 // We can't perform this conversion or binding.
2908 if (ParamType
->isReferenceType())
2909 S
.Diag(Arg
->getLocStart(), diag::err_template_arg_no_ref_bind
)
2910 << ParamType
<< Arg
->getType() << Arg
->getSourceRange();
2912 S
.Diag(Arg
->getLocStart(), diag::err_template_arg_not_convertible
)
2913 << Arg
->getType() << ParamType
<< Arg
->getSourceRange();
2914 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
2919 // Create the template argument.
2920 Converted
= TemplateArgument(Entity
->getCanonicalDecl());
2921 S
.MarkDeclarationReferenced(Arg
->getLocStart(), Entity
);
2925 /// \brief Checks whether the given template argument is a pointer to
2926 /// member constant according to C++ [temp.arg.nontype]p1.
2927 bool Sema::CheckTemplateArgumentPointerToMember(Expr
*Arg
,
2928 TemplateArgument
&Converted
) {
2929 bool Invalid
= false;
2931 // See through any implicit casts we added to fix the type.
2932 while (ImplicitCastExpr
*Cast
= dyn_cast
<ImplicitCastExpr
>(Arg
))
2933 Arg
= Cast
->getSubExpr();
2935 // C++ [temp.arg.nontype]p1:
2937 // A template-argument for a non-type, non-template
2938 // template-parameter shall be one of: [...]
2940 // -- a pointer to member expressed as described in 5.3.1.
2941 DeclRefExpr
*DRE
= 0;
2943 // In C++98/03 mode, give an extension warning on any extra parentheses.
2944 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2945 bool ExtraParens
= false;
2946 while (ParenExpr
*Parens
= dyn_cast
<ParenExpr
>(Arg
)) {
2947 if (!Invalid
&& !ExtraParens
&& !getLangOptions().CPlusPlus0x
) {
2948 Diag(Arg
->getSourceRange().getBegin(),
2949 diag::ext_template_arg_extra_parens
)
2950 << Arg
->getSourceRange();
2954 Arg
= Parens
->getSubExpr();
2957 // A pointer-to-member constant written &Class::member.
2958 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(Arg
)) {
2959 if (UnOp
->getOpcode() == UO_AddrOf
) {
2960 DRE
= dyn_cast
<DeclRefExpr
>(UnOp
->getSubExpr());
2961 if (DRE
&& !DRE
->getQualifier())
2965 // A constant of pointer-to-member type.
2966 else if ((DRE
= dyn_cast
<DeclRefExpr
>(Arg
))) {
2967 if (ValueDecl
*VD
= dyn_cast
<ValueDecl
>(DRE
->getDecl())) {
2968 if (VD
->getType()->isMemberPointerType()) {
2969 if (isa
<NonTypeTemplateParmDecl
>(VD
) ||
2970 (isa
<VarDecl
>(VD
) &&
2971 Context
.getCanonicalType(VD
->getType()).isConstQualified())) {
2972 if (Arg
->isTypeDependent() || Arg
->isValueDependent())
2973 Converted
= TemplateArgument(Arg
);
2975 Converted
= TemplateArgument(VD
->getCanonicalDecl());
2985 return Diag(Arg
->getSourceRange().getBegin(),
2986 diag::err_template_arg_not_pointer_to_member_form
)
2987 << Arg
->getSourceRange();
2989 if (isa
<FieldDecl
>(DRE
->getDecl()) || isa
<CXXMethodDecl
>(DRE
->getDecl())) {
2990 assert((isa
<FieldDecl
>(DRE
->getDecl()) ||
2991 !cast
<CXXMethodDecl
>(DRE
->getDecl())->isStatic()) &&
2992 "Only non-static member pointers can make it here");
2994 // Okay: this is the address of a non-static member, and therefore
2995 // a member pointer constant.
2996 if (Arg
->isTypeDependent() || Arg
->isValueDependent())
2997 Converted
= TemplateArgument(Arg
);
2999 Converted
= TemplateArgument(DRE
->getDecl()->getCanonicalDecl());
3003 // We found something else, but we don't know specifically what it is.
3004 Diag(Arg
->getSourceRange().getBegin(),
3005 diag::err_template_arg_not_pointer_to_member_form
)
3006 << Arg
->getSourceRange();
3007 Diag(DRE
->getDecl()->getLocation(),
3008 diag::note_template_arg_refers_here
);
3012 /// \brief Check a template argument against its corresponding
3013 /// non-type template parameter.
3015 /// This routine implements the semantics of C++ [temp.arg.nontype].
3016 /// It returns true if an error occurred, and false otherwise. \p
3017 /// InstantiatedParamType is the type of the non-type template
3018 /// parameter after it has been instantiated.
3020 /// If no error was detected, Converted receives the converted template argument.
3021 bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl
*Param
,
3022 QualType InstantiatedParamType
, Expr
*&Arg
,
3023 TemplateArgument
&Converted
,
3024 CheckTemplateArgumentKind CTAK
) {
3025 SourceLocation StartLoc
= Arg
->getSourceRange().getBegin();
3027 // If either the parameter has a dependent type or the argument is
3028 // type-dependent, there's nothing we can check now.
3029 if (InstantiatedParamType
->isDependentType() || Arg
->isTypeDependent()) {
3030 // FIXME: Produce a cloned, canonical expression?
3031 Converted
= TemplateArgument(Arg
);
3035 // C++ [temp.arg.nontype]p5:
3036 // The following conversions are performed on each expression used
3037 // as a non-type template-argument. If a non-type
3038 // template-argument cannot be converted to the type of the
3039 // corresponding template-parameter then the program is
3042 // -- for a non-type template-parameter of integral or
3043 // enumeration type, integral promotions (4.5) and integral
3044 // conversions (4.7) are applied.
3045 QualType ParamType
= InstantiatedParamType
;
3046 QualType ArgType
= Arg
->getType();
3047 if (ParamType
->isIntegralOrEnumerationType()) {
3048 // C++ [temp.arg.nontype]p1:
3049 // A template-argument for a non-type, non-template
3050 // template-parameter shall be one of:
3052 // -- an integral constant-expression of integral or enumeration
3054 // -- the name of a non-type template-parameter; or
3055 SourceLocation NonConstantLoc
;
3057 if (!ArgType
->isIntegralOrEnumerationType()) {
3058 Diag(Arg
->getSourceRange().getBegin(),
3059 diag::err_template_arg_not_integral_or_enumeral
)
3060 << ArgType
<< Arg
->getSourceRange();
3061 Diag(Param
->getLocation(), diag::note_template_param_here
);
3063 } else if (!Arg
->isValueDependent() &&
3064 !Arg
->isIntegerConstantExpr(Value
, Context
, &NonConstantLoc
)) {
3065 Diag(NonConstantLoc
, diag::err_template_arg_not_ice
)
3066 << ArgType
<< Arg
->getSourceRange();
3070 // From here on out, all we care about are the unqualified forms
3071 // of the parameter and argument types.
3072 ParamType
= ParamType
.getUnqualifiedType();
3073 ArgType
= ArgType
.getUnqualifiedType();
3075 // Try to convert the argument to the parameter's type.
3076 if (Context
.hasSameType(ParamType
, ArgType
)) {
3077 // Okay: no conversion necessary
3078 } else if (CTAK
== CTAK_Deduced
) {
3079 // C++ [temp.deduct.type]p17:
3080 // If, in the declaration of a function template with a non-type
3081 // template-parameter, the non-type template- parameter is used
3082 // in an expression in the function parameter-list and, if the
3083 // corresponding template-argument is deduced, the
3084 // template-argument type shall match the type of the
3085 // template-parameter exactly, except that a template-argument
3086 // deduced from an array bound may be of any integral type.
3087 Diag(StartLoc
, diag::err_deduced_non_type_template_arg_type_mismatch
)
3088 << ArgType
<< ParamType
;
3089 Diag(Param
->getLocation(), diag::note_template_param_here
);
3091 } else if (ParamType
->isBooleanType()) {
3092 // This is an integral-to-boolean conversion.
3093 ImpCastExprToType(Arg
, ParamType
, CK_IntegralToBoolean
);
3094 } else if (IsIntegralPromotion(Arg
, ArgType
, ParamType
) ||
3095 !ParamType
->isEnumeralType()) {
3096 // This is an integral promotion or conversion.
3097 ImpCastExprToType(Arg
, ParamType
, CK_IntegralCast
);
3099 // We can't perform this conversion.
3100 Diag(Arg
->getSourceRange().getBegin(),
3101 diag::err_template_arg_not_convertible
)
3102 << Arg
->getType() << InstantiatedParamType
<< Arg
->getSourceRange();
3103 Diag(Param
->getLocation(), diag::note_template_param_here
);
3107 QualType IntegerType
= Context
.getCanonicalType(ParamType
);
3108 if (const EnumType
*Enum
= IntegerType
->getAs
<EnumType
>())
3109 IntegerType
= Context
.getCanonicalType(Enum
->getDecl()->getIntegerType());
3111 if (!Arg
->isValueDependent()) {
3112 llvm::APSInt OldValue
= Value
;
3114 // Coerce the template argument's value to the value it will have
3115 // based on the template parameter's type.
3116 unsigned AllowedBits
= Context
.getTypeSize(IntegerType
);
3117 if (Value
.getBitWidth() != AllowedBits
)
3118 Value
.extOrTrunc(AllowedBits
);
3119 Value
.setIsSigned(IntegerType
->isSignedIntegerType());
3121 // Complain if an unsigned parameter received a negative value.
3122 if (IntegerType
->isUnsignedIntegerType()
3123 && (OldValue
.isSigned() && OldValue
.isNegative())) {
3124 Diag(Arg
->getSourceRange().getBegin(), diag::warn_template_arg_negative
)
3125 << OldValue
.toString(10) << Value
.toString(10) << Param
->getType()
3126 << Arg
->getSourceRange();
3127 Diag(Param
->getLocation(), diag::note_template_param_here
);
3130 // Complain if we overflowed the template parameter's type.
3131 unsigned RequiredBits
;
3132 if (IntegerType
->isUnsignedIntegerType())
3133 RequiredBits
= OldValue
.getActiveBits();
3134 else if (OldValue
.isUnsigned())
3135 RequiredBits
= OldValue
.getActiveBits() + 1;
3137 RequiredBits
= OldValue
.getMinSignedBits();
3138 if (RequiredBits
> AllowedBits
) {
3139 Diag(Arg
->getSourceRange().getBegin(),
3140 diag::warn_template_arg_too_large
)
3141 << OldValue
.toString(10) << Value
.toString(10) << Param
->getType()
3142 << Arg
->getSourceRange();
3143 Diag(Param
->getLocation(), diag::note_template_param_here
);
3147 // Add the value of this argument to the list of converted
3148 // arguments. We use the bitwidth and signedness of the template
3150 if (Arg
->isValueDependent()) {
3151 // The argument is value-dependent. Create a new
3152 // TemplateArgument with the converted expression.
3153 Converted
= TemplateArgument(Arg
);
3157 Converted
= TemplateArgument(Value
,
3158 ParamType
->isEnumeralType() ? ParamType
3163 DeclAccessPair FoundResult
; // temporary for ResolveOverloadedFunction
3165 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3166 // from a template argument of type std::nullptr_t to a non-type
3167 // template parameter of type pointer to object, pointer to
3168 // function, or pointer-to-member, respectively.
3169 if (ArgType
->isNullPtrType() &&
3170 (ParamType
->isPointerType() || ParamType
->isMemberPointerType())) {
3171 Converted
= TemplateArgument((NamedDecl
*)0);
3175 // Handle pointer-to-function, reference-to-function, and
3176 // pointer-to-member-function all in (roughly) the same way.
3177 if (// -- For a non-type template-parameter of type pointer to
3178 // function, only the function-to-pointer conversion (4.3) is
3179 // applied. If the template-argument represents a set of
3180 // overloaded functions (or a pointer to such), the matching
3181 // function is selected from the set (13.4).
3182 (ParamType
->isPointerType() &&
3183 ParamType
->getAs
<PointerType
>()->getPointeeType()->isFunctionType()) ||
3184 // -- For a non-type template-parameter of type reference to
3185 // function, no conversions apply. If the template-argument
3186 // represents a set of overloaded functions, the matching
3187 // function is selected from the set (13.4).
3188 (ParamType
->isReferenceType() &&
3189 ParamType
->getAs
<ReferenceType
>()->getPointeeType()->isFunctionType()) ||
3190 // -- For a non-type template-parameter of type pointer to
3191 // member function, no conversions apply. If the
3192 // template-argument represents a set of overloaded member
3193 // functions, the matching member function is selected from
3195 (ParamType
->isMemberPointerType() &&
3196 ParamType
->getAs
<MemberPointerType
>()->getPointeeType()
3197 ->isFunctionType())) {
3199 if (Arg
->getType() == Context
.OverloadTy
) {
3200 if (FunctionDecl
*Fn
= ResolveAddressOfOverloadedFunction(Arg
, ParamType
,
3203 if (DiagnoseUseOfDecl(Fn
, Arg
->getSourceRange().getBegin()))
3206 Arg
= FixOverloadedFunctionReference(Arg
, FoundResult
, Fn
);
3207 ArgType
= Arg
->getType();
3212 if (!ParamType
->isMemberPointerType())
3213 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param
,
3217 if (IsQualificationConversion(ArgType
, ParamType
.getNonReferenceType())) {
3218 ImpCastExprToType(Arg
, ParamType
, CK_NoOp
, CastCategory(Arg
));
3219 } else if (!Context
.hasSameUnqualifiedType(ArgType
,
3220 ParamType
.getNonReferenceType())) {
3221 // We can't perform this conversion.
3222 Diag(Arg
->getSourceRange().getBegin(),
3223 diag::err_template_arg_not_convertible
)
3224 << Arg
->getType() << InstantiatedParamType
<< Arg
->getSourceRange();
3225 Diag(Param
->getLocation(), diag::note_template_param_here
);
3229 return CheckTemplateArgumentPointerToMember(Arg
, Converted
);
3232 if (ParamType
->isPointerType()) {
3233 // -- for a non-type template-parameter of type pointer to
3234 // object, qualification conversions (4.4) and the
3235 // array-to-pointer conversion (4.2) are applied.
3236 // C++0x also allows a value of std::nullptr_t.
3237 assert(ParamType
->getPointeeType()->isIncompleteOrObjectType() &&
3238 "Only object pointers allowed here");
3240 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param
,
3245 if (const ReferenceType
*ParamRefType
= ParamType
->getAs
<ReferenceType
>()) {
3246 // -- For a non-type template-parameter of type reference to
3247 // object, no conversions apply. The type referred to by the
3248 // reference may be more cv-qualified than the (otherwise
3249 // identical) type of the template-argument. The
3250 // template-parameter is bound directly to the
3251 // template-argument, which must be an lvalue.
3252 assert(ParamRefType
->getPointeeType()->isIncompleteOrObjectType() &&
3253 "Only object references allowed here");
3255 if (Arg
->getType() == Context
.OverloadTy
) {
3256 if (FunctionDecl
*Fn
= ResolveAddressOfOverloadedFunction(Arg
,
3257 ParamRefType
->getPointeeType(),
3260 if (DiagnoseUseOfDecl(Fn
, Arg
->getSourceRange().getBegin()))
3263 Arg
= FixOverloadedFunctionReference(Arg
, FoundResult
, Fn
);
3264 ArgType
= Arg
->getType();
3269 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param
,
3274 // -- For a non-type template-parameter of type pointer to data
3275 // member, qualification conversions (4.4) are applied.
3276 assert(ParamType
->isMemberPointerType() && "Only pointers to members remain");
3278 if (Context
.hasSameUnqualifiedType(ParamType
, ArgType
)) {
3279 // Types match exactly: nothing more to do here.
3280 } else if (IsQualificationConversion(ArgType
, ParamType
)) {
3281 ImpCastExprToType(Arg
, ParamType
, CK_NoOp
, CastCategory(Arg
));
3283 // We can't perform this conversion.
3284 Diag(Arg
->getSourceRange().getBegin(),
3285 diag::err_template_arg_not_convertible
)
3286 << Arg
->getType() << InstantiatedParamType
<< Arg
->getSourceRange();
3287 Diag(Param
->getLocation(), diag::note_template_param_here
);
3291 return CheckTemplateArgumentPointerToMember(Arg
, Converted
);
3294 /// \brief Check a template argument against its corresponding
3295 /// template template parameter.
3297 /// This routine implements the semantics of C++ [temp.arg.template].
3298 /// It returns true if an error occurred, and false otherwise.
3299 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl
*Param
,
3300 const TemplateArgumentLoc
&Arg
) {
3301 TemplateName Name
= Arg
.getArgument().getAsTemplate();
3302 TemplateDecl
*Template
= Name
.getAsTemplateDecl();
3304 // Any dependent template name is fine.
3305 assert(Name
.isDependent() && "Non-dependent template isn't a declaration?");
3309 // C++ [temp.arg.template]p1:
3310 // A template-argument for a template template-parameter shall be
3311 // the name of a class template, expressed as id-expression. Only
3312 // primary class templates are considered when matching the
3313 // template template argument with the corresponding parameter;
3314 // partial specializations are not considered even if their
3315 // parameter lists match that of the template template parameter.
3317 // Note that we also allow template template parameters here, which
3318 // will happen when we are dealing with, e.g., class template
3319 // partial specializations.
3320 if (!isa
<ClassTemplateDecl
>(Template
) &&
3321 !isa
<TemplateTemplateParmDecl
>(Template
)) {
3322 assert(isa
<FunctionTemplateDecl
>(Template
) &&
3323 "Only function templates are possible here");
3324 Diag(Arg
.getLocation(), diag::err_template_arg_not_class_template
);
3325 Diag(Template
->getLocation(), diag::note_template_arg_refers_here_func
)
3329 return !TemplateParameterListsAreEqual(Template
->getTemplateParameters(),
3330 Param
->getTemplateParameters(),
3332 TPL_TemplateTemplateArgumentMatch
,
3336 /// \brief Given a non-type template argument that refers to a
3337 /// declaration and the type of its corresponding non-type template
3338 /// parameter, produce an expression that properly refers to that
3341 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument
&Arg
,
3343 SourceLocation Loc
) {
3344 assert(Arg
.getKind() == TemplateArgument::Declaration
&&
3345 "Only declaration template arguments permitted here");
3346 ValueDecl
*VD
= cast
<ValueDecl
>(Arg
.getAsDecl());
3348 if (VD
->getDeclContext()->isRecord() &&
3349 (isa
<CXXMethodDecl
>(VD
) || isa
<FieldDecl
>(VD
))) {
3350 // If the value is a class member, we might have a pointer-to-member.
3351 // Determine whether the non-type template template parameter is of
3352 // pointer-to-member type. If so, we need to build an appropriate
3353 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3354 // would refer to the member itself.
3355 if (ParamType
->isMemberPointerType()) {
3357 = Context
.getTypeDeclType(cast
<RecordDecl
>(VD
->getDeclContext()));
3358 NestedNameSpecifier
*Qualifier
3359 = NestedNameSpecifier::Create(Context
, 0, false,
3360 ClassType
.getTypePtr());
3362 SS
.setScopeRep(Qualifier
);
3363 ExprResult RefExpr
= BuildDeclRefExpr(VD
,
3364 VD
->getType().getNonReferenceType(),
3367 if (RefExpr
.isInvalid())
3370 RefExpr
= CreateBuiltinUnaryOp(Loc
, UO_AddrOf
, RefExpr
.get());
3372 // We might need to perform a trailing qualification conversion, since
3373 // the element type on the parameter could be more qualified than the
3374 // element type in the expression we constructed.
3375 if (IsQualificationConversion(((Expr
*) RefExpr
.get())->getType(),
3376 ParamType
.getUnqualifiedType())) {
3377 Expr
*RefE
= RefExpr
.takeAs
<Expr
>();
3378 ImpCastExprToType(RefE
, ParamType
.getUnqualifiedType(), CK_NoOp
);
3379 RefExpr
= Owned(RefE
);
3382 assert(!RefExpr
.isInvalid() &&
3383 Context
.hasSameType(((Expr
*) RefExpr
.get())->getType(),
3384 ParamType
.getUnqualifiedType()));
3385 return move(RefExpr
);
3389 QualType T
= VD
->getType().getNonReferenceType();
3390 if (ParamType
->isPointerType()) {
3391 // When the non-type template parameter is a pointer, take the
3392 // address of the declaration.
3393 ExprResult RefExpr
= BuildDeclRefExpr(VD
, T
, Loc
);
3394 if (RefExpr
.isInvalid())
3397 if (T
->isFunctionType() || T
->isArrayType()) {
3398 // Decay functions and arrays.
3399 Expr
*RefE
= (Expr
*)RefExpr
.get();
3400 DefaultFunctionArrayConversion(RefE
);
3401 if (RefE
!= RefExpr
.get()) {
3403 RefExpr
= Owned(RefE
);
3406 return move(RefExpr
);
3409 // Take the address of everything else
3410 return CreateBuiltinUnaryOp(Loc
, UO_AddrOf
, RefExpr
.get());
3413 // If the non-type template parameter has reference type, qualify the
3414 // resulting declaration reference with the extra qualifiers on the
3415 // type that the reference refers to.
3416 if (const ReferenceType
*TargetRef
= ParamType
->getAs
<ReferenceType
>())
3417 T
= Context
.getQualifiedType(T
, TargetRef
->getPointeeType().getQualifiers());
3419 return BuildDeclRefExpr(VD
, T
, Loc
);
3422 /// \brief Construct a new expression that refers to the given
3423 /// integral template argument with the given source-location
3426 /// This routine takes care of the mapping from an integral template
3427 /// argument (which may have any integral type) to the appropriate
3430 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument
&Arg
,
3431 SourceLocation Loc
) {
3432 assert(Arg
.getKind() == TemplateArgument::Integral
&&
3433 "Operation is only value for integral template arguments");
3434 QualType T
= Arg
.getIntegralType();
3435 if (T
->isCharType() || T
->isWideCharType())
3436 return Owned(new (Context
) CharacterLiteral(
3437 Arg
.getAsIntegral()->getZExtValue(),
3438 T
->isWideCharType(),
3441 if (T
->isBooleanType())
3442 return Owned(new (Context
) CXXBoolLiteralExpr(
3443 Arg
.getAsIntegral()->getBoolValue(),
3447 return Owned(IntegerLiteral::Create(Context
, *Arg
.getAsIntegral(), T
, Loc
));
3451 /// \brief Determine whether the given template parameter lists are
3454 /// \param New The new template parameter list, typically written in the
3455 /// source code as part of a new template declaration.
3457 /// \param Old The old template parameter list, typically found via
3458 /// name lookup of the template declared with this template parameter
3461 /// \param Complain If true, this routine will produce a diagnostic if
3462 /// the template parameter lists are not equivalent.
3464 /// \param Kind describes how we are to match the template parameter lists.
3466 /// \param TemplateArgLoc If this source location is valid, then we
3467 /// are actually checking the template parameter list of a template
3468 /// argument (New) against the template parameter list of its
3469 /// corresponding template template parameter (Old). We produce
3470 /// slightly different diagnostics in this scenario.
3472 /// \returns True if the template parameter lists are equal, false
3475 Sema::TemplateParameterListsAreEqual(TemplateParameterList
*New
,
3476 TemplateParameterList
*Old
,
3478 TemplateParameterListEqualKind Kind
,
3479 SourceLocation TemplateArgLoc
) {
3480 if (Old
->size() != New
->size()) {
3482 unsigned NextDiag
= diag::err_template_param_list_different_arity
;
3483 if (TemplateArgLoc
.isValid()) {
3484 Diag(TemplateArgLoc
, diag::err_template_arg_template_params_mismatch
);
3485 NextDiag
= diag::note_template_param_list_different_arity
;
3487 Diag(New
->getTemplateLoc(), NextDiag
)
3488 << (New
->size() > Old
->size())
3489 << (Kind
!= TPL_TemplateMatch
)
3490 << SourceRange(New
->getTemplateLoc(), New
->getRAngleLoc());
3491 Diag(Old
->getTemplateLoc(), diag::note_template_prev_declaration
)
3492 << (Kind
!= TPL_TemplateMatch
)
3493 << SourceRange(Old
->getTemplateLoc(), Old
->getRAngleLoc());
3499 for (TemplateParameterList::iterator OldParm
= Old
->begin(),
3500 OldParmEnd
= Old
->end(), NewParm
= New
->begin();
3501 OldParm
!= OldParmEnd
; ++OldParm
, ++NewParm
) {
3502 if ((*OldParm
)->getKind() != (*NewParm
)->getKind()) {
3504 unsigned NextDiag
= diag::err_template_param_different_kind
;
3505 if (TemplateArgLoc
.isValid()) {
3506 Diag(TemplateArgLoc
, diag::err_template_arg_template_params_mismatch
);
3507 NextDiag
= diag::note_template_param_different_kind
;
3509 Diag((*NewParm
)->getLocation(), NextDiag
)
3510 << (Kind
!= TPL_TemplateMatch
);
3511 Diag((*OldParm
)->getLocation(), diag::note_template_prev_declaration
)
3512 << (Kind
!= TPL_TemplateMatch
);
3517 if (TemplateTypeParmDecl
*OldTTP
3518 = dyn_cast
<TemplateTypeParmDecl
>(*OldParm
)) {
3519 // Template type parameters are equivalent if either both are template
3520 // type parameter packs or neither are (since we know we're at the same
3522 TemplateTypeParmDecl
*NewTTP
= cast
<TemplateTypeParmDecl
>(*NewParm
);
3523 if (OldTTP
->isParameterPack() != NewTTP
->isParameterPack()) {
3524 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3525 // allow one to match a template parameter pack in the template
3526 // parameter list of a template template parameter to one or more
3527 // template parameters in the template parameter list of the
3528 // corresponding template template argument.
3530 unsigned NextDiag
= diag::err_template_parameter_pack_non_pack
;
3531 if (TemplateArgLoc
.isValid()) {
3532 Diag(TemplateArgLoc
,
3533 diag::err_template_arg_template_params_mismatch
);
3534 NextDiag
= diag::note_template_parameter_pack_non_pack
;
3536 Diag(NewTTP
->getLocation(), NextDiag
)
3537 << 0 << NewTTP
->isParameterPack();
3538 Diag(OldTTP
->getLocation(), diag::note_template_parameter_pack_here
)
3539 << 0 << OldTTP
->isParameterPack();
3543 } else if (NonTypeTemplateParmDecl
*OldNTTP
3544 = dyn_cast
<NonTypeTemplateParmDecl
>(*OldParm
)) {
3545 // The types of non-type template parameters must agree.
3546 NonTypeTemplateParmDecl
*NewNTTP
3547 = cast
<NonTypeTemplateParmDecl
>(*NewParm
);
3549 // If we are matching a template template argument to a template
3550 // template parameter and one of the non-type template parameter types
3551 // is dependent, then we must wait until template instantiation time
3552 // to actually compare the arguments.
3553 if (Kind
== TPL_TemplateTemplateArgumentMatch
&&
3554 (OldNTTP
->getType()->isDependentType() ||
3555 NewNTTP
->getType()->isDependentType()))
3558 if (Context
.getCanonicalType(OldNTTP
->getType()) !=
3559 Context
.getCanonicalType(NewNTTP
->getType())) {
3561 unsigned NextDiag
= diag::err_template_nontype_parm_different_type
;
3562 if (TemplateArgLoc
.isValid()) {
3563 Diag(TemplateArgLoc
,
3564 diag::err_template_arg_template_params_mismatch
);
3565 NextDiag
= diag::note_template_nontype_parm_different_type
;
3567 Diag(NewNTTP
->getLocation(), NextDiag
)
3568 << NewNTTP
->getType()
3569 << (Kind
!= TPL_TemplateMatch
);
3570 Diag(OldNTTP
->getLocation(),
3571 diag::note_template_nontype_parm_prev_declaration
)
3572 << OldNTTP
->getType();
3577 // The template parameter lists of template template
3578 // parameters must agree.
3579 assert(isa
<TemplateTemplateParmDecl
>(*OldParm
) &&
3580 "Only template template parameters handled here");
3581 TemplateTemplateParmDecl
*OldTTP
3582 = cast
<TemplateTemplateParmDecl
>(*OldParm
);
3583 TemplateTemplateParmDecl
*NewTTP
3584 = cast
<TemplateTemplateParmDecl
>(*NewParm
);
3585 if (!TemplateParameterListsAreEqual(NewTTP
->getTemplateParameters(),
3586 OldTTP
->getTemplateParameters(),
3588 (Kind
== TPL_TemplateMatch
? TPL_TemplateTemplateParmMatch
: Kind
),
3597 /// \brief Check whether a template can be declared within this scope.
3599 /// If the template declaration is valid in this scope, returns
3600 /// false. Otherwise, issues a diagnostic and returns true.
3602 Sema::CheckTemplateDeclScope(Scope
*S
, TemplateParameterList
*TemplateParams
) {
3603 // Find the nearest enclosing declaration scope.
3604 while ((S
->getFlags() & Scope::DeclScope
) == 0 ||
3605 (S
->getFlags() & Scope::TemplateParamScope
) != 0)
3609 // A template-declaration can appear only as a namespace scope or
3610 // class scope declaration.
3611 DeclContext
*Ctx
= static_cast<DeclContext
*>(S
->getEntity());
3612 if (Ctx
&& isa
<LinkageSpecDecl
>(Ctx
) &&
3613 cast
<LinkageSpecDecl
>(Ctx
)->getLanguage() != LinkageSpecDecl::lang_cxx
)
3614 return Diag(TemplateParams
->getTemplateLoc(), diag::err_template_linkage
)
3615 << TemplateParams
->getSourceRange();
3617 while (Ctx
&& isa
<LinkageSpecDecl
>(Ctx
))
3618 Ctx
= Ctx
->getParent();
3620 if (Ctx
&& (Ctx
->isFileContext() || Ctx
->isRecord()))
3623 return Diag(TemplateParams
->getTemplateLoc(),
3624 diag::err_template_outside_namespace_or_class_scope
)
3625 << TemplateParams
->getSourceRange();
3628 /// \brief Determine what kind of template specialization the given declaration
3630 static TemplateSpecializationKind
getTemplateSpecializationKind(NamedDecl
*D
) {
3632 return TSK_Undeclared
;
3634 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(D
))
3635 return Record
->getTemplateSpecializationKind();
3636 if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(D
))
3637 return Function
->getTemplateSpecializationKind();
3638 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(D
))
3639 return Var
->getTemplateSpecializationKind();
3641 return TSK_Undeclared
;
3644 /// \brief Check whether a specialization is well-formed in the current
3647 /// This routine determines whether a template specialization can be declared
3648 /// in the current context (C++ [temp.expl.spec]p2).
3650 /// \param S the semantic analysis object for which this check is being
3653 /// \param Specialized the entity being specialized or instantiated, which
3654 /// may be a kind of template (class template, function template, etc.) or
3655 /// a member of a class template (member function, static data member,
3658 /// \param PrevDecl the previous declaration of this entity, if any.
3660 /// \param Loc the location of the explicit specialization or instantiation of
3663 /// \param IsPartialSpecialization whether this is a partial specialization of
3664 /// a class template.
3666 /// \returns true if there was an error that we cannot recover from, false
3668 static bool CheckTemplateSpecializationScope(Sema
&S
,
3669 NamedDecl
*Specialized
,
3670 NamedDecl
*PrevDecl
,
3672 bool IsPartialSpecialization
) {
3673 // Keep these "kind" numbers in sync with the %select statements in the
3674 // various diagnostics emitted by this routine.
3676 bool isTemplateSpecialization
= false;
3677 if (isa
<ClassTemplateDecl
>(Specialized
)) {
3678 EntityKind
= IsPartialSpecialization
? 1 : 0;
3679 isTemplateSpecialization
= true;
3680 } else if (isa
<FunctionTemplateDecl
>(Specialized
)) {
3682 isTemplateSpecialization
= true;
3683 } else if (isa
<CXXMethodDecl
>(Specialized
))
3685 else if (isa
<VarDecl
>(Specialized
))
3687 else if (isa
<RecordDecl
>(Specialized
))
3690 S
.Diag(Loc
, diag::err_template_spec_unknown_kind
);
3691 S
.Diag(Specialized
->getLocation(), diag::note_specialized_entity
);
3695 // C++ [temp.expl.spec]p2:
3696 // An explicit specialization shall be declared in the namespace
3697 // of which the template is a member, or, for member templates, in
3698 // the namespace of which the enclosing class or enclosing class
3699 // template is a member. An explicit specialization of a member
3700 // function, member class or static data member of a class
3701 // template shall be declared in the namespace of which the class
3702 // template is a member. Such a declaration may also be a
3703 // definition. If the declaration is not a definition, the
3704 // specialization may be defined later in the name- space in which
3705 // the explicit specialization was declared, or in a namespace
3706 // that encloses the one in which the explicit specialization was
3708 if (S
.CurContext
->getRedeclContext()->isFunctionOrMethod()) {
3709 S
.Diag(Loc
, diag::err_template_spec_decl_function_scope
)
3714 if (S
.CurContext
->isRecord() && !IsPartialSpecialization
) {
3715 S
.Diag(Loc
, diag::err_template_spec_decl_class_scope
)
3720 // C++ [temp.class.spec]p6:
3721 // A class template partial specialization may be declared or redeclared
3722 // in any namespace scope in which its definition may be defined (14.5.1
3724 bool ComplainedAboutScope
= false;
3725 DeclContext
*SpecializedContext
3726 = Specialized
->getDeclContext()->getEnclosingNamespaceContext();
3727 DeclContext
*DC
= S
.CurContext
->getEnclosingNamespaceContext();
3729 getTemplateSpecializationKind(PrevDecl
) == TSK_Undeclared
||
3730 getTemplateSpecializationKind(PrevDecl
) == TSK_ImplicitInstantiation
)){
3731 // C++ [temp.exp.spec]p2:
3732 // An explicit specialization shall be declared in the namespace of which
3733 // the template is a member, or, for member templates, in the namespace
3734 // of which the enclosing class or enclosing class template is a member.
3735 // An explicit specialization of a member function, member class or
3736 // static data member of a class template shall be declared in the
3737 // namespace of which the class template is a member.
3739 // C++0x [temp.expl.spec]p2:
3740 // An explicit specialization shall be declared in a namespace enclosing
3741 // the specialized template.
3742 if (!DC
->InEnclosingNamespaceSetOf(SpecializedContext
) &&
3743 !(S
.getLangOptions().CPlusPlus0x
&& DC
->Encloses(SpecializedContext
))) {
3744 bool IsCPlusPlus0xExtension
3745 = !S
.getLangOptions().CPlusPlus0x
&& DC
->Encloses(SpecializedContext
);
3746 if (isa
<TranslationUnitDecl
>(SpecializedContext
))
3747 S
.Diag(Loc
, IsCPlusPlus0xExtension
3748 ? diag::ext_template_spec_decl_out_of_scope_global
3749 : diag::err_template_spec_decl_out_of_scope_global
)
3750 << EntityKind
<< Specialized
;
3751 else if (isa
<NamespaceDecl
>(SpecializedContext
))
3752 S
.Diag(Loc
, IsCPlusPlus0xExtension
3753 ? diag::ext_template_spec_decl_out_of_scope
3754 : diag::err_template_spec_decl_out_of_scope
)
3755 << EntityKind
<< Specialized
3756 << cast
<NamedDecl
>(SpecializedContext
);
3758 S
.Diag(Specialized
->getLocation(), diag::note_specialized_entity
);
3759 ComplainedAboutScope
= true;
3763 // Make sure that this redeclaration (or definition) occurs in an enclosing
3765 // Note that HandleDeclarator() performs this check for explicit
3766 // specializations of function templates, static data members, and member
3767 // functions, so we skip the check here for those kinds of entities.
3768 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
3769 // Should we refactor that check, so that it occurs later?
3770 if (!ComplainedAboutScope
&& !DC
->Encloses(SpecializedContext
) &&
3771 !(isa
<FunctionTemplateDecl
>(Specialized
) || isa
<VarDecl
>(Specialized
) ||
3772 isa
<FunctionDecl
>(Specialized
))) {
3773 if (isa
<TranslationUnitDecl
>(SpecializedContext
))
3774 S
.Diag(Loc
, diag::err_template_spec_redecl_global_scope
)
3775 << EntityKind
<< Specialized
;
3776 else if (isa
<NamespaceDecl
>(SpecializedContext
))
3777 S
.Diag(Loc
, diag::err_template_spec_redecl_out_of_scope
)
3778 << EntityKind
<< Specialized
3779 << cast
<NamedDecl
>(SpecializedContext
);
3781 S
.Diag(Specialized
->getLocation(), diag::note_specialized_entity
);
3784 // FIXME: check for specialization-after-instantiation errors and such.
3789 /// \brief Check the non-type template arguments of a class template
3790 /// partial specialization according to C++ [temp.class.spec]p9.
3792 /// \param TemplateParams the template parameters of the primary class
3795 /// \param TemplateArg the template arguments of the class template
3796 /// partial specialization.
3798 /// \param MirrorsPrimaryTemplate will be set true if the class
3799 /// template partial specialization arguments are identical to the
3800 /// implicit template arguments of the primary template. This is not
3801 /// necessarily an error (C++0x), and it is left to the caller to diagnose
3802 /// this condition when it is an error.
3804 /// \returns true if there was an error, false otherwise.
3805 bool Sema::CheckClassTemplatePartialSpecializationArgs(
3806 TemplateParameterList
*TemplateParams
,
3807 llvm::SmallVectorImpl
<TemplateArgument
> &TemplateArgs
,
3808 bool &MirrorsPrimaryTemplate
) {
3809 // FIXME: the interface to this function will have to change to
3810 // accommodate variadic templates.
3811 MirrorsPrimaryTemplate
= true;
3813 const TemplateArgument
*ArgList
= TemplateArgs
.data();
3815 for (unsigned I
= 0, N
= TemplateParams
->size(); I
!= N
; ++I
) {
3816 // Determine whether the template argument list of the partial
3817 // specialization is identical to the implicit argument list of
3818 // the primary template. The caller may need to diagnostic this as
3819 // an error per C++ [temp.class.spec]p9b3.
3820 if (MirrorsPrimaryTemplate
) {
3821 if (TemplateTypeParmDecl
*TTP
3822 = dyn_cast
<TemplateTypeParmDecl
>(TemplateParams
->getParam(I
))) {
3823 if (Context
.getCanonicalType(Context
.getTypeDeclType(TTP
)) !=
3824 Context
.getCanonicalType(ArgList
[I
].getAsType()))
3825 MirrorsPrimaryTemplate
= false;
3826 } else if (TemplateTemplateParmDecl
*TTP
3827 = dyn_cast
<TemplateTemplateParmDecl
>(
3828 TemplateParams
->getParam(I
))) {
3829 TemplateName Name
= ArgList
[I
].getAsTemplate();
3830 TemplateTemplateParmDecl
*ArgDecl
3831 = dyn_cast_or_null
<TemplateTemplateParmDecl
>(Name
.getAsTemplateDecl());
3833 ArgDecl
->getIndex() != TTP
->getIndex() ||
3834 ArgDecl
->getDepth() != TTP
->getDepth())
3835 MirrorsPrimaryTemplate
= false;
3839 NonTypeTemplateParmDecl
*Param
3840 = dyn_cast
<NonTypeTemplateParmDecl
>(TemplateParams
->getParam(I
));
3845 Expr
*ArgExpr
= ArgList
[I
].getAsExpr();
3847 MirrorsPrimaryTemplate
= false;
3851 // C++ [temp.class.spec]p8:
3852 // A non-type argument is non-specialized if it is the name of a
3853 // non-type parameter. All other non-type arguments are
3856 // Below, we check the two conditions that only apply to
3857 // specialized non-type arguments, so skip any non-specialized
3859 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(ArgExpr
))
3860 if (NonTypeTemplateParmDecl
*NTTP
3861 = dyn_cast
<NonTypeTemplateParmDecl
>(DRE
->getDecl())) {
3862 if (MirrorsPrimaryTemplate
&&
3863 (Param
->getIndex() != NTTP
->getIndex() ||
3864 Param
->getDepth() != NTTP
->getDepth()))
3865 MirrorsPrimaryTemplate
= false;
3870 // C++ [temp.class.spec]p9:
3871 // Within the argument list of a class template partial
3872 // specialization, the following restrictions apply:
3873 // -- A partially specialized non-type argument expression
3874 // shall not involve a template parameter of the partial
3875 // specialization except when the argument expression is a
3876 // simple identifier.
3877 if (ArgExpr
->isTypeDependent() || ArgExpr
->isValueDependent()) {
3878 Diag(ArgExpr
->getLocStart(),
3879 diag::err_dependent_non_type_arg_in_partial_spec
)
3880 << ArgExpr
->getSourceRange();
3884 // -- The type of a template parameter corresponding to a
3885 // specialized non-type argument shall not be dependent on a
3886 // parameter of the specialization.
3887 if (Param
->getType()->isDependentType()) {
3888 Diag(ArgExpr
->getLocStart(),
3889 diag::err_dependent_typed_non_type_arg_in_partial_spec
)
3891 << ArgExpr
->getSourceRange();
3892 Diag(Param
->getLocation(), diag::note_template_param_here
);
3896 MirrorsPrimaryTemplate
= false;
3902 /// \brief Retrieve the previous declaration of the given declaration.
3903 static NamedDecl
*getPreviousDecl(NamedDecl
*ND
) {
3904 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(ND
))
3905 return VD
->getPreviousDeclaration();
3906 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(ND
))
3907 return FD
->getPreviousDeclaration();
3908 if (TagDecl
*TD
= dyn_cast
<TagDecl
>(ND
))
3909 return TD
->getPreviousDeclaration();
3910 if (TypedefDecl
*TD
= dyn_cast
<TypedefDecl
>(ND
))
3911 return TD
->getPreviousDeclaration();
3912 if (FunctionTemplateDecl
*FTD
= dyn_cast
<FunctionTemplateDecl
>(ND
))
3913 return FTD
->getPreviousDeclaration();
3914 if (ClassTemplateDecl
*CTD
= dyn_cast
<ClassTemplateDecl
>(ND
))
3915 return CTD
->getPreviousDeclaration();
3920 Sema::ActOnClassTemplateSpecialization(Scope
*S
, unsigned TagSpec
,
3922 SourceLocation KWLoc
,
3924 TemplateTy TemplateD
,
3925 SourceLocation TemplateNameLoc
,
3926 SourceLocation LAngleLoc
,
3927 ASTTemplateArgsPtr TemplateArgsIn
,
3928 SourceLocation RAngleLoc
,
3929 AttributeList
*Attr
,
3930 MultiTemplateParamsArg TemplateParameterLists
) {
3931 assert(TUK
!= TUK_Reference
&& "References are not specializations");
3933 // Find the class template we're specializing
3934 TemplateName Name
= TemplateD
.getAsVal
<TemplateName
>();
3935 ClassTemplateDecl
*ClassTemplate
3936 = dyn_cast_or_null
<ClassTemplateDecl
>(Name
.getAsTemplateDecl());
3938 if (!ClassTemplate
) {
3939 Diag(TemplateNameLoc
, diag::err_not_class_template_specialization
)
3940 << (Name
.getAsTemplateDecl() &&
3941 isa
<TemplateTemplateParmDecl
>(Name
.getAsTemplateDecl()));
3945 bool isExplicitSpecialization
= false;
3946 bool isPartialSpecialization
= false;
3948 // Check the validity of the template headers that introduce this
3950 // FIXME: We probably shouldn't complain about these headers for
3951 // friend declarations.
3952 bool Invalid
= false;
3953 TemplateParameterList
*TemplateParams
3954 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc
, SS
,
3955 (TemplateParameterList
**)TemplateParameterLists
.get(),
3956 TemplateParameterLists
.size(),
3958 isExplicitSpecialization
,
3963 unsigned NumMatchedTemplateParamLists
= TemplateParameterLists
.size();
3965 --NumMatchedTemplateParamLists
;
3967 if (TemplateParams
&& TemplateParams
->size() > 0) {
3968 isPartialSpecialization
= true;
3970 // C++ [temp.class.spec]p10:
3971 // The template parameter list of a specialization shall not
3972 // contain default template argument values.
3973 for (unsigned I
= 0, N
= TemplateParams
->size(); I
!= N
; ++I
) {
3974 Decl
*Param
= TemplateParams
->getParam(I
);
3975 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(Param
)) {
3976 if (TTP
->hasDefaultArgument()) {
3977 Diag(TTP
->getDefaultArgumentLoc(),
3978 diag::err_default_arg_in_partial_spec
);
3979 TTP
->removeDefaultArgument();
3981 } else if (NonTypeTemplateParmDecl
*NTTP
3982 = dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
3983 if (Expr
*DefArg
= NTTP
->getDefaultArgument()) {
3984 Diag(NTTP
->getDefaultArgumentLoc(),
3985 diag::err_default_arg_in_partial_spec
)
3986 << DefArg
->getSourceRange();
3987 NTTP
->removeDefaultArgument();
3990 TemplateTemplateParmDecl
*TTP
= cast
<TemplateTemplateParmDecl
>(Param
);
3991 if (TTP
->hasDefaultArgument()) {
3992 Diag(TTP
->getDefaultArgument().getLocation(),
3993 diag::err_default_arg_in_partial_spec
)
3994 << TTP
->getDefaultArgument().getSourceRange();
3995 TTP
->removeDefaultArgument();
3999 } else if (TemplateParams
) {
4000 if (TUK
== TUK_Friend
)
4001 Diag(KWLoc
, diag::err_template_spec_friend
)
4002 << FixItHint::CreateRemoval(
4003 SourceRange(TemplateParams
->getTemplateLoc(),
4004 TemplateParams
->getRAngleLoc()))
4005 << SourceRange(LAngleLoc
, RAngleLoc
);
4007 isExplicitSpecialization
= true;
4008 } else if (TUK
!= TUK_Friend
) {
4009 Diag(KWLoc
, diag::err_template_spec_needs_header
)
4010 << FixItHint::CreateInsertion(KWLoc
, "template<> ");
4011 isExplicitSpecialization
= true;
4014 // Check that the specialization uses the same tag kind as the
4015 // original template.
4016 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
4017 assert(Kind
!= TTK_Enum
&& "Invalid enum tag in class template spec!");
4018 if (!isAcceptableTagRedeclaration(ClassTemplate
->getTemplatedDecl(),
4020 *ClassTemplate
->getIdentifier())) {
4021 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
4023 << FixItHint::CreateReplacement(KWLoc
,
4024 ClassTemplate
->getTemplatedDecl()->getKindName());
4025 Diag(ClassTemplate
->getTemplatedDecl()->getLocation(),
4026 diag::note_previous_use
);
4027 Kind
= ClassTemplate
->getTemplatedDecl()->getTagKind();
4030 // Translate the parser's template argument list in our AST format.
4031 TemplateArgumentListInfo TemplateArgs
;
4032 TemplateArgs
.setLAngleLoc(LAngleLoc
);
4033 TemplateArgs
.setRAngleLoc(RAngleLoc
);
4034 translateTemplateArguments(TemplateArgsIn
, TemplateArgs
);
4036 // Check that the template argument list is well-formed for this
4038 llvm::SmallVector
<TemplateArgument
, 4> Converted
;
4039 if (CheckTemplateArgumentList(ClassTemplate
, TemplateNameLoc
,
4040 TemplateArgs
, false, Converted
))
4043 assert((Converted
.size() == ClassTemplate
->getTemplateParameters()->size()) &&
4044 "Converted template argument list is too short!");
4046 // Find the class template (partial) specialization declaration that
4047 // corresponds to these arguments.
4048 if (isPartialSpecialization
) {
4049 bool MirrorsPrimaryTemplate
;
4050 if (CheckClassTemplatePartialSpecializationArgs(
4051 ClassTemplate
->getTemplateParameters(),
4052 Converted
, MirrorsPrimaryTemplate
))
4055 if (MirrorsPrimaryTemplate
) {
4056 // C++ [temp.class.spec]p9b3:
4058 // -- The argument list of the specialization shall not be identical
4059 // to the implicit argument list of the primary template.
4060 Diag(TemplateNameLoc
, diag::err_partial_spec_args_match_primary_template
)
4061 << (TUK
== TUK_Definition
)
4062 << FixItHint::CreateRemoval(SourceRange(LAngleLoc
, RAngleLoc
));
4063 return CheckClassTemplate(S
, TagSpec
, TUK
, KWLoc
, SS
,
4064 ClassTemplate
->getIdentifier(),
4071 // FIXME: Diagnose friend partial specializations
4073 if (!Name
.isDependent() &&
4074 !TemplateSpecializationType::anyDependentTemplateArguments(
4075 TemplateArgs
.getArgumentArray(),
4076 TemplateArgs
.size())) {
4077 Diag(TemplateNameLoc
, diag::err_partial_spec_fully_specialized
)
4078 << ClassTemplate
->getDeclName();
4079 isPartialSpecialization
= false;
4083 void *InsertPos
= 0;
4084 ClassTemplateSpecializationDecl
*PrevDecl
= 0;
4086 if (isPartialSpecialization
)
4087 // FIXME: Template parameter list matters, too
4089 = ClassTemplate
->findPartialSpecialization(Converted
.data(),
4094 = ClassTemplate
->findSpecialization(Converted
.data(),
4095 Converted
.size(), InsertPos
);
4097 ClassTemplateSpecializationDecl
*Specialization
= 0;
4099 // Check whether we can declare a class template specialization in
4100 // the current scope.
4101 if (TUK
!= TUK_Friend
&&
4102 CheckTemplateSpecializationScope(*this, ClassTemplate
, PrevDecl
,
4104 isPartialSpecialization
))
4107 // The canonical type
4110 (PrevDecl
->getSpecializationKind() == TSK_Undeclared
||
4111 TUK
== TUK_Friend
)) {
4112 // Since the only prior class template specialization with these
4113 // arguments was referenced but not declared, or we're only
4114 // referencing this specialization as a friend, reuse that
4115 // declaration node as our own, updating its source location to
4116 // reflect our new declaration.
4117 Specialization
= PrevDecl
;
4118 Specialization
->setLocation(TemplateNameLoc
);
4120 CanonType
= Context
.getTypeDeclType(Specialization
);
4121 } else if (isPartialSpecialization
) {
4122 // Build the canonical type that describes the converted template
4123 // arguments of the class template partial specialization.
4124 TemplateName CanonTemplate
= Context
.getCanonicalTemplateName(Name
);
4125 CanonType
= Context
.getTemplateSpecializationType(CanonTemplate
,
4129 // Create a new class template partial specialization declaration node.
4130 ClassTemplatePartialSpecializationDecl
*PrevPartial
4131 = cast_or_null
<ClassTemplatePartialSpecializationDecl
>(PrevDecl
);
4132 unsigned SequenceNumber
= PrevPartial
? PrevPartial
->getSequenceNumber()
4133 : ClassTemplate
->getNextPartialSpecSequenceNumber();
4134 ClassTemplatePartialSpecializationDecl
*Partial
4135 = ClassTemplatePartialSpecializationDecl::Create(Context
, Kind
,
4136 ClassTemplate
->getDeclContext(),
4146 SetNestedNameSpecifier(Partial
, SS
);
4147 if (NumMatchedTemplateParamLists
> 0 && SS
.isSet()) {
4148 Partial
->setTemplateParameterListsInfo(Context
,
4149 NumMatchedTemplateParamLists
,
4150 (TemplateParameterList
**) TemplateParameterLists
.release());
4154 ClassTemplate
->AddPartialSpecialization(Partial
, InsertPos
);
4155 Specialization
= Partial
;
4157 // If we are providing an explicit specialization of a member class
4158 // template specialization, make a note of that.
4159 if (PrevPartial
&& PrevPartial
->getInstantiatedFromMember())
4160 PrevPartial
->setMemberSpecialization();
4162 // Check that all of the template parameters of the class template
4163 // partial specialization are deducible from the template
4164 // arguments. If not, this class template partial specialization
4165 // will never be used.
4166 llvm::SmallVector
<bool, 8> DeducibleParams
;
4167 DeducibleParams
.resize(TemplateParams
->size());
4168 MarkUsedTemplateParameters(Partial
->getTemplateArgs(), true,
4169 TemplateParams
->getDepth(),
4171 unsigned NumNonDeducible
= 0;
4172 for (unsigned I
= 0, N
= DeducibleParams
.size(); I
!= N
; ++I
)
4173 if (!DeducibleParams
[I
])
4176 if (NumNonDeducible
) {
4177 Diag(TemplateNameLoc
, diag::warn_partial_specs_not_deducible
)
4178 << (NumNonDeducible
> 1)
4179 << SourceRange(TemplateNameLoc
, RAngleLoc
);
4180 for (unsigned I
= 0, N
= DeducibleParams
.size(); I
!= N
; ++I
) {
4181 if (!DeducibleParams
[I
]) {
4182 NamedDecl
*Param
= cast
<NamedDecl
>(TemplateParams
->getParam(I
));
4183 if (Param
->getDeclName())
4184 Diag(Param
->getLocation(),
4185 diag::note_partial_spec_unused_parameter
)
4186 << Param
->getDeclName();
4188 Diag(Param
->getLocation(),
4189 diag::note_partial_spec_unused_parameter
)
4195 // Create a new class template specialization declaration node for
4196 // this explicit specialization or friend declaration.
4198 = ClassTemplateSpecializationDecl::Create(Context
, Kind
,
4199 ClassTemplate
->getDeclContext(),
4205 SetNestedNameSpecifier(Specialization
, SS
);
4206 if (NumMatchedTemplateParamLists
> 0 && SS
.isSet()) {
4207 Specialization
->setTemplateParameterListsInfo(Context
,
4208 NumMatchedTemplateParamLists
,
4209 (TemplateParameterList
**) TemplateParameterLists
.release());
4213 ClassTemplate
->AddSpecialization(Specialization
, InsertPos
);
4215 CanonType
= Context
.getTypeDeclType(Specialization
);
4218 // C++ [temp.expl.spec]p6:
4219 // If a template, a member template or the member of a class template is
4220 // explicitly specialized then that specialization shall be declared
4221 // before the first use of that specialization that would cause an implicit
4222 // instantiation to take place, in every translation unit in which such a
4223 // use occurs; no diagnostic is required.
4224 if (PrevDecl
&& PrevDecl
->getPointOfInstantiation().isValid()) {
4226 for (NamedDecl
*Prev
= PrevDecl
; Prev
; Prev
= getPreviousDecl(Prev
)) {
4227 // Is there any previous explicit specialization declaration?
4228 if (getTemplateSpecializationKind(Prev
) == TSK_ExplicitSpecialization
) {
4235 SourceRange
Range(TemplateNameLoc
, RAngleLoc
);
4236 Diag(TemplateNameLoc
, diag::err_specialization_after_instantiation
)
4237 << Context
.getTypeDeclType(Specialization
) << Range
;
4239 Diag(PrevDecl
->getPointOfInstantiation(),
4240 diag::note_instantiation_required_here
)
4241 << (PrevDecl
->getTemplateSpecializationKind()
4242 != TSK_ImplicitInstantiation
);
4247 // If this is not a friend, note that this is an explicit specialization.
4248 if (TUK
!= TUK_Friend
)
4249 Specialization
->setSpecializationKind(TSK_ExplicitSpecialization
);
4251 // Check that this isn't a redefinition of this specialization.
4252 if (TUK
== TUK_Definition
) {
4253 if (RecordDecl
*Def
= Specialization
->getDefinition()) {
4254 SourceRange
Range(TemplateNameLoc
, RAngleLoc
);
4255 Diag(TemplateNameLoc
, diag::err_redefinition
)
4256 << Context
.getTypeDeclType(Specialization
) << Range
;
4257 Diag(Def
->getLocation(), diag::note_previous_definition
);
4258 Specialization
->setInvalidDecl();
4263 // Build the fully-sugared type for this class template
4264 // specialization as the user wrote in the specialization
4265 // itself. This means that we'll pretty-print the type retrieved
4266 // from the specialization's declaration the way that the user
4267 // actually wrote the specialization, rather than formatting the
4268 // name based on the "canonical" representation used to store the
4269 // template arguments in the specialization.
4270 TypeSourceInfo
*WrittenTy
4271 = Context
.getTemplateSpecializationTypeInfo(Name
, TemplateNameLoc
,
4272 TemplateArgs
, CanonType
);
4273 if (TUK
!= TUK_Friend
) {
4274 Specialization
->setTypeAsWritten(WrittenTy
);
4276 Specialization
->setTemplateKeywordLoc(TemplateParams
->getTemplateLoc());
4278 TemplateArgsIn
.release();
4280 // C++ [temp.expl.spec]p9:
4281 // A template explicit specialization is in the scope of the
4282 // namespace in which the template was defined.
4284 // We actually implement this paragraph where we set the semantic
4285 // context (in the creation of the ClassTemplateSpecializationDecl),
4286 // but we also maintain the lexical context where the actual
4287 // definition occurs.
4288 Specialization
->setLexicalDeclContext(CurContext
);
4290 // We may be starting the definition of this specialization.
4291 if (TUK
== TUK_Definition
)
4292 Specialization
->startDefinition();
4294 if (TUK
== TUK_Friend
) {
4295 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
,
4299 Friend
->setAccess(AS_public
);
4300 CurContext
->addDecl(Friend
);
4302 // Add the specialization into its lexical context, so that it can
4303 // be seen when iterating through the list of declarations in that
4304 // context. However, specializations are not found by name lookup.
4305 CurContext
->addDecl(Specialization
);
4307 return Specialization
;
4310 Decl
*Sema::ActOnTemplateDeclarator(Scope
*S
,
4311 MultiTemplateParamsArg TemplateParameterLists
,
4313 return HandleDeclarator(S
, D
, move(TemplateParameterLists
), false);
4316 Decl
*Sema::ActOnStartOfFunctionTemplateDef(Scope
*FnBodyScope
,
4317 MultiTemplateParamsArg TemplateParameterLists
,
4319 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4320 assert(D
.getTypeObject(0).Kind
== DeclaratorChunk::Function
&&
4321 "Not a function declarator!");
4322 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getTypeObject(0).Fun
;
4324 if (FTI
.hasPrototype
) {
4325 // FIXME: Diagnose arguments without names in C.
4328 Scope
*ParentScope
= FnBodyScope
->getParent();
4330 Decl
*DP
= HandleDeclarator(ParentScope
, D
,
4331 move(TemplateParameterLists
),
4332 /*IsFunctionDefinition=*/true);
4333 if (FunctionTemplateDecl
*FunctionTemplate
4334 = dyn_cast_or_null
<FunctionTemplateDecl
>(DP
))
4335 return ActOnStartOfFunctionDef(FnBodyScope
,
4336 FunctionTemplate
->getTemplatedDecl());
4337 if (FunctionDecl
*Function
= dyn_cast_or_null
<FunctionDecl
>(DP
))
4338 return ActOnStartOfFunctionDef(FnBodyScope
, Function
);
4342 /// \brief Strips various properties off an implicit instantiation
4343 /// that has just been explicitly specialized.
4344 static void StripImplicitInstantiation(NamedDecl
*D
) {
4347 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
4348 FD
->setInlineSpecified(false);
4352 /// \brief Diagnose cases where we have an explicit template specialization
4353 /// before/after an explicit template instantiation, producing diagnostics
4354 /// for those cases where they are required and determining whether the
4355 /// new specialization/instantiation will have any effect.
4357 /// \param NewLoc the location of the new explicit specialization or
4360 /// \param NewTSK the kind of the new explicit specialization or instantiation.
4362 /// \param PrevDecl the previous declaration of the entity.
4364 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4366 /// \param PrevPointOfInstantiation if valid, indicates where the previus
4367 /// declaration was instantiated (either implicitly or explicitly).
4369 /// \param HasNoEffect will be set to true to indicate that the new
4370 /// specialization or instantiation has no effect and should be ignored.
4372 /// \returns true if there was an error that should prevent the introduction of
4373 /// the new declaration into the AST, false otherwise.
4375 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc
,
4376 TemplateSpecializationKind NewTSK
,
4377 NamedDecl
*PrevDecl
,
4378 TemplateSpecializationKind PrevTSK
,
4379 SourceLocation PrevPointOfInstantiation
,
4380 bool &HasNoEffect
) {
4381 HasNoEffect
= false;
4384 case TSK_Undeclared
:
4385 case TSK_ImplicitInstantiation
:
4386 assert(false && "Don't check implicit instantiations here");
4389 case TSK_ExplicitSpecialization
:
4391 case TSK_Undeclared
:
4392 case TSK_ExplicitSpecialization
:
4393 // Okay, we're just specializing something that is either already
4394 // explicitly specialized or has merely been mentioned without any
4398 case TSK_ImplicitInstantiation
:
4399 if (PrevPointOfInstantiation
.isInvalid()) {
4400 // The declaration itself has not actually been instantiated, so it is
4401 // still okay to specialize it.
4402 StripImplicitInstantiation(PrevDecl
);
4407 case TSK_ExplicitInstantiationDeclaration
:
4408 case TSK_ExplicitInstantiationDefinition
:
4409 assert((PrevTSK
== TSK_ImplicitInstantiation
||
4410 PrevPointOfInstantiation
.isValid()) &&
4411 "Explicit instantiation without point of instantiation?");
4413 // C++ [temp.expl.spec]p6:
4414 // If a template, a member template or the member of a class template
4415 // is explicitly specialized then that specialization shall be declared
4416 // before the first use of that specialization that would cause an
4417 // implicit instantiation to take place, in every translation unit in
4418 // which such a use occurs; no diagnostic is required.
4419 for (NamedDecl
*Prev
= PrevDecl
; Prev
; Prev
= getPreviousDecl(Prev
)) {
4420 // Is there any previous explicit specialization declaration?
4421 if (getTemplateSpecializationKind(Prev
) == TSK_ExplicitSpecialization
)
4425 Diag(NewLoc
, diag::err_specialization_after_instantiation
)
4427 Diag(PrevPointOfInstantiation
, diag::note_instantiation_required_here
)
4428 << (PrevTSK
!= TSK_ImplicitInstantiation
);
4434 case TSK_ExplicitInstantiationDeclaration
:
4436 case TSK_ExplicitInstantiationDeclaration
:
4437 // This explicit instantiation declaration is redundant (that's okay).
4441 case TSK_Undeclared
:
4442 case TSK_ImplicitInstantiation
:
4443 // We're explicitly instantiating something that may have already been
4444 // implicitly instantiated; that's fine.
4447 case TSK_ExplicitSpecialization
:
4448 // C++0x [temp.explicit]p4:
4449 // For a given set of template parameters, if an explicit instantiation
4450 // of a template appears after a declaration of an explicit
4451 // specialization for that template, the explicit instantiation has no
4456 case TSK_ExplicitInstantiationDefinition
:
4457 // C++0x [temp.explicit]p10:
4458 // If an entity is the subject of both an explicit instantiation
4459 // declaration and an explicit instantiation definition in the same
4460 // translation unit, the definition shall follow the declaration.
4462 diag::err_explicit_instantiation_declaration_after_definition
);
4463 Diag(PrevPointOfInstantiation
,
4464 diag::note_explicit_instantiation_definition_here
);
4465 assert(PrevPointOfInstantiation
.isValid() &&
4466 "Explicit instantiation without point of instantiation?");
4472 case TSK_ExplicitInstantiationDefinition
:
4474 case TSK_Undeclared
:
4475 case TSK_ImplicitInstantiation
:
4476 // We're explicitly instantiating something that may have already been
4477 // implicitly instantiated; that's fine.
4480 case TSK_ExplicitSpecialization
:
4481 // C++ DR 259, C++0x [temp.explicit]p4:
4482 // For a given set of template parameters, if an explicit
4483 // instantiation of a template appears after a declaration of
4484 // an explicit specialization for that template, the explicit
4485 // instantiation has no effect.
4487 // In C++98/03 mode, we only give an extension warning here, because it
4488 // is not harmful to try to explicitly instantiate something that
4489 // has been explicitly specialized.
4490 if (!getLangOptions().CPlusPlus0x
) {
4491 Diag(NewLoc
, diag::ext_explicit_instantiation_after_specialization
)
4493 Diag(PrevDecl
->getLocation(),
4494 diag::note_previous_template_specialization
);
4499 case TSK_ExplicitInstantiationDeclaration
:
4500 // We're explicity instantiating a definition for something for which we
4501 // were previously asked to suppress instantiations. That's fine.
4504 case TSK_ExplicitInstantiationDefinition
:
4505 // C++0x [temp.spec]p5:
4506 // For a given template and a given set of template-arguments,
4507 // - an explicit instantiation definition shall appear at most once
4509 Diag(NewLoc
, diag::err_explicit_instantiation_duplicate
)
4511 Diag(PrevPointOfInstantiation
,
4512 diag::note_previous_explicit_instantiation
);
4519 assert(false && "Missing specialization/instantiation case?");
4524 /// \brief Perform semantic analysis for the given dependent function
4525 /// template specialization. The only possible way to get a dependent
4526 /// function template specialization is with a friend declaration,
4529 /// template <class T> void foo(T);
4530 /// template <class T> class A {
4531 /// friend void foo<>(T);
4534 /// There really isn't any useful analysis we can do here, so we
4535 /// just store the information.
4537 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl
*FD
,
4538 const TemplateArgumentListInfo
&ExplicitTemplateArgs
,
4539 LookupResult
&Previous
) {
4540 // Remove anything from Previous that isn't a function template in
4541 // the correct context.
4542 DeclContext
*FDLookupContext
= FD
->getDeclContext()->getRedeclContext();
4543 LookupResult::Filter F
= Previous
.makeFilter();
4544 while (F
.hasNext()) {
4545 NamedDecl
*D
= F
.next()->getUnderlyingDecl();
4546 if (!isa
<FunctionTemplateDecl
>(D
) ||
4547 !FDLookupContext
->InEnclosingNamespaceSetOf(
4548 D
->getDeclContext()->getRedeclContext()))
4553 // Should this be diagnosed here?
4554 if (Previous
.empty()) return true;
4556 FD
->setDependentTemplateSpecialization(Context
, Previous
.asUnresolvedSet(),
4557 ExplicitTemplateArgs
);
4561 /// \brief Perform semantic analysis for the given function template
4564 /// This routine performs all of the semantic analysis required for an
4565 /// explicit function template specialization. On successful completion,
4566 /// the function declaration \p FD will become a function template
4569 /// \param FD the function declaration, which will be updated to become a
4570 /// function template specialization.
4572 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4573 /// if any. Note that this may be valid info even when 0 arguments are
4574 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4575 /// as it anyway contains info on the angle brackets locations.
4577 /// \param PrevDecl the set of declarations that may be specialized by
4578 /// this function specialization.
4580 Sema::CheckFunctionTemplateSpecialization(FunctionDecl
*FD
,
4581 const TemplateArgumentListInfo
*ExplicitTemplateArgs
,
4582 LookupResult
&Previous
) {
4583 // The set of function template specializations that could match this
4584 // explicit function template specialization.
4585 UnresolvedSet
<8> Candidates
;
4587 DeclContext
*FDLookupContext
= FD
->getDeclContext()->getRedeclContext();
4588 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
4590 NamedDecl
*Ovl
= (*I
)->getUnderlyingDecl();
4591 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(Ovl
)) {
4592 // Only consider templates found within the same semantic lookup scope as
4594 if (!FDLookupContext
->InEnclosingNamespaceSetOf(
4595 Ovl
->getDeclContext()->getRedeclContext()))
4598 // C++ [temp.expl.spec]p11:
4599 // A trailing template-argument can be left unspecified in the
4600 // template-id naming an explicit function template specialization
4601 // provided it can be deduced from the function argument type.
4602 // Perform template argument deduction to determine whether we may be
4603 // specializing this template.
4604 // FIXME: It is somewhat wasteful to build
4605 TemplateDeductionInfo
Info(Context
, FD
->getLocation());
4606 FunctionDecl
*Specialization
= 0;
4607 if (TemplateDeductionResult TDK
4608 = DeduceTemplateArguments(FunTmpl
, ExplicitTemplateArgs
,
4612 // FIXME: Template argument deduction failed; record why it failed, so
4613 // that we can provide nifty diagnostics.
4618 // Record this candidate.
4619 Candidates
.addDecl(Specialization
, I
.getAccess());
4623 // Find the most specialized function template.
4624 UnresolvedSetIterator Result
4625 = getMostSpecialized(Candidates
.begin(), Candidates
.end(),
4626 TPOC_Other
, FD
->getLocation(),
4627 PDiag(diag::err_function_template_spec_no_match
)
4628 << FD
->getDeclName(),
4629 PDiag(diag::err_function_template_spec_ambiguous
)
4630 << FD
->getDeclName() << (ExplicitTemplateArgs
!= 0),
4631 PDiag(diag::note_function_template_spec_matched
));
4632 if (Result
== Candidates
.end())
4635 // Ignore access information; it doesn't figure into redeclaration checking.
4636 FunctionDecl
*Specialization
= cast
<FunctionDecl
>(*Result
);
4637 Specialization
->setLocation(FD
->getLocation());
4639 // FIXME: Check if the prior specialization has a point of instantiation.
4640 // If so, we have run afoul of .
4642 // If this is a friend declaration, then we're not really declaring
4643 // an explicit specialization.
4644 bool isFriend
= (FD
->getFriendObjectKind() != Decl::FOK_None
);
4646 // Check the scope of this explicit specialization.
4648 CheckTemplateSpecializationScope(*this,
4649 Specialization
->getPrimaryTemplate(),
4650 Specialization
, FD
->getLocation(),
4654 // C++ [temp.expl.spec]p6:
4655 // If a template, a member template or the member of a class template is
4656 // explicitly specialized then that specialization shall be declared
4657 // before the first use of that specialization that would cause an implicit
4658 // instantiation to take place, in every translation unit in which such a
4659 // use occurs; no diagnostic is required.
4660 FunctionTemplateSpecializationInfo
*SpecInfo
4661 = Specialization
->getTemplateSpecializationInfo();
4662 assert(SpecInfo
&& "Function template specialization info missing?");
4664 bool HasNoEffect
= false;
4666 CheckSpecializationInstantiationRedecl(FD
->getLocation(),
4667 TSK_ExplicitSpecialization
,
4669 SpecInfo
->getTemplateSpecializationKind(),
4670 SpecInfo
->getPointOfInstantiation(),
4674 // Mark the prior declaration as an explicit specialization, so that later
4675 // clients know that this is an explicit specialization.
4677 SpecInfo
->setTemplateSpecializationKind(TSK_ExplicitSpecialization
);
4678 MarkUnusedFileScopedDecl(Specialization
);
4681 // Turn the given function declaration into a function template
4682 // specialization, with the template arguments from the previous
4684 // Take copies of (semantic and syntactic) template argument lists.
4685 const TemplateArgumentList
* TemplArgs
= new (Context
)
4686 TemplateArgumentList(Specialization
->getTemplateSpecializationArgs());
4687 const TemplateArgumentListInfo
* TemplArgsAsWritten
= ExplicitTemplateArgs
4688 ? new (Context
) TemplateArgumentListInfo(*ExplicitTemplateArgs
) : 0;
4689 FD
->setFunctionTemplateSpecialization(Specialization
->getPrimaryTemplate(),
4690 TemplArgs
, /*InsertPos=*/0,
4691 SpecInfo
->getTemplateSpecializationKind(),
4692 TemplArgsAsWritten
);
4694 // The "previous declaration" for this function template specialization is
4695 // the prior function template specialization.
4697 Previous
.addDecl(Specialization
);
4701 /// \brief Perform semantic analysis for the given non-template member
4704 /// This routine performs all of the semantic analysis required for an
4705 /// explicit member function specialization. On successful completion,
4706 /// the function declaration \p FD will become a member function
4709 /// \param Member the member declaration, which will be updated to become a
4712 /// \param Previous the set of declarations, one of which may be specialized
4713 /// by this function specialization; the set will be modified to contain the
4714 /// redeclared member.
4716 Sema::CheckMemberSpecialization(NamedDecl
*Member
, LookupResult
&Previous
) {
4717 assert(!isa
<TemplateDecl
>(Member
) && "Only for non-template members");
4719 // Try to find the member we are instantiating.
4720 NamedDecl
*Instantiation
= 0;
4721 NamedDecl
*InstantiatedFrom
= 0;
4722 MemberSpecializationInfo
*MSInfo
= 0;
4724 if (Previous
.empty()) {
4725 // Nowhere to look anyway.
4726 } else if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(Member
)) {
4727 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
4729 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
4730 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
)) {
4731 if (Context
.hasSameType(Function
->getType(), Method
->getType())) {
4732 Instantiation
= Method
;
4733 InstantiatedFrom
= Method
->getInstantiatedFromMemberFunction();
4734 MSInfo
= Method
->getMemberSpecializationInfo();
4739 } else if (isa
<VarDecl
>(Member
)) {
4741 if (Previous
.isSingleResult() &&
4742 (PrevVar
= dyn_cast
<VarDecl
>(Previous
.getFoundDecl())))
4743 if (PrevVar
->isStaticDataMember()) {
4744 Instantiation
= PrevVar
;
4745 InstantiatedFrom
= PrevVar
->getInstantiatedFromStaticDataMember();
4746 MSInfo
= PrevVar
->getMemberSpecializationInfo();
4748 } else if (isa
<RecordDecl
>(Member
)) {
4749 CXXRecordDecl
*PrevRecord
;
4750 if (Previous
.isSingleResult() &&
4751 (PrevRecord
= dyn_cast
<CXXRecordDecl
>(Previous
.getFoundDecl()))) {
4752 Instantiation
= PrevRecord
;
4753 InstantiatedFrom
= PrevRecord
->getInstantiatedFromMemberClass();
4754 MSInfo
= PrevRecord
->getMemberSpecializationInfo();
4758 if (!Instantiation
) {
4759 // There is no previous declaration that matches. Since member
4760 // specializations are always out-of-line, the caller will complain about
4761 // this mismatch later.
4765 // If this is a friend, just bail out here before we start turning
4766 // things into explicit specializations.
4767 if (Member
->getFriendObjectKind() != Decl::FOK_None
) {
4768 // Preserve instantiation information.
4769 if (InstantiatedFrom
&& isa
<CXXMethodDecl
>(Member
)) {
4770 cast
<CXXMethodDecl
>(Member
)->setInstantiationOfMemberFunction(
4771 cast
<CXXMethodDecl
>(InstantiatedFrom
),
4772 cast
<CXXMethodDecl
>(Instantiation
)->getTemplateSpecializationKind());
4773 } else if (InstantiatedFrom
&& isa
<CXXRecordDecl
>(Member
)) {
4774 cast
<CXXRecordDecl
>(Member
)->setInstantiationOfMemberClass(
4775 cast
<CXXRecordDecl
>(InstantiatedFrom
),
4776 cast
<CXXRecordDecl
>(Instantiation
)->getTemplateSpecializationKind());
4780 Previous
.addDecl(Instantiation
);
4784 // Make sure that this is a specialization of a member.
4785 if (!InstantiatedFrom
) {
4786 Diag(Member
->getLocation(), diag::err_spec_member_not_instantiated
)
4788 Diag(Instantiation
->getLocation(), diag::note_specialized_decl
);
4792 // C++ [temp.expl.spec]p6:
4793 // If a template, a member template or the member of a class template is
4794 // explicitly specialized then that spe- cialization shall be declared
4795 // before the first use of that specialization that would cause an implicit
4796 // instantiation to take place, in every translation unit in which such a
4797 // use occurs; no diagnostic is required.
4798 assert(MSInfo
&& "Member specialization info missing?");
4800 bool HasNoEffect
= false;
4801 if (CheckSpecializationInstantiationRedecl(Member
->getLocation(),
4802 TSK_ExplicitSpecialization
,
4804 MSInfo
->getTemplateSpecializationKind(),
4805 MSInfo
->getPointOfInstantiation(),
4809 // Check the scope of this explicit specialization.
4810 if (CheckTemplateSpecializationScope(*this,
4812 Instantiation
, Member
->getLocation(),
4816 // Note that this is an explicit instantiation of a member.
4817 // the original declaration to note that it is an explicit specialization
4818 // (if it was previously an implicit instantiation). This latter step
4819 // makes bookkeeping easier.
4820 if (isa
<FunctionDecl
>(Member
)) {
4821 FunctionDecl
*InstantiationFunction
= cast
<FunctionDecl
>(Instantiation
);
4822 if (InstantiationFunction
->getTemplateSpecializationKind() ==
4823 TSK_ImplicitInstantiation
) {
4824 InstantiationFunction
->setTemplateSpecializationKind(
4825 TSK_ExplicitSpecialization
);
4826 InstantiationFunction
->setLocation(Member
->getLocation());
4829 cast
<FunctionDecl
>(Member
)->setInstantiationOfMemberFunction(
4830 cast
<CXXMethodDecl
>(InstantiatedFrom
),
4831 TSK_ExplicitSpecialization
);
4832 MarkUnusedFileScopedDecl(InstantiationFunction
);
4833 } else if (isa
<VarDecl
>(Member
)) {
4834 VarDecl
*InstantiationVar
= cast
<VarDecl
>(Instantiation
);
4835 if (InstantiationVar
->getTemplateSpecializationKind() ==
4836 TSK_ImplicitInstantiation
) {
4837 InstantiationVar
->setTemplateSpecializationKind(
4838 TSK_ExplicitSpecialization
);
4839 InstantiationVar
->setLocation(Member
->getLocation());
4842 Context
.setInstantiatedFromStaticDataMember(cast
<VarDecl
>(Member
),
4843 cast
<VarDecl
>(InstantiatedFrom
),
4844 TSK_ExplicitSpecialization
);
4845 MarkUnusedFileScopedDecl(InstantiationVar
);
4847 assert(isa
<CXXRecordDecl
>(Member
) && "Only member classes remain");
4848 CXXRecordDecl
*InstantiationClass
= cast
<CXXRecordDecl
>(Instantiation
);
4849 if (InstantiationClass
->getTemplateSpecializationKind() ==
4850 TSK_ImplicitInstantiation
) {
4851 InstantiationClass
->setTemplateSpecializationKind(
4852 TSK_ExplicitSpecialization
);
4853 InstantiationClass
->setLocation(Member
->getLocation());
4856 cast
<CXXRecordDecl
>(Member
)->setInstantiationOfMemberClass(
4857 cast
<CXXRecordDecl
>(InstantiatedFrom
),
4858 TSK_ExplicitSpecialization
);
4861 // Save the caller the trouble of having to figure out which declaration
4862 // this specialization matches.
4864 Previous
.addDecl(Instantiation
);
4868 /// \brief Check the scope of an explicit instantiation.
4870 /// \returns true if a serious error occurs, false otherwise.
4871 static bool CheckExplicitInstantiationScope(Sema
&S
, NamedDecl
*D
,
4872 SourceLocation InstLoc
,
4873 bool WasQualifiedName
) {
4874 DeclContext
*OrigContext
= D
->getDeclContext()->getEnclosingNamespaceContext();
4875 DeclContext
*CurContext
= S
.CurContext
->getRedeclContext();
4877 if (CurContext
->isRecord()) {
4878 S
.Diag(InstLoc
, diag::err_explicit_instantiation_in_class
)
4883 // C++0x [temp.explicit]p2:
4884 // An explicit instantiation shall appear in an enclosing namespace of its
4887 // This is DR275, which we do not retroactively apply to C++98/03.
4888 if (S
.getLangOptions().CPlusPlus0x
&&
4889 !CurContext
->Encloses(OrigContext
)) {
4890 if (NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(OrigContext
))
4892 S
.getLangOptions().CPlusPlus0x
?
4893 diag::err_explicit_instantiation_out_of_scope
4894 : diag::warn_explicit_instantiation_out_of_scope_0x
)
4898 S
.getLangOptions().CPlusPlus0x
?
4899 diag::err_explicit_instantiation_must_be_global
4900 : diag::warn_explicit_instantiation_out_of_scope_0x
)
4902 S
.Diag(D
->getLocation(), diag::note_explicit_instantiation_here
);
4906 // C++0x [temp.explicit]p2:
4907 // If the name declared in the explicit instantiation is an unqualified
4908 // name, the explicit instantiation shall appear in the namespace where
4909 // its template is declared or, if that namespace is inline (7.3.1), any
4910 // namespace from its enclosing namespace set.
4911 if (WasQualifiedName
)
4914 if (CurContext
->InEnclosingNamespaceSetOf(OrigContext
))
4918 S
.getLangOptions().CPlusPlus0x
?
4919 diag::err_explicit_instantiation_unqualified_wrong_namespace
4920 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x
)
4921 << D
<< OrigContext
;
4922 S
.Diag(D
->getLocation(), diag::note_explicit_instantiation_here
);
4926 /// \brief Determine whether the given scope specifier has a template-id in it.
4927 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec
&SS
) {
4931 // C++0x [temp.explicit]p2:
4932 // If the explicit instantiation is for a member function, a member class
4933 // or a static data member of a class template specialization, the name of
4934 // the class template specialization in the qualified-id for the member
4935 // name shall be a simple-template-id.
4937 // C++98 has the same restriction, just worded differently.
4938 for (NestedNameSpecifier
*NNS
= (NestedNameSpecifier
*)SS
.getScopeRep();
4939 NNS
; NNS
= NNS
->getPrefix())
4940 if (Type
*T
= NNS
->getAsType())
4941 if (isa
<TemplateSpecializationType
>(T
))
4947 // Explicit instantiation of a class template specialization
4949 Sema::ActOnExplicitInstantiation(Scope
*S
,
4950 SourceLocation ExternLoc
,
4951 SourceLocation TemplateLoc
,
4953 SourceLocation KWLoc
,
4954 const CXXScopeSpec
&SS
,
4955 TemplateTy TemplateD
,
4956 SourceLocation TemplateNameLoc
,
4957 SourceLocation LAngleLoc
,
4958 ASTTemplateArgsPtr TemplateArgsIn
,
4959 SourceLocation RAngleLoc
,
4960 AttributeList
*Attr
) {
4961 // Find the class template we're specializing
4962 TemplateName Name
= TemplateD
.getAsVal
<TemplateName
>();
4963 ClassTemplateDecl
*ClassTemplate
4964 = cast
<ClassTemplateDecl
>(Name
.getAsTemplateDecl());
4966 // Check that the specialization uses the same tag kind as the
4967 // original template.
4968 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
4969 assert(Kind
!= TTK_Enum
&&
4970 "Invalid enum tag in class template explicit instantiation!");
4971 if (!isAcceptableTagRedeclaration(ClassTemplate
->getTemplatedDecl(),
4973 *ClassTemplate
->getIdentifier())) {
4974 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
4976 << FixItHint::CreateReplacement(KWLoc
,
4977 ClassTemplate
->getTemplatedDecl()->getKindName());
4978 Diag(ClassTemplate
->getTemplatedDecl()->getLocation(),
4979 diag::note_previous_use
);
4980 Kind
= ClassTemplate
->getTemplatedDecl()->getTagKind();
4983 // C++0x [temp.explicit]p2:
4984 // There are two forms of explicit instantiation: an explicit instantiation
4985 // definition and an explicit instantiation declaration. An explicit
4986 // instantiation declaration begins with the extern keyword. [...]
4987 TemplateSpecializationKind TSK
4988 = ExternLoc
.isInvalid()? TSK_ExplicitInstantiationDefinition
4989 : TSK_ExplicitInstantiationDeclaration
;
4991 // Translate the parser's template argument list in our AST format.
4992 TemplateArgumentListInfo
TemplateArgs(LAngleLoc
, RAngleLoc
);
4993 translateTemplateArguments(TemplateArgsIn
, TemplateArgs
);
4995 // Check that the template argument list is well-formed for this
4997 llvm::SmallVector
<TemplateArgument
, 4> Converted
;
4998 if (CheckTemplateArgumentList(ClassTemplate
, TemplateNameLoc
,
4999 TemplateArgs
, false, Converted
))
5002 assert((Converted
.size() == ClassTemplate
->getTemplateParameters()->size()) &&
5003 "Converted template argument list is too short!");
5005 // Find the class template specialization declaration that
5006 // corresponds to these arguments.
5007 void *InsertPos
= 0;
5008 ClassTemplateSpecializationDecl
*PrevDecl
5009 = ClassTemplate
->findSpecialization(Converted
.data(),
5010 Converted
.size(), InsertPos
);
5012 TemplateSpecializationKind PrevDecl_TSK
5013 = PrevDecl
? PrevDecl
->getTemplateSpecializationKind() : TSK_Undeclared
;
5015 // C++0x [temp.explicit]p2:
5016 // [...] An explicit instantiation shall appear in an enclosing
5017 // namespace of its template. [...]
5019 // This is C++ DR 275.
5020 if (CheckExplicitInstantiationScope(*this, ClassTemplate
, TemplateNameLoc
,
5024 ClassTemplateSpecializationDecl
*Specialization
= 0;
5026 bool ReusedDecl
= false;
5027 bool HasNoEffect
= false;
5029 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc
, TSK
,
5030 PrevDecl
, PrevDecl_TSK
,
5031 PrevDecl
->getPointOfInstantiation(),
5035 // Even though HasNoEffect == true means that this explicit instantiation
5036 // has no effect on semantics, we go on to put its syntax in the AST.
5038 if (PrevDecl_TSK
== TSK_ImplicitInstantiation
||
5039 PrevDecl_TSK
== TSK_Undeclared
) {
5040 // Since the only prior class template specialization with these
5041 // arguments was referenced but not declared, reuse that
5042 // declaration node as our own, updating the source location
5043 // for the template name to reflect our new declaration.
5044 // (Other source locations will be updated later.)
5045 Specialization
= PrevDecl
;
5046 Specialization
->setLocation(TemplateNameLoc
);
5052 if (!Specialization
) {
5053 // Create a new class template specialization declaration node for
5054 // this explicit specialization.
5056 = ClassTemplateSpecializationDecl::Create(Context
, Kind
,
5057 ClassTemplate
->getDeclContext(),
5063 SetNestedNameSpecifier(Specialization
, SS
);
5065 if (!HasNoEffect
&& !PrevDecl
) {
5066 // Insert the new specialization.
5067 ClassTemplate
->AddSpecialization(Specialization
, InsertPos
);
5071 // Build the fully-sugared type for this explicit instantiation as
5072 // the user wrote in the explicit instantiation itself. This means
5073 // that we'll pretty-print the type retrieved from the
5074 // specialization's declaration the way that the user actually wrote
5075 // the explicit instantiation, rather than formatting the name based
5076 // on the "canonical" representation used to store the template
5077 // arguments in the specialization.
5078 TypeSourceInfo
*WrittenTy
5079 = Context
.getTemplateSpecializationTypeInfo(Name
, TemplateNameLoc
,
5081 Context
.getTypeDeclType(Specialization
));
5082 Specialization
->setTypeAsWritten(WrittenTy
);
5083 TemplateArgsIn
.release();
5085 // Set source locations for keywords.
5086 Specialization
->setExternLoc(ExternLoc
);
5087 Specialization
->setTemplateKeywordLoc(TemplateLoc
);
5089 // Add the explicit instantiation into its lexical context. However,
5090 // since explicit instantiations are never found by name lookup, we
5091 // just put it into the declaration context directly.
5092 Specialization
->setLexicalDeclContext(CurContext
);
5093 CurContext
->addDecl(Specialization
);
5095 // Syntax is now OK, so return if it has no other effect on semantics.
5097 // Set the template specialization kind.
5098 Specialization
->setTemplateSpecializationKind(TSK
);
5099 return Specialization
;
5102 // C++ [temp.explicit]p3:
5103 // A definition of a class template or class member template
5104 // shall be in scope at the point of the explicit instantiation of
5105 // the class template or class member template.
5107 // This check comes when we actually try to perform the
5109 ClassTemplateSpecializationDecl
*Def
5110 = cast_or_null
<ClassTemplateSpecializationDecl
>(
5111 Specialization
->getDefinition());
5113 InstantiateClassTemplateSpecialization(TemplateNameLoc
, Specialization
, TSK
);
5114 else if (TSK
== TSK_ExplicitInstantiationDefinition
) {
5115 MarkVTableUsed(TemplateNameLoc
, Specialization
, true);
5116 Specialization
->setPointOfInstantiation(Def
->getPointOfInstantiation());
5119 // Instantiate the members of this class template specialization.
5120 Def
= cast_or_null
<ClassTemplateSpecializationDecl
>(
5121 Specialization
->getDefinition());
5123 TemplateSpecializationKind Old_TSK
= Def
->getTemplateSpecializationKind();
5125 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5126 // TSK_ExplicitInstantiationDefinition
5127 if (Old_TSK
== TSK_ExplicitInstantiationDeclaration
&&
5128 TSK
== TSK_ExplicitInstantiationDefinition
)
5129 Def
->setTemplateSpecializationKind(TSK
);
5131 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc
, Def
, TSK
);
5134 // Set the template specialization kind.
5135 Specialization
->setTemplateSpecializationKind(TSK
);
5136 return Specialization
;
5139 // Explicit instantiation of a member class of a class template.
5141 Sema::ActOnExplicitInstantiation(Scope
*S
,
5142 SourceLocation ExternLoc
,
5143 SourceLocation TemplateLoc
,
5145 SourceLocation KWLoc
,
5147 IdentifierInfo
*Name
,
5148 SourceLocation NameLoc
,
5149 AttributeList
*Attr
) {
5152 bool IsDependent
= false;
5153 Decl
*TagD
= ActOnTag(S
, TagSpec
, Sema::TUK_Reference
,
5154 KWLoc
, SS
, Name
, NameLoc
, Attr
, AS_none
,
5155 MultiTemplateParamsArg(*this, 0, 0),
5156 Owned
, IsDependent
, false,
5158 assert(!IsDependent
&& "explicit instantiation of dependent name not yet handled");
5163 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
5164 if (Tag
->isEnum()) {
5165 Diag(TemplateLoc
, diag::err_explicit_instantiation_enum
)
5166 << Context
.getTypeDeclType(Tag
);
5170 if (Tag
->isInvalidDecl())
5173 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(Tag
);
5174 CXXRecordDecl
*Pattern
= Record
->getInstantiatedFromMemberClass();
5176 Diag(TemplateLoc
, diag::err_explicit_instantiation_nontemplate_type
)
5177 << Context
.getTypeDeclType(Record
);
5178 Diag(Record
->getLocation(), diag::note_nontemplate_decl_here
);
5182 // C++0x [temp.explicit]p2:
5183 // If the explicit instantiation is for a class or member class, the
5184 // elaborated-type-specifier in the declaration shall include a
5185 // simple-template-id.
5187 // C++98 has the same restriction, just worded differently.
5188 if (!ScopeSpecifierHasTemplateId(SS
))
5189 Diag(TemplateLoc
, diag::ext_explicit_instantiation_without_qualified_id
)
5190 << Record
<< SS
.getRange();
5192 // C++0x [temp.explicit]p2:
5193 // There are two forms of explicit instantiation: an explicit instantiation
5194 // definition and an explicit instantiation declaration. An explicit
5195 // instantiation declaration begins with the extern keyword. [...]
5196 TemplateSpecializationKind TSK
5197 = ExternLoc
.isInvalid()? TSK_ExplicitInstantiationDefinition
5198 : TSK_ExplicitInstantiationDeclaration
;
5200 // C++0x [temp.explicit]p2:
5201 // [...] An explicit instantiation shall appear in an enclosing
5202 // namespace of its template. [...]
5204 // This is C++ DR 275.
5205 CheckExplicitInstantiationScope(*this, Record
, NameLoc
, true);
5207 // Verify that it is okay to explicitly instantiate here.
5208 CXXRecordDecl
*PrevDecl
5209 = cast_or_null
<CXXRecordDecl
>(Record
->getPreviousDeclaration());
5210 if (!PrevDecl
&& Record
->getDefinition())
5213 MemberSpecializationInfo
*MSInfo
= PrevDecl
->getMemberSpecializationInfo();
5214 bool HasNoEffect
= false;
5215 assert(MSInfo
&& "No member specialization information?");
5216 if (CheckSpecializationInstantiationRedecl(TemplateLoc
, TSK
,
5218 MSInfo
->getTemplateSpecializationKind(),
5219 MSInfo
->getPointOfInstantiation(),
5226 CXXRecordDecl
*RecordDef
5227 = cast_or_null
<CXXRecordDecl
>(Record
->getDefinition());
5229 // C++ [temp.explicit]p3:
5230 // A definition of a member class of a class template shall be in scope
5231 // at the point of an explicit instantiation of the member class.
5233 = cast_or_null
<CXXRecordDecl
>(Pattern
->getDefinition());
5235 Diag(TemplateLoc
, diag::err_explicit_instantiation_undefined_member
)
5236 << 0 << Record
->getDeclName() << Record
->getDeclContext();
5237 Diag(Pattern
->getLocation(), diag::note_forward_declaration
)
5241 if (InstantiateClass(NameLoc
, Record
, Def
,
5242 getTemplateInstantiationArgs(Record
),
5246 RecordDef
= cast_or_null
<CXXRecordDecl
>(Record
->getDefinition());
5252 // Instantiate all of the members of the class.
5253 InstantiateClassMembers(NameLoc
, RecordDef
,
5254 getTemplateInstantiationArgs(Record
), TSK
);
5256 if (TSK
== TSK_ExplicitInstantiationDefinition
)
5257 MarkVTableUsed(NameLoc
, RecordDef
, true);
5259 // FIXME: We don't have any representation for explicit instantiations of
5260 // member classes. Such a representation is not needed for compilation, but it
5261 // should be available for clients that want to see all of the declarations in
5266 DeclResult
Sema::ActOnExplicitInstantiation(Scope
*S
,
5267 SourceLocation ExternLoc
,
5268 SourceLocation TemplateLoc
,
5270 // Explicit instantiations always require a name.
5271 // TODO: check if/when DNInfo should replace Name.
5272 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
5273 DeclarationName Name
= NameInfo
.getName();
5275 if (!D
.isInvalidType())
5276 Diag(D
.getDeclSpec().getSourceRange().getBegin(),
5277 diag::err_explicit_instantiation_requires_name
)
5278 << D
.getDeclSpec().getSourceRange()
5279 << D
.getSourceRange();
5284 // The scope passed in may not be a decl scope. Zip up the scope tree until
5285 // we find one that is.
5286 while ((S
->getFlags() & Scope::DeclScope
) == 0 ||
5287 (S
->getFlags() & Scope::TemplateParamScope
) != 0)
5290 // Determine the type of the declaration.
5291 TypeSourceInfo
*T
= GetTypeForDeclarator(D
, S
);
5292 QualType R
= T
->getType();
5296 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
) {
5297 // Cannot explicitly instantiate a typedef.
5298 Diag(D
.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef
)
5303 // C++0x [temp.explicit]p1:
5304 // [...] An explicit instantiation of a function template shall not use the
5305 // inline or constexpr specifiers.
5306 // Presumably, this also applies to member functions of class templates as
5308 if (D
.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x
)
5309 Diag(D
.getDeclSpec().getInlineSpecLoc(),
5310 diag::err_explicit_instantiation_inline
)
5311 <<FixItHint::CreateRemoval(D
.getDeclSpec().getInlineSpecLoc());
5313 // FIXME: check for constexpr specifier.
5315 // C++0x [temp.explicit]p2:
5316 // There are two forms of explicit instantiation: an explicit instantiation
5317 // definition and an explicit instantiation declaration. An explicit
5318 // instantiation declaration begins with the extern keyword. [...]
5319 TemplateSpecializationKind TSK
5320 = ExternLoc
.isInvalid()? TSK_ExplicitInstantiationDefinition
5321 : TSK_ExplicitInstantiationDeclaration
;
5323 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
);
5324 LookupParsedName(Previous
, S
, &D
.getCXXScopeSpec());
5326 if (!R
->isFunctionType()) {
5327 // C++ [temp.explicit]p1:
5328 // A [...] static data member of a class template can be explicitly
5329 // instantiated from the member definition associated with its class
5331 if (Previous
.isAmbiguous())
5334 VarDecl
*Prev
= Previous
.getAsSingle
<VarDecl
>();
5335 if (!Prev
|| !Prev
->isStaticDataMember()) {
5336 // We expect to see a data data member here.
5337 Diag(D
.getIdentifierLoc(), diag::err_explicit_instantiation_not_known
)
5339 for (LookupResult::iterator P
= Previous
.begin(), PEnd
= Previous
.end();
5341 Diag((*P
)->getLocation(), diag::note_explicit_instantiation_here
);
5345 if (!Prev
->getInstantiatedFromStaticDataMember()) {
5346 // FIXME: Check for explicit specialization?
5347 Diag(D
.getIdentifierLoc(),
5348 diag::err_explicit_instantiation_data_member_not_instantiated
)
5350 Diag(Prev
->getLocation(), diag::note_explicit_instantiation_here
);
5351 // FIXME: Can we provide a note showing where this was declared?
5355 // C++0x [temp.explicit]p2:
5356 // If the explicit instantiation is for a member function, a member class
5357 // or a static data member of a class template specialization, the name of
5358 // the class template specialization in the qualified-id for the member
5359 // name shall be a simple-template-id.
5361 // C++98 has the same restriction, just worded differently.
5362 if (!ScopeSpecifierHasTemplateId(D
.getCXXScopeSpec()))
5363 Diag(D
.getIdentifierLoc(),
5364 diag::ext_explicit_instantiation_without_qualified_id
)
5365 << Prev
<< D
.getCXXScopeSpec().getRange();
5367 // Check the scope of this explicit instantiation.
5368 CheckExplicitInstantiationScope(*this, Prev
, D
.getIdentifierLoc(), true);
5370 // Verify that it is okay to explicitly instantiate here.
5371 MemberSpecializationInfo
*MSInfo
= Prev
->getMemberSpecializationInfo();
5372 assert(MSInfo
&& "Missing static data member specialization info?");
5373 bool HasNoEffect
= false;
5374 if (CheckSpecializationInstantiationRedecl(D
.getIdentifierLoc(), TSK
, Prev
,
5375 MSInfo
->getTemplateSpecializationKind(),
5376 MSInfo
->getPointOfInstantiation(),
5382 // Instantiate static data member.
5383 Prev
->setTemplateSpecializationKind(TSK
, D
.getIdentifierLoc());
5384 if (TSK
== TSK_ExplicitInstantiationDefinition
)
5385 InstantiateStaticDataMemberDefinition(D
.getIdentifierLoc(), Prev
);
5387 // FIXME: Create an ExplicitInstantiation node?
5391 // If the declarator is a template-id, translate the parser's template
5392 // argument list into our AST format.
5393 bool HasExplicitTemplateArgs
= false;
5394 TemplateArgumentListInfo TemplateArgs
;
5395 if (D
.getName().getKind() == UnqualifiedId::IK_TemplateId
) {
5396 TemplateIdAnnotation
*TemplateId
= D
.getName().TemplateId
;
5397 TemplateArgs
.setLAngleLoc(TemplateId
->LAngleLoc
);
5398 TemplateArgs
.setRAngleLoc(TemplateId
->RAngleLoc
);
5399 ASTTemplateArgsPtr
TemplateArgsPtr(*this,
5400 TemplateId
->getTemplateArgs(),
5401 TemplateId
->NumArgs
);
5402 translateTemplateArguments(TemplateArgsPtr
, TemplateArgs
);
5403 HasExplicitTemplateArgs
= true;
5404 TemplateArgsPtr
.release();
5407 // C++ [temp.explicit]p1:
5408 // A [...] function [...] can be explicitly instantiated from its template.
5409 // A member function [...] of a class template can be explicitly
5410 // instantiated from the member definition associated with its class
5412 UnresolvedSet
<8> Matches
;
5413 for (LookupResult::iterator P
= Previous
.begin(), PEnd
= Previous
.end();
5415 NamedDecl
*Prev
= *P
;
5416 if (!HasExplicitTemplateArgs
) {
5417 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Prev
)) {
5418 if (Context
.hasSameUnqualifiedType(Method
->getType(), R
)) {
5421 Matches
.addDecl(Method
, P
.getAccess());
5422 if (Method
->getTemplateSpecializationKind() == TSK_Undeclared
)
5428 FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(Prev
);
5432 TemplateDeductionInfo
Info(Context
, D
.getIdentifierLoc());
5433 FunctionDecl
*Specialization
= 0;
5434 if (TemplateDeductionResult TDK
5435 = DeduceTemplateArguments(FunTmpl
,
5436 (HasExplicitTemplateArgs
? &TemplateArgs
: 0),
5437 R
, Specialization
, Info
)) {
5438 // FIXME: Keep track of almost-matches?
5443 Matches
.addDecl(Specialization
, P
.getAccess());
5446 // Find the most specialized function template specialization.
5447 UnresolvedSetIterator Result
5448 = getMostSpecialized(Matches
.begin(), Matches
.end(), TPOC_Other
,
5449 D
.getIdentifierLoc(),
5450 PDiag(diag::err_explicit_instantiation_not_known
) << Name
,
5451 PDiag(diag::err_explicit_instantiation_ambiguous
) << Name
,
5452 PDiag(diag::note_explicit_instantiation_candidate
));
5454 if (Result
== Matches
.end())
5457 // Ignore access control bits, we don't need them for redeclaration checking.
5458 FunctionDecl
*Specialization
= cast
<FunctionDecl
>(*Result
);
5460 if (Specialization
->getTemplateSpecializationKind() == TSK_Undeclared
) {
5461 Diag(D
.getIdentifierLoc(),
5462 diag::err_explicit_instantiation_member_function_not_instantiated
)
5464 << (Specialization
->getTemplateSpecializationKind() ==
5465 TSK_ExplicitSpecialization
);
5466 Diag(Specialization
->getLocation(), diag::note_explicit_instantiation_here
);
5470 FunctionDecl
*PrevDecl
= Specialization
->getPreviousDeclaration();
5471 if (!PrevDecl
&& Specialization
->isThisDeclarationADefinition())
5472 PrevDecl
= Specialization
;
5475 bool HasNoEffect
= false;
5476 if (CheckSpecializationInstantiationRedecl(D
.getIdentifierLoc(), TSK
,
5478 PrevDecl
->getTemplateSpecializationKind(),
5479 PrevDecl
->getPointOfInstantiation(),
5483 // FIXME: We may still want to build some representation of this
5484 // explicit specialization.
5489 Specialization
->setTemplateSpecializationKind(TSK
, D
.getIdentifierLoc());
5491 if (TSK
== TSK_ExplicitInstantiationDefinition
)
5492 InstantiateFunctionDefinition(D
.getIdentifierLoc(), Specialization
);
5494 // C++0x [temp.explicit]p2:
5495 // If the explicit instantiation is for a member function, a member class
5496 // or a static data member of a class template specialization, the name of
5497 // the class template specialization in the qualified-id for the member
5498 // name shall be a simple-template-id.
5500 // C++98 has the same restriction, just worded differently.
5501 FunctionTemplateDecl
*FunTmpl
= Specialization
->getPrimaryTemplate();
5502 if (D
.getName().getKind() != UnqualifiedId::IK_TemplateId
&& !FunTmpl
&&
5503 D
.getCXXScopeSpec().isSet() &&
5504 !ScopeSpecifierHasTemplateId(D
.getCXXScopeSpec()))
5505 Diag(D
.getIdentifierLoc(),
5506 diag::ext_explicit_instantiation_without_qualified_id
)
5507 << Specialization
<< D
.getCXXScopeSpec().getRange();
5509 CheckExplicitInstantiationScope(*this,
5510 FunTmpl
? (NamedDecl
*)FunTmpl
5511 : Specialization
->getInstantiatedFromMemberFunction(),
5512 D
.getIdentifierLoc(),
5513 D
.getCXXScopeSpec().isSet());
5515 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5520 Sema::ActOnDependentTag(Scope
*S
, unsigned TagSpec
, TagUseKind TUK
,
5521 const CXXScopeSpec
&SS
, IdentifierInfo
*Name
,
5522 SourceLocation TagLoc
, SourceLocation NameLoc
) {
5523 // This has to hold, because SS is expected to be defined.
5524 assert(Name
&& "Expected a name in a dependent tag");
5526 NestedNameSpecifier
*NNS
5527 = static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
5531 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
5533 if (TUK
== TUK_Declaration
|| TUK
== TUK_Definition
) {
5534 Diag(NameLoc
, diag::err_dependent_tag_decl
)
5535 << (TUK
== TUK_Definition
) << Kind
<< SS
.getRange();
5539 ElaboratedTypeKeyword Kwd
= TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
5540 return ParsedType::make(Context
.getDependentNameType(Kwd
, NNS
, Name
));
5544 Sema::ActOnTypenameType(Scope
*S
, SourceLocation TypenameLoc
,
5545 const CXXScopeSpec
&SS
, const IdentifierInfo
&II
,
5546 SourceLocation IdLoc
) {
5547 NestedNameSpecifier
*NNS
5548 = static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
5552 if (TypenameLoc
.isValid() && S
&& !S
->getTemplateParamParent() &&
5553 !getLangOptions().CPlusPlus0x
)
5554 Diag(TypenameLoc
, diag::ext_typename_outside_of_template
)
5555 << FixItHint::CreateRemoval(TypenameLoc
);
5557 QualType T
= CheckTypenameType(ETK_Typename
, NNS
, II
,
5558 TypenameLoc
, SS
.getRange(), IdLoc
);
5562 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
5563 if (isa
<DependentNameType
>(T
)) {
5564 DependentNameTypeLoc TL
= cast
<DependentNameTypeLoc
>(TSI
->getTypeLoc());
5565 TL
.setKeywordLoc(TypenameLoc
);
5566 TL
.setQualifierRange(SS
.getRange());
5567 TL
.setNameLoc(IdLoc
);
5569 ElaboratedTypeLoc TL
= cast
<ElaboratedTypeLoc
>(TSI
->getTypeLoc());
5570 TL
.setKeywordLoc(TypenameLoc
);
5571 TL
.setQualifierRange(SS
.getRange());
5572 cast
<TypeSpecTypeLoc
>(TL
.getNamedTypeLoc()).setNameLoc(IdLoc
);
5575 return CreateParsedType(T
, TSI
);
5579 Sema::ActOnTypenameType(Scope
*S
, SourceLocation TypenameLoc
,
5580 const CXXScopeSpec
&SS
, SourceLocation TemplateLoc
,
5582 if (TypenameLoc
.isValid() && S
&& !S
->getTemplateParamParent() &&
5583 !getLangOptions().CPlusPlus0x
)
5584 Diag(TypenameLoc
, diag::ext_typename_outside_of_template
)
5585 << FixItHint::CreateRemoval(TypenameLoc
);
5587 TypeSourceInfo
*InnerTSI
= 0;
5588 QualType T
= GetTypeFromParser(Ty
, &InnerTSI
);
5590 assert(isa
<TemplateSpecializationType
>(T
) &&
5591 "Expected a template specialization type");
5593 if (computeDeclContext(SS
, false)) {
5594 // If we can compute a declaration context, then the "typename"
5595 // keyword was superfluous. Just build an ElaboratedType to keep
5596 // track of the nested-name-specifier.
5598 // Push the inner type, preserving its source locations if possible.
5599 TypeLocBuilder Builder
;
5601 Builder
.pushFullCopy(InnerTSI
->getTypeLoc());
5603 Builder
.push
<TemplateSpecializationTypeLoc
>(T
).initialize(TemplateLoc
);
5605 /* Note: NNS already embedded in template specialization type T. */
5606 T
= Context
.getElaboratedType(ETK_Typename
, /*NNS=*/0, T
);
5607 ElaboratedTypeLoc TL
= Builder
.push
<ElaboratedTypeLoc
>(T
);
5608 TL
.setKeywordLoc(TypenameLoc
);
5609 TL
.setQualifierRange(SS
.getRange());
5611 TypeSourceInfo
*TSI
= Builder
.getTypeSourceInfo(Context
, T
);
5612 return CreateParsedType(T
, TSI
);
5615 // TODO: it's really silly that we make a template specialization
5616 // type earlier only to drop it again here.
5617 TemplateSpecializationType
*TST
= cast
<TemplateSpecializationType
>(T
);
5618 DependentTemplateName
*DTN
=
5619 TST
->getTemplateName().getAsDependentTemplateName();
5620 assert(DTN
&& "dependent template has non-dependent name?");
5621 assert(DTN
->getQualifier()
5622 == static_cast<NestedNameSpecifier
*>(SS
.getScopeRep()));
5623 T
= Context
.getDependentTemplateSpecializationType(ETK_Typename
,
5624 DTN
->getQualifier(),
5625 DTN
->getIdentifier(),
5628 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
5629 DependentTemplateSpecializationTypeLoc TL
=
5630 cast
<DependentTemplateSpecializationTypeLoc
>(TSI
->getTypeLoc());
5632 TemplateSpecializationTypeLoc TSTL
=
5633 cast
<TemplateSpecializationTypeLoc
>(InnerTSI
->getTypeLoc());
5634 TL
.setLAngleLoc(TSTL
.getLAngleLoc());
5635 TL
.setRAngleLoc(TSTL
.getRAngleLoc());
5636 for (unsigned I
= 0, E
= TST
->getNumArgs(); I
!= E
; ++I
)
5637 TL
.setArgLocInfo(I
, TSTL
.getArgLocInfo(I
));
5639 TL
.initializeLocal(SourceLocation());
5641 TL
.setKeywordLoc(TypenameLoc
);
5642 TL
.setQualifierRange(SS
.getRange());
5643 return CreateParsedType(T
, TSI
);
5646 /// \brief Build the type that describes a C++ typename specifier,
5647 /// e.g., "typename T::type".
5649 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword
,
5650 NestedNameSpecifier
*NNS
, const IdentifierInfo
&II
,
5651 SourceLocation KeywordLoc
, SourceRange NNSRange
,
5652 SourceLocation IILoc
) {
5654 SS
.setScopeRep(NNS
);
5655 SS
.setRange(NNSRange
);
5657 DeclContext
*Ctx
= computeDeclContext(SS
);
5659 // If the nested-name-specifier is dependent and couldn't be
5660 // resolved to a type, build a typename type.
5661 assert(NNS
->isDependent());
5662 return Context
.getDependentNameType(Keyword
, NNS
, &II
);
5665 // If the nested-name-specifier refers to the current instantiation,
5666 // the "typename" keyword itself is superfluous. In C++03, the
5667 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5668 // allows such extraneous "typename" keywords, and we retroactively
5669 // apply this DR to C++03 code with only a warning. In any case we continue.
5671 if (RequireCompleteDeclContext(SS
, Ctx
))
5674 DeclarationName
Name(&II
);
5675 LookupResult
Result(*this, Name
, IILoc
, LookupOrdinaryName
);
5676 LookupQualifiedName(Result
, Ctx
);
5677 unsigned DiagID
= 0;
5678 Decl
*Referenced
= 0;
5679 switch (Result
.getResultKind()) {
5680 case LookupResult::NotFound
:
5681 DiagID
= diag::err_typename_nested_not_found
;
5684 case LookupResult::NotFoundInCurrentInstantiation
:
5685 // Okay, it's a member of an unknown instantiation.
5686 return Context
.getDependentNameType(Keyword
, NNS
, &II
);
5688 case LookupResult::Found
:
5689 if (TypeDecl
*Type
= dyn_cast
<TypeDecl
>(Result
.getFoundDecl())) {
5690 // We found a type. Build an ElaboratedType, since the
5691 // typename-specifier was just sugar.
5692 return Context
.getElaboratedType(ETK_Typename
, NNS
,
5693 Context
.getTypeDeclType(Type
));
5696 DiagID
= diag::err_typename_nested_not_type
;
5697 Referenced
= Result
.getFoundDecl();
5700 case LookupResult::FoundUnresolvedValue
:
5701 llvm_unreachable("unresolved using decl in non-dependent context");
5704 case LookupResult::FoundOverloaded
:
5705 DiagID
= diag::err_typename_nested_not_type
;
5706 Referenced
= *Result
.begin();
5709 case LookupResult::Ambiguous
:
5713 // If we get here, it's because name lookup did not find a
5714 // type. Emit an appropriate diagnostic and return an error.
5715 SourceRange
FullRange(KeywordLoc
.isValid() ? KeywordLoc
: NNSRange
.getBegin(),
5717 Diag(IILoc
, DiagID
) << FullRange
<< Name
<< Ctx
;
5719 Diag(Referenced
->getLocation(), diag::note_typename_refers_here
)
5725 // See Sema::RebuildTypeInCurrentInstantiation
5726 class CurrentInstantiationRebuilder
5727 : public TreeTransform
<CurrentInstantiationRebuilder
> {
5729 DeclarationName Entity
;
5732 typedef TreeTransform
<CurrentInstantiationRebuilder
> inherited
;
5734 CurrentInstantiationRebuilder(Sema
&SemaRef
,
5736 DeclarationName Entity
)
5737 : TreeTransform
<CurrentInstantiationRebuilder
>(SemaRef
),
5738 Loc(Loc
), Entity(Entity
) { }
5740 /// \brief Determine whether the given type \p T has already been
5743 /// For the purposes of type reconstruction, a type has already been
5744 /// transformed if it is NULL or if it is not dependent.
5745 bool AlreadyTransformed(QualType T
) {
5746 return T
.isNull() || !T
->isDependentType();
5749 /// \brief Returns the location of the entity whose type is being
5751 SourceLocation
getBaseLocation() { return Loc
; }
5753 /// \brief Returns the name of the entity whose type is being rebuilt.
5754 DeclarationName
getBaseEntity() { return Entity
; }
5756 /// \brief Sets the "base" location and entity when that
5757 /// information is known based on another transformation.
5758 void setBase(SourceLocation Loc
, DeclarationName Entity
) {
5760 this->Entity
= Entity
;
5765 /// \brief Rebuilds a type within the context of the current instantiation.
5767 /// The type \p T is part of the type of an out-of-line member definition of
5768 /// a class template (or class template partial specialization) that was parsed
5769 /// and constructed before we entered the scope of the class template (or
5770 /// partial specialization thereof). This routine will rebuild that type now
5771 /// that we have entered the declarator's scope, which may produce different
5772 /// canonical types, e.g.,
5775 /// template<typename T>
5777 /// typedef T* pointer;
5781 /// template<typename T>
5782 /// typename X<T>::pointer X<T>::data() { ... }
5785 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
5786 /// since we do not know that we can look into X<T> when we parsed the type.
5787 /// This function will rebuild the type, performing the lookup of "pointer"
5788 /// in X<T> and returning an ElaboratedType whose canonical type is the same
5789 /// as the canonical type of T*, allowing the return types of the out-of-line
5790 /// definition and the declaration to match.
5791 TypeSourceInfo
*Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo
*T
,
5793 DeclarationName Name
) {
5794 if (!T
|| !T
->getType()->isDependentType())
5797 CurrentInstantiationRebuilder
Rebuilder(*this, Loc
, Name
);
5798 return Rebuilder
.TransformType(T
);
5801 ExprResult
Sema::RebuildExprInCurrentInstantiation(Expr
*E
) {
5802 CurrentInstantiationRebuilder
Rebuilder(*this, E
->getExprLoc(),
5804 return Rebuilder
.TransformExpr(E
);
5807 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec
&SS
) {
5808 if (SS
.isInvalid()) return true;
5810 NestedNameSpecifier
*NNS
= static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
5811 CurrentInstantiationRebuilder
Rebuilder(*this, SS
.getRange().getBegin(),
5813 NestedNameSpecifier
*Rebuilt
=
5814 Rebuilder
.TransformNestedNameSpecifier(NNS
, SS
.getRange());
5815 if (!Rebuilt
) return true;
5817 SS
.setScopeRep(Rebuilt
);
5821 /// \brief Produces a formatted string that describes the binding of
5822 /// template parameters to template arguments.
5824 Sema::getTemplateArgumentBindingsText(const TemplateParameterList
*Params
,
5825 const TemplateArgumentList
&Args
) {
5826 return getTemplateArgumentBindingsText(Params
, Args
.data(), Args
.size());
5830 Sema::getTemplateArgumentBindingsText(const TemplateParameterList
*Params
,
5831 const TemplateArgument
*Args
,
5835 if (!Params
|| Params
->size() == 0 || NumArgs
== 0)
5838 for (unsigned I
= 0, N
= Params
->size(); I
!= N
; ++I
) {
5847 if (const IdentifierInfo
*Id
= Params
->getParam(I
)->getIdentifier()) {
5848 Result
+= Id
->getName();
5851 Result
+= llvm::utostr(I
);
5856 switch (Args
[I
].getKind()) {
5857 case TemplateArgument::Null
:
5858 Result
+= "<no value>";
5861 case TemplateArgument::Type
: {
5862 std::string TypeStr
;
5863 Args
[I
].getAsType().getAsStringInternal(TypeStr
,
5864 Context
.PrintingPolicy
);
5869 case TemplateArgument::Declaration
: {
5870 bool Unnamed
= true;
5871 if (NamedDecl
*ND
= dyn_cast_or_null
<NamedDecl
>(Args
[I
].getAsDecl())) {
5872 if (ND
->getDeclName()) {
5874 Result
+= ND
->getNameAsString();
5879 Result
+= "<anonymous>";
5884 case TemplateArgument::Template
: {
5886 llvm::raw_string_ostream
OS(Str
);
5887 Args
[I
].getAsTemplate().print(OS
, Context
.PrintingPolicy
);
5892 case TemplateArgument::Integral
: {
5893 Result
+= Args
[I
].getAsIntegral()->toString(10);
5897 case TemplateArgument::Expression
: {
5898 // FIXME: This is non-optimal, since we're regurgitating the
5899 // expression we were given.
5902 llvm::raw_string_ostream
OS(Str
);
5903 Args
[I
].getAsExpr()->printPretty(OS
, Context
, 0,
5904 Context
.PrintingPolicy
);
5910 case TemplateArgument::Pack
:
5911 // FIXME: Format template argument packs
5912 Result
+= "<template argument pack>";