blob: 2e1a89e658813dcff3ee57e119732b0d3fb92281 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000013#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000014#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000015#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000016#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000020#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000021#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000023using namespace clang;
24
Douglas Gregorb7bfe792009-09-02 22:59:36 +000025/// \brief Determine whether the declaration found is acceptable as the name
26/// of a template and, if so, return that template declaration. Otherwise,
27/// returns NULL.
28static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
29 if (!D)
30 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000031
Douglas Gregorb7bfe792009-09-02 22:59:36 +000032 if (isa<TemplateDecl>(D))
33 return D;
Mike Stump11289f42009-09-09 15:08:12 +000034
Douglas Gregorb7bfe792009-09-02 22:59:36 +000035 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
36 // C++ [temp.local]p1:
37 // Like normal (non-template) classes, class templates have an
38 // injected-class-name (Clause 9). The injected-class-name
39 // can be used with or without a template-argument-list. When
40 // it is used without a template-argument-list, it is
41 // equivalent to the injected-class-name followed by the
42 // template-parameters of the class template enclosed in
43 // <>. When it is used with a template-argument-list, it
44 // refers to the specified class template specialization,
45 // which could be the current specialization or another
46 // specialization.
47 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000048 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000049 if (Record->getDescribedClassTemplate())
50 return Record->getDescribedClassTemplate();
51
52 if (ClassTemplateSpecializationDecl *Spec
53 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
54 return Spec->getSpecializedTemplate();
55 }
Mike Stump11289f42009-09-09 15:08:12 +000056
Douglas Gregorb7bfe792009-09-02 22:59:36 +000057 return 0;
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
61 if (!Ovl)
62 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000063
Douglas Gregorb7bfe792009-09-02 22:59:36 +000064 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
65 FEnd = Ovl->function_end();
66 F != FEnd; ++F) {
67 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
68 // We've found a function template. Determine whether there are
69 // any other function templates we need to bundle together in an
70 // OverloadedFunctionDecl
71 for (++F; F != FEnd; ++F) {
72 if (isa<FunctionTemplateDecl>(*F))
73 break;
74 }
Mike Stump11289f42009-09-09 15:08:12 +000075
Douglas Gregorb7bfe792009-09-02 22:59:36 +000076 if (F != FEnd) {
77 // Build an overloaded function decl containing only the
78 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000079 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000080 = OverloadedFunctionDecl::Create(Context,
81 Ovl->getDeclContext(),
82 Ovl->getDeclName());
83 OvlTemplate->addOverload(FuncTmpl);
84 OvlTemplate->addOverload(*F);
85 for (++F; F != FEnd; ++F) {
86 if (isa<FunctionTemplateDecl>(*F))
87 OvlTemplate->addOverload(*F);
88 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Douglas Gregorb7bfe792009-09-02 22:59:36 +000090 return OvlTemplate;
91 }
92
93 return FuncTmpl;
94 }
95 }
Mike Stump11289f42009-09-09 15:08:12 +000096
Douglas Gregorb7bfe792009-09-02 22:59:36 +000097 return 0;
98}
99
100TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000101 const CXXScopeSpec &SS,
102 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000103 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000104 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000105 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000106 DeclarationName TName;
107
108 switch (Name.getKind()) {
109 case UnqualifiedId::IK_Identifier:
110 TName = DeclarationName(Name.Identifier);
111 break;
112
113 case UnqualifiedId::IK_OperatorFunctionId:
114 TName = Context.DeclarationNames.getCXXOperatorName(
115 Name.OperatorFunctionId.Operator);
116 break;
117
118 default:
119 return TNK_Non_template;
120 }
121
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000122 // Determine where to perform name lookup
123 DeclContext *LookupCtx = 0;
124 bool isDependent = false;
125 if (ObjectTypePtr) {
126 // This nested-name-specifier occurs in a member access expression, e.g.,
127 // x->B::f, and we are looking into the type of the object.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000128 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000129 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
130 LookupCtx = computeDeclContext(ObjectType);
131 isDependent = ObjectType->isDependentType();
Douglas Gregor3cf81312009-11-03 23:16:33 +0000132 } else if (SS.isSet()) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000133 // This nested-name-specifier occurs after another nested-name-specifier,
134 // so long into the context associated with the prior nested-name-specifier.
135
Douglas Gregor3cf81312009-11-03 23:16:33 +0000136 LookupCtx = computeDeclContext(SS, EnteringContext);
137 isDependent = isDependentScopeSpecifier(SS);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000140 LookupResult Found;
141 bool ObjectTypeSearchedInScope = false;
142 if (LookupCtx) {
143 // Perform "qualified" name lookup into the declaration context we
144 // computed, which is either the type of the base of a member access
Mike Stump11289f42009-09-09 15:08:12 +0000145 // expression or the declaration context associated with a prior
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000146 // nested-name-specifier.
147
148 // The declaration context must be complete.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000149 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(SS))
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000150 return TNK_Non_template;
Mike Stump11289f42009-09-09 15:08:12 +0000151
Douglas Gregor3cf81312009-11-03 23:16:33 +0000152 LookupQualifiedName(Found, LookupCtx, TName, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +0000153
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000154 if (ObjectTypePtr && Found.getKind() == LookupResult::NotFound) {
155 // C++ [basic.lookup.classref]p1:
156 // In a class member access expression (5.2.5), if the . or -> token is
Mike Stump11289f42009-09-09 15:08:12 +0000157 // immediately followed by an identifier followed by a <, the
158 // identifier must be looked up to determine whether the < is the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000159 // beginning of a template argument list (14.2) or a less-than operator.
Mike Stump11289f42009-09-09 15:08:12 +0000160 // The identifier is first looked up in the class of the object
161 // expression. If the identifier is not found, it is then looked up in
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000162 // the context of the entire postfix-expression and shall name a class
163 // or function template.
164 //
165 // FIXME: When we're instantiating a template, do we actually have to
166 // look in the scope of the template? Seems fishy...
Douglas Gregor3cf81312009-11-03 23:16:33 +0000167 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000168 ObjectTypeSearchedInScope = true;
169 }
170 } else if (isDependent) {
Mike Stump11289f42009-09-09 15:08:12 +0000171 // We cannot look into a dependent object type or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000172 return TNK_Non_template;
173 } else {
174 // Perform unqualified name lookup in the current scope.
Douglas Gregor3cf81312009-11-03 23:16:33 +0000175 LookupName(Found, S, TName, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000176 }
Mike Stump11289f42009-09-09 15:08:12 +0000177
Douglas Gregore861bac2009-08-25 22:51:20 +0000178 // FIXME: Cope with ambiguous name-lookup results.
Mike Stump11289f42009-09-09 15:08:12 +0000179 assert(!Found.isAmbiguous() &&
Douglas Gregore861bac2009-08-25 22:51:20 +0000180 "Cannot handle template name-lookup ambiguities");
Douglas Gregordc572a32009-03-30 22:58:21 +0000181
John McCall9f3059a2009-10-09 21:13:30 +0000182 NamedDecl *Template
183 = isAcceptableTemplateName(Context, Found.getAsSingleDecl(Context));
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000184 if (!Template)
185 return TNK_Non_template;
186
187 if (ObjectTypePtr && !ObjectTypeSearchedInScope) {
188 // C++ [basic.lookup.classref]p1:
Mike Stump11289f42009-09-09 15:08:12 +0000189 // [...] If the lookup in the class of the object expression finds a
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000190 // template, the name is also looked up in the context of the entire
191 // postfix-expression and [...]
192 //
John McCall9f3059a2009-10-09 21:13:30 +0000193 LookupResult FoundOuter;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000194 LookupName(FoundOuter, S, TName, LookupOrdinaryName);
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000195 // FIXME: Handle ambiguities in this lookup better
John McCall9f3059a2009-10-09 21:13:30 +0000196 NamedDecl *OuterTemplate
197 = isAcceptableTemplateName(Context, FoundOuter.getAsSingleDecl(Context));
Mike Stump11289f42009-09-09 15:08:12 +0000198
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000199 if (!OuterTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +0000200 // - if the name is not found, the name found in the class of the
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000201 // object expression is used, otherwise
202 } else if (!isa<ClassTemplateDecl>(OuterTemplate)) {
Mike Stump11289f42009-09-09 15:08:12 +0000203 // - if the name is found in the context of the entire
204 // postfix-expression and does not name a class template, the name
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000205 // found in the class of the object expression is used, otherwise
206 } else {
207 // - if the name found is a class template, it must refer to the same
Mike Stump11289f42009-09-09 15:08:12 +0000208 // entity as the one found in the class of the object expression,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000209 // otherwise the program is ill-formed.
210 if (OuterTemplate->getCanonicalDecl() != Template->getCanonicalDecl()) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000211 Diag(Name.getSourceRange().getBegin(),
212 diag::err_nested_name_member_ref_lookup_ambiguous)
213 << TName
214 << Name.getSourceRange();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000215 Diag(Template->getLocation(), diag::note_ambig_member_ref_object_type)
216 << QualType::getFromOpaquePtr(ObjectTypePtr);
217 Diag(OuterTemplate->getLocation(), diag::note_ambig_member_ref_scope);
Mike Stump11289f42009-09-09 15:08:12 +0000218
219 // Recover by taking the template that we found in the object
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000220 // expression's type.
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000221 }
Mike Stump11289f42009-09-09 15:08:12 +0000222 }
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000223 }
Mike Stump11289f42009-09-09 15:08:12 +0000224
Douglas Gregor3cf81312009-11-03 23:16:33 +0000225 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000226 NestedNameSpecifier *Qualifier
Douglas Gregor3cf81312009-11-03 23:16:33 +0000227 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000228 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000229 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000230 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000231 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
232 Ovl));
233 else
Mike Stump11289f42009-09-09 15:08:12 +0000234 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000235 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000236 cast<TemplateDecl>(Template)));
237 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000238 = dyn_cast<OverloadedFunctionDecl>(Template)) {
239 TemplateResult = TemplateTy::make(TemplateName(Ovl));
240 } else {
241 TemplateResult = TemplateTy::make(
242 TemplateName(cast<TemplateDecl>(Template)));
243 }
Mike Stump11289f42009-09-09 15:08:12 +0000244
245 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000246 isa<TemplateTemplateParmDecl>(Template))
247 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000248
249 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000250 isa<OverloadedFunctionDecl>(Template)) &&
251 "Unhandled template kind in Sema::isTemplateName");
252 return TNK_Function_template;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000253}
254
Douglas Gregor5101c242008-12-05 18:15:24 +0000255/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
256/// that the template parameter 'PrevDecl' is being shadowed by a new
257/// declaration at location Loc. Returns true to indicate that this is
258/// an error, and false otherwise.
259bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000260 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000261
262 // Microsoft Visual C++ permits template parameters to be shadowed.
263 if (getLangOptions().Microsoft)
264 return false;
265
266 // C++ [temp.local]p4:
267 // A template-parameter shall not be redeclared within its
268 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000269 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000270 << cast<NamedDecl>(PrevDecl)->getDeclName();
271 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
272 return true;
273}
274
Douglas Gregor463421d2009-03-03 04:44:36 +0000275/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000276/// the parameter D to reference the templated declaration and return a pointer
277/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000278TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000279 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000280 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000281 return Temp;
282 }
283 return 0;
284}
285
Douglas Gregor5101c242008-12-05 18:15:24 +0000286/// ActOnTypeParameter - Called when a C++ template type parameter
287/// (e.g., "typename T") has been parsed. Typename specifies whether
288/// the keyword "typename" was used to declare the type parameter
289/// (otherwise, "class" was used), and KeyLoc is the location of the
290/// "class" or "typename" keyword. ParamName is the name of the
291/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000292/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000293/// If the type parameter has a default argument, it will be added
294/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000295Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000296 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000297 SourceLocation KeyLoc,
298 IdentifierInfo *ParamName,
299 SourceLocation ParamNameLoc,
300 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000301 assert(S->isTemplateParamScope() &&
302 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000303 bool Invalid = false;
304
305 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000306 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000307 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000308 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000309 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000310 }
311
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000312 SourceLocation Loc = ParamNameLoc;
313 if (!ParamName)
314 Loc = KeyLoc;
315
Douglas Gregor5101c242008-12-05 18:15:24 +0000316 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000317 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
318 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000319 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000320 if (Invalid)
321 Param->setInvalidDecl();
322
323 if (ParamName) {
324 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000325 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000326 IdResolver.AddDecl(Param);
327 }
328
Chris Lattner83f095c2009-03-28 19:18:32 +0000329 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000330}
331
Douglas Gregordba32632009-02-10 19:49:53 +0000332/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000333/// Default) to the given template type parameter (TypeParam).
334void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000335 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000336 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000337 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000338 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000339 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000340
341 DeclaratorInfo *DefaultDInfo;
342 GetTypeFromParser(DefaultT, &DefaultDInfo);
343
344 assert(DefaultDInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000345
Anders Carlssond3824352009-06-12 22:30:13 +0000346 // C++0x [temp.param]p9:
347 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000348 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000349 if (Parm->isParameterPack()) {
350 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000351 return;
352 }
Mike Stump11289f42009-09-09 15:08:12 +0000353
Douglas Gregordba32632009-02-10 19:49:53 +0000354 // C++ [temp.param]p14:
355 // A template-parameter shall not be used in its own default argument.
356 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000357
Douglas Gregordba32632009-02-10 19:49:53 +0000358 // Check the template argument itself.
John McCall0ad16662009-10-29 08:12:44 +0000359 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000360 Parm->setInvalidDecl();
361 return;
362 }
363
John McCall0ad16662009-10-29 08:12:44 +0000364 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000365}
366
Douglas Gregor463421d2009-03-03 04:44:36 +0000367/// \brief Check that the type of a non-type template parameter is
368/// well-formed.
369///
370/// \returns the (possibly-promoted) parameter type if valid;
371/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000372QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000373Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
374 // C++ [temp.param]p4:
375 //
376 // A non-type template-parameter shall have one of the following
377 // (optionally cv-qualified) types:
378 //
379 // -- integral or enumeration type,
380 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000381 // -- pointer to object or pointer to function,
382 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000383 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
384 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000385 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000386 T->isReferenceType() ||
387 // -- pointer to member.
388 T->isMemberPointerType() ||
389 // If T is a dependent type, we can't do the check now, so we
390 // assume that it is well-formed.
391 T->isDependentType())
392 return T;
393 // C++ [temp.param]p8:
394 //
395 // A non-type template-parameter of type "array of T" or
396 // "function returning T" is adjusted to be of type "pointer to
397 // T" or "pointer to function returning T", respectively.
398 else if (T->isArrayType())
399 // FIXME: Keep the type prior to promotion?
400 return Context.getArrayDecayedType(T);
401 else if (T->isFunctionType())
402 // FIXME: Keep the type prior to promotion?
403 return Context.getPointerType(T);
404
405 Diag(Loc, diag::err_template_nontype_parm_bad_type)
406 << T;
407
408 return QualType();
409}
410
Douglas Gregor5101c242008-12-05 18:15:24 +0000411/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
412/// template parameter (e.g., "int Size" in "template<int Size>
413/// class Array") has been parsed. S is the current scope and D is
414/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000415Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000416 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000417 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000418 DeclaratorInfo *DInfo = 0;
419 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000420
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000421 assert(S->isTemplateParamScope() &&
422 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000423 bool Invalid = false;
424
425 IdentifierInfo *ParamName = D.getIdentifier();
426 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000427 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000428 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000429 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000430 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000431 }
432
Douglas Gregor463421d2009-03-03 04:44:36 +0000433 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000434 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000435 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000436 Invalid = true;
437 }
Douglas Gregor81338792009-02-10 17:43:50 +0000438
Douglas Gregor5101c242008-12-05 18:15:24 +0000439 NonTypeTemplateParmDecl *Param
440 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000441 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000442 if (Invalid)
443 Param->setInvalidDecl();
444
445 if (D.getIdentifier()) {
446 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000447 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000448 IdResolver.AddDecl(Param);
449 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000450 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000451}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000452
Douglas Gregordba32632009-02-10 19:49:53 +0000453/// \brief Adds a default argument to the given non-type template
454/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000455void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000456 SourceLocation EqualLoc,
457 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000458 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000459 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000460 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000461
Douglas Gregordba32632009-02-10 19:49:53 +0000462 // C++ [temp.param]p14:
463 // A template-parameter shall not be used in its own default argument.
464 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000465
Douglas Gregordba32632009-02-10 19:49:53 +0000466 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000467 TemplateArgument Converted;
468 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
469 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000470 TemplateParm->setInvalidDecl();
471 return;
472 }
473
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000474 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000475}
476
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000477
478/// ActOnTemplateTemplateParameter - Called when a C++ template template
479/// parameter (e.g. T in template <template <typename> class T> class array)
480/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000481Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
482 SourceLocation TmpLoc,
483 TemplateParamsTy *Params,
484 IdentifierInfo *Name,
485 SourceLocation NameLoc,
486 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000487 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000488 assert(S->isTemplateParamScope() &&
489 "Template template parameter not in template parameter scope!");
490
491 // Construct the parameter object.
492 TemplateTemplateParmDecl *Param =
493 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
494 Position, Name,
495 (TemplateParameterList*)Params);
496
497 // Make sure the parameter is valid.
498 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
499 // do anything yet. However, if the template parameter list or (eventual)
500 // default value is ever invalidated, that will propagate here.
501 bool Invalid = false;
502 if (Invalid) {
503 Param->setInvalidDecl();
504 }
505
506 // If the tt-param has a name, then link the identifier into the scope
507 // and lookup mechanisms.
508 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000509 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000510 IdResolver.AddDecl(Param);
511 }
512
Chris Lattner83f095c2009-03-28 19:18:32 +0000513 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000514}
515
Douglas Gregordba32632009-02-10 19:49:53 +0000516/// \brief Adds a default argument to the given template template
517/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000518void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000519 SourceLocation EqualLoc,
520 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000521 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000522 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000523
524 // Since a template-template parameter's default argument is an
525 // id-expression, it must be a DeclRefExpr.
Mike Stump11289f42009-09-09 15:08:12 +0000526 DeclRefExpr *Default
Douglas Gregordba32632009-02-10 19:49:53 +0000527 = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
528
529 // C++ [temp.param]p14:
530 // A template-parameter shall not be used in its own default argument.
531 // FIXME: Implement this check! Needs a recursive walk over the types.
532
533 // Check the well-formedness of the template argument.
534 if (!isa<TemplateDecl>(Default->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +0000535 Diag(Default->getSourceRange().getBegin(),
Douglas Gregordba32632009-02-10 19:49:53 +0000536 diag::err_template_arg_must_be_template)
537 << Default->getSourceRange();
538 TemplateParm->setInvalidDecl();
539 return;
Mike Stump11289f42009-09-09 15:08:12 +0000540 }
Douglas Gregordba32632009-02-10 19:49:53 +0000541 if (CheckTemplateArgument(TemplateParm, Default)) {
542 TemplateParm->setInvalidDecl();
543 return;
544 }
545
546 DefaultE.release();
547 TemplateParm->setDefaultArgument(Default);
548}
549
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000550/// ActOnTemplateParameterList - Builds a TemplateParameterList that
551/// contains the template parameters in Params/NumParams.
552Sema::TemplateParamsTy *
553Sema::ActOnTemplateParameterList(unsigned Depth,
554 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000555 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000556 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000557 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000558 SourceLocation RAngleLoc) {
559 if (ExportLoc.isValid())
560 Diag(ExportLoc, diag::note_template_export_unsupported);
561
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000562 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000563 (NamedDecl**)Params, NumParams,
564 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000565}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000566
Douglas Gregorc08f4892009-03-25 00:13:59 +0000567Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000568Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000569 SourceLocation KWLoc, const CXXScopeSpec &SS,
570 IdentifierInfo *Name, SourceLocation NameLoc,
571 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000572 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000573 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000574 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000575 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000576 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000577 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000578
579 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000580 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000581 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000582
John McCall27b5c252009-09-14 21:59:20 +0000583 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
584 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000585
586 // There is no such thing as an unnamed class template.
587 if (!Name) {
588 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000589 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000590 }
591
592 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000593 DeclContext *SemanticContext;
594 LookupResult Previous;
595 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000596 if (RequireCompleteDeclContext(SS))
597 return true;
598
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000599 SemanticContext = computeDeclContext(SS, true);
600 if (!SemanticContext) {
601 // FIXME: Produce a reasonable diagnostic here
602 return true;
603 }
Mike Stump11289f42009-09-09 15:08:12 +0000604
John McCall9f3059a2009-10-09 21:13:30 +0000605 LookupQualifiedName(Previous, SemanticContext, Name, LookupOrdinaryName,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000606 true);
607 } else {
608 SemanticContext = CurContext;
John McCall9f3059a2009-10-09 21:13:30 +0000609 LookupName(Previous, S, Name, LookupOrdinaryName, true);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000610 }
Mike Stump11289f42009-09-09 15:08:12 +0000611
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000612 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
613 NamedDecl *PrevDecl = 0;
614 if (Previous.begin() != Previous.end())
615 PrevDecl = *Previous.begin();
616
Douglas Gregor9acb6902009-09-26 07:05:09 +0000617 if (PrevDecl && TUK == TUK_Friend) {
618 // C++ [namespace.memdef]p3:
619 // [...] When looking for a prior declaration of a class or a function
620 // declared as a friend, and when the name of the friend class or
621 // function is neither a qualified name nor a template-id, scopes outside
622 // the innermost enclosing namespace scope are not considered.
623 DeclContext *OutermostContext = CurContext;
624 while (!OutermostContext->isFileContext())
625 OutermostContext = OutermostContext->getLookupParent();
626
627 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
628 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
629 SemanticContext = PrevDecl->getDeclContext();
630 } else {
631 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000632 // context we computed is the semantic context for our new
Douglas Gregor9acb6902009-09-26 07:05:09 +0000633 // declaration.
634 PrevDecl = 0;
635 SemanticContext = OutermostContext;
636 }
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000637
638 if (CurContext->isDependentContext()) {
639 // If this is a dependent context, we don't want to link the friend
640 // class template to the template in scope, because that would perform
641 // checking of the template parameter lists that can't be performed
642 // until the outer context is instantiated.
643 PrevDecl = 0;
644 }
Douglas Gregor9acb6902009-09-26 07:05:09 +0000645 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000646 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000647
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000648 // If there is a previous declaration with the same name, check
649 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000650 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000651 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000652
653 // We may have found the injected-class-name of a class template,
654 // class template partial specialization, or class template specialization.
655 // In these cases, grab the template that is being defined or specialized.
656 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
657 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
658 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
659 PrevClassTemplate
660 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
661 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
662 PrevClassTemplate
663 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
664 ->getSpecializedTemplate();
665 }
666 }
667
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000668 if (PrevClassTemplate) {
669 // Ensure that the template parameter lists are compatible.
670 if (!TemplateParameterListsAreEqual(TemplateParams,
671 PrevClassTemplate->getTemplateParameters(),
672 /*Complain=*/true))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000673 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000674
675 // C++ [temp.class]p4:
676 // In a redeclaration, partial specialization, explicit
677 // specialization or explicit instantiation of a class template,
678 // the class-key shall agree in kind with the original class
679 // template declaration (7.1.5.3).
680 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000681 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000682 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000683 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000684 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000685 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000686 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000687 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000688 }
689
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000690 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000691 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000692 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
693 Diag(NameLoc, diag::err_redefinition) << Name;
694 Diag(Def->getLocation(), diag::note_previous_definition);
695 // FIXME: Would it make sense to try to "forget" the previous
696 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000697 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000698 }
699 }
700 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
701 // Maybe we will complain about the shadowed template parameter.
702 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
703 // Just pretend that we didn't see the previous declaration.
704 PrevDecl = 0;
705 } else if (PrevDecl) {
706 // C++ [temp]p5:
707 // A class template shall not have the same name as any other
708 // template, class, function, object, enumeration, enumerator,
709 // namespace, or type in the same scope (3.3), except as specified
710 // in (14.5.4).
711 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
712 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000713 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000714 }
715
Douglas Gregordba32632009-02-10 19:49:53 +0000716 // Check the template parameter list of this declaration, possibly
717 // merging in the template parameter list from the previous class
718 // template declaration.
719 if (CheckTemplateParameterList(TemplateParams,
720 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
721 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000722
Douglas Gregore362cea2009-05-10 22:57:19 +0000723 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000724 // declaration!
725
Mike Stump11289f42009-09-09 15:08:12 +0000726 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000727 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000728 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000729 PrevClassTemplate->getTemplatedDecl() : 0,
730 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000731
732 ClassTemplateDecl *NewTemplate
733 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
734 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000735 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000736 NewClass->setDescribedClassTemplate(NewTemplate);
737
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000738 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000739 QualType T =
740 Context.getTypeDeclType(NewClass,
741 PrevClassTemplate?
742 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000743 assert(T->isDependentType() && "Class template type is not dependent?");
744 (void)T;
745
Douglas Gregorcf915552009-10-13 16:30:37 +0000746 // If we are providing an explicit specialization of a member that is a
747 // class template, make a note of that.
748 if (PrevClassTemplate &&
749 PrevClassTemplate->getInstantiatedFromMemberTemplate())
750 PrevClassTemplate->setMemberSpecialization();
751
Anders Carlsson137108d2009-03-26 01:24:28 +0000752 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000753 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000754 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000755
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000756 // Set the lexical context of these templates
757 NewClass->setLexicalDeclContext(CurContext);
758 NewTemplate->setLexicalDeclContext(CurContext);
759
John McCall9bb74a52009-07-31 02:45:11 +0000760 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000761 NewClass->startDefinition();
762
763 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000764 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000765
John McCall27b5c252009-09-14 21:59:20 +0000766 if (TUK != TUK_Friend)
767 PushOnScopeChains(NewTemplate, S);
768 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000769 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000770 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000771 NewClass->setAccess(PrevClassTemplate->getAccess());
772 }
John McCall27b5c252009-09-14 21:59:20 +0000773
Douglas Gregor3dad8422009-09-26 06:47:28 +0000774 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
775 PrevClassTemplate != NULL);
776
John McCall27b5c252009-09-14 21:59:20 +0000777 // Friend templates are visible in fairly strange ways.
778 if (!CurContext->isDependentContext()) {
779 DeclContext *DC = SemanticContext->getLookupContext();
780 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
781 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
782 PushOnScopeChains(NewTemplate, EnclosingScope,
783 /* AddToContext = */ false);
784 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000785
786 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
787 NewClass->getLocation(),
788 NewTemplate,
789 /*FIXME:*/NewClass->getLocation());
790 Friend->setAccess(AS_public);
791 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000792 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000793
Douglas Gregordba32632009-02-10 19:49:53 +0000794 if (Invalid) {
795 NewTemplate->setInvalidDecl();
796 NewClass->setInvalidDecl();
797 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000798 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000799}
800
Douglas Gregordba32632009-02-10 19:49:53 +0000801/// \brief Checks the validity of a template parameter list, possibly
802/// considering the template parameter list from a previous
803/// declaration.
804///
805/// If an "old" template parameter list is provided, it must be
806/// equivalent (per TemplateParameterListsAreEqual) to the "new"
807/// template parameter list.
808///
809/// \param NewParams Template parameter list for a new template
810/// declaration. This template parameter list will be updated with any
811/// default arguments that are carried through from the previous
812/// template parameter list.
813///
814/// \param OldParams If provided, template parameter list from a
815/// previous declaration of the same template. Default template
816/// arguments will be merged from the old template parameter list to
817/// the new template parameter list.
818///
819/// \returns true if an error occurred, false otherwise.
820bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
821 TemplateParameterList *OldParams) {
822 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +0000823
Douglas Gregordba32632009-02-10 19:49:53 +0000824 // C++ [temp.param]p10:
825 // The set of default template-arguments available for use with a
826 // template declaration or definition is obtained by merging the
827 // default arguments from the definition (if in scope) and all
828 // declarations in scope in the same way default function
829 // arguments are (8.3.6).
830 bool SawDefaultArgument = false;
831 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +0000832
Anders Carlsson327865d2009-06-12 23:20:15 +0000833 bool SawParameterPack = false;
834 SourceLocation ParameterPackLoc;
835
Mike Stumpc89c8e32009-02-11 23:03:27 +0000836 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +0000837 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +0000838 if (OldParams)
839 OldParam = OldParams->begin();
840
841 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
842 NewParamEnd = NewParams->end();
843 NewParam != NewParamEnd; ++NewParam) {
844 // Variables used to diagnose redundant default arguments
845 bool RedundantDefaultArg = false;
846 SourceLocation OldDefaultLoc;
847 SourceLocation NewDefaultLoc;
848
849 // Variables used to diagnose missing default arguments
850 bool MissingDefaultArg = false;
851
Anders Carlsson327865d2009-06-12 23:20:15 +0000852 // C++0x [temp.param]p11:
853 // If a template parameter of a class template is a template parameter pack,
854 // it must be the last template parameter.
855 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +0000856 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +0000857 diag::err_template_param_pack_must_be_last_template_parameter);
858 Invalid = true;
859 }
860
Douglas Gregordba32632009-02-10 19:49:53 +0000861 // Merge default arguments for template type parameters.
862 if (TemplateTypeParmDecl *NewTypeParm
863 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +0000864 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000865 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000866
Anders Carlsson327865d2009-06-12 23:20:15 +0000867 if (NewTypeParm->isParameterPack()) {
868 assert(!NewTypeParm->hasDefaultArgument() &&
869 "Parameter packs can't have a default argument!");
870 SawParameterPack = true;
871 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000872 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +0000873 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +0000874 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
875 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
876 SawDefaultArgument = true;
877 RedundantDefaultArg = true;
878 PreviousDefaultArgLoc = NewDefaultLoc;
879 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
880 // Merge the default argument from the old declaration to the
881 // new declaration.
882 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +0000883 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +0000884 true);
885 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
886 } else if (NewTypeParm->hasDefaultArgument()) {
887 SawDefaultArgument = true;
888 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
889 } else if (SawDefaultArgument)
890 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000891 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +0000892 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000893 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000894 NonTypeTemplateParmDecl *OldNonTypeParm
895 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000896 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000897 NewNonTypeParm->hasDefaultArgument()) {
898 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
899 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
900 SawDefaultArgument = true;
901 RedundantDefaultArg = true;
902 PreviousDefaultArgLoc = NewDefaultLoc;
903 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
904 // Merge the default argument from the old declaration to the
905 // new declaration.
906 SawDefaultArgument = true;
907 // FIXME: We need to create a new kind of "default argument"
908 // expression that points to a previous template template
909 // parameter.
910 NewNonTypeParm->setDefaultArgument(
911 OldNonTypeParm->getDefaultArgument());
912 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
913 } else if (NewNonTypeParm->hasDefaultArgument()) {
914 SawDefaultArgument = true;
915 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
916 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000917 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +0000918 } else {
Douglas Gregordba32632009-02-10 19:49:53 +0000919 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +0000920 TemplateTemplateParmDecl *NewTemplateParm
921 = cast<TemplateTemplateParmDecl>(*NewParam);
922 TemplateTemplateParmDecl *OldTemplateParm
923 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +0000924 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +0000925 NewTemplateParm->hasDefaultArgument()) {
926 OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
927 NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
928 SawDefaultArgument = true;
929 RedundantDefaultArg = true;
930 PreviousDefaultArgLoc = NewDefaultLoc;
931 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
932 // Merge the default argument from the old declaration to the
933 // new declaration.
934 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +0000935 // FIXME: We need to create a new kind of "default argument" expression
936 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +0000937 NewTemplateParm->setDefaultArgument(
938 OldTemplateParm->getDefaultArgument());
939 PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
940 } else if (NewTemplateParm->hasDefaultArgument()) {
941 SawDefaultArgument = true;
942 PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
943 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000944 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +0000945 }
946
947 if (RedundantDefaultArg) {
948 // C++ [temp.param]p12:
949 // A template-parameter shall not be given default arguments
950 // by two different declarations in the same scope.
951 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
952 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
953 Invalid = true;
954 } else if (MissingDefaultArg) {
955 // C++ [temp.param]p11:
956 // If a template-parameter has a default template-argument,
957 // all subsequent template-parameters shall have a default
958 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +0000959 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +0000960 diag::err_template_param_default_arg_missing);
961 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
962 Invalid = true;
963 }
964
965 // If we have an old template parameter list that we're merging
966 // in, move on to the next parameter.
967 if (OldParams)
968 ++OldParam;
969 }
970
971 return Invalid;
972}
Douglas Gregord32e0282009-02-09 23:23:08 +0000973
Mike Stump11289f42009-09-09 15:08:12 +0000974/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +0000975/// specifier, returning the template parameter list that applies to the
976/// name.
977///
978/// \param DeclStartLoc the start of the declaration that has a scope
979/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000980///
Douglas Gregord8d297c2009-07-21 23:53:31 +0000981/// \param SS the scope specifier that will be matched to the given template
982/// parameter lists. This scope specifier precedes a qualified name that is
983/// being declared.
984///
985/// \param ParamLists the template parameter lists, from the outermost to the
986/// innermost template parameter lists.
987///
988/// \param NumParamLists the number of template parameter lists in ParamLists.
989///
Douglas Gregor5c0405d2009-10-07 22:35:40 +0000990/// \param IsExplicitSpecialization will be set true if the entity being
991/// declared is an explicit specialization, false otherwise.
992///
Mike Stump11289f42009-09-09 15:08:12 +0000993/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +0000994/// name that is preceded by the scope specifier @p SS. This template
995/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +0000996/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +0000997/// template specialization), or may be NULL (if we were's declaring isn't
998/// itself a template).
999TemplateParameterList *
1000Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1001 const CXXScopeSpec &SS,
1002 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001003 unsigned NumParamLists,
1004 bool &IsExplicitSpecialization) {
1005 IsExplicitSpecialization = false;
1006
Douglas Gregord8d297c2009-07-21 23:53:31 +00001007 // Find the template-ids that occur within the nested-name-specifier. These
1008 // template-ids will match up with the template parameter lists.
1009 llvm::SmallVector<const TemplateSpecializationType *, 4>
1010 TemplateIdsInSpecifier;
1011 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1012 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001013 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001014 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1015 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1016 if (!Template)
1017 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001018
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001019 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001020 ClassTemplateSpecializationDecl *SpecDecl
1021 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1022 // If the nested name specifier refers to an explicit specialization,
1023 // we don't need a template<> header.
Douglas Gregor82e22862009-09-16 00:01:48 +00001024 // FIXME: revisit this approach once we cope with specializations
Douglas Gregor15301382009-07-30 17:40:51 +00001025 // properly.
Douglas Gregord8d297c2009-07-21 23:53:31 +00001026 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization)
1027 continue;
1028 }
Mike Stump11289f42009-09-09 15:08:12 +00001029
Douglas Gregord8d297c2009-07-21 23:53:31 +00001030 TemplateIdsInSpecifier.push_back(SpecType);
1031 }
1032 }
Mike Stump11289f42009-09-09 15:08:12 +00001033
Douglas Gregord8d297c2009-07-21 23:53:31 +00001034 // Reverse the list of template-ids in the scope specifier, so that we can
1035 // more easily match up the template-ids and the template parameter lists.
1036 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001037
Douglas Gregord8d297c2009-07-21 23:53:31 +00001038 SourceLocation FirstTemplateLoc = DeclStartLoc;
1039 if (NumParamLists)
1040 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001041
Douglas Gregord8d297c2009-07-21 23:53:31 +00001042 // Match the template-ids found in the specifier to the template parameter
1043 // lists.
1044 unsigned Idx = 0;
1045 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1046 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001047 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1048 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001049 if (Idx >= NumParamLists) {
1050 // We have a template-id without a corresponding template parameter
1051 // list.
1052 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001053 // FIXME: the location information here isn't great.
1054 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001055 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001056 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001057 << SS.getRange();
1058 } else {
1059 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1060 << SS.getRange()
1061 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1062 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001063 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001064 }
1065 return 0;
1066 }
Mike Stump11289f42009-09-09 15:08:12 +00001067
Douglas Gregord8d297c2009-07-21 23:53:31 +00001068 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001069 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001070 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001071 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1072
Mike Stump11289f42009-09-09 15:08:12 +00001073 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001074 = dyn_cast<ClassTemplateDecl>(Template)) {
1075 TemplateParameterList *ExpectedTemplateParams = 0;
1076 // Is this template-id naming the primary template?
1077 if (Context.hasSameType(TemplateId,
1078 ClassTemplate->getInjectedClassNameType(Context)))
1079 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1080 // ... or a partial specialization?
1081 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1082 = ClassTemplate->findPartialSpecialization(TemplateId))
1083 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1084
1085 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001086 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001087 ExpectedTemplateParams,
1088 true);
Mike Stump11289f42009-09-09 15:08:12 +00001089 }
Douglas Gregor15301382009-07-30 17:40:51 +00001090 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001091 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001092 diag::err_template_param_list_matches_nontemplate)
1093 << TemplateId
1094 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001095 else
1096 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001097 }
Mike Stump11289f42009-09-09 15:08:12 +00001098
Douglas Gregord8d297c2009-07-21 23:53:31 +00001099 // If there were at least as many template-ids as there were template
1100 // parameter lists, then there are no template parameter lists remaining for
1101 // the declaration itself.
1102 if (Idx >= NumParamLists)
1103 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001104
Douglas Gregord8d297c2009-07-21 23:53:31 +00001105 // If there were too many template parameter lists, complain about that now.
1106 if (Idx != NumParamLists - 1) {
1107 while (Idx < NumParamLists - 1) {
Mike Stump11289f42009-09-09 15:08:12 +00001108 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001109 diag::err_template_spec_extra_headers)
1110 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1111 ParamLists[Idx]->getRAngleLoc());
1112 ++Idx;
1113 }
1114 }
Mike Stump11289f42009-09-09 15:08:12 +00001115
Douglas Gregord8d297c2009-07-21 23:53:31 +00001116 // Return the last template parameter list, which corresponds to the
1117 // entity being declared.
1118 return ParamLists[NumParamLists - 1];
1119}
1120
Douglas Gregorc40290e2009-03-09 23:48:35 +00001121/// \brief Translates template arguments as provided by the parser
1122/// into template arguments used by semantic analysis.
Douglas Gregor0e876e02009-09-25 23:53:26 +00001123void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
1124 SourceLocation *TemplateArgLocs,
John McCall0ad16662009-10-29 08:12:44 +00001125 llvm::SmallVector<TemplateArgumentLoc, 16> &TemplateArgs) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001126 TemplateArgs.reserve(TemplateArgsIn.size());
1127
1128 void **Args = TemplateArgsIn.getArgs();
1129 bool *ArgIsType = TemplateArgsIn.getArgIsType();
1130 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
John McCall0ad16662009-10-29 08:12:44 +00001131 if (ArgIsType[Arg]) {
1132 DeclaratorInfo *DI;
1133 QualType T = Sema::GetTypeFromParser(Args[Arg], &DI);
1134 if (!DI) DI = Context.getTrivialDeclaratorInfo(T, TemplateArgLocs[Arg]);
1135 TemplateArgs.push_back(TemplateArgumentLoc(TemplateArgument(T), DI));
1136 } else {
1137 Expr *E = reinterpret_cast<Expr *>(Args[Arg]);
1138 TemplateArgs.push_back(TemplateArgumentLoc(TemplateArgument(E), E));
1139 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00001140 }
1141}
1142
Douglas Gregordc572a32009-03-30 22:58:21 +00001143QualType Sema::CheckTemplateIdType(TemplateName Name,
1144 SourceLocation TemplateLoc,
1145 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001146 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregordc572a32009-03-30 22:58:21 +00001147 unsigned NumTemplateArgs,
1148 SourceLocation RAngleLoc) {
1149 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001150 if (!Template) {
1151 // The template name does not resolve to a template, so we just
1152 // build a dependent template-id type.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001153 return Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001154 NumTemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001155 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001156
Douglas Gregorc40290e2009-03-09 23:48:35 +00001157 // Check that the template argument list is well-formed for this
1158 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001159 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1160 NumTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001161 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001162 TemplateArgs, NumTemplateArgs, RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001163 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001164 return QualType();
1165
Mike Stump11289f42009-09-09 15:08:12 +00001166 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001167 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001168 "Converted template argument list is too short!");
1169
1170 QualType CanonType;
1171
Douglas Gregordc572a32009-03-30 22:58:21 +00001172 if (TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregorc40290e2009-03-09 23:48:35 +00001173 TemplateArgs,
1174 NumTemplateArgs)) {
1175 // This class template specialization is a dependent
1176 // type. Therefore, its canonical type is another class template
1177 // specialization type that contains all of the converted
1178 // arguments in canonical form. This ensures that, e.g., A<T> and
1179 // A<T, T> have identical types when A is declared as:
1180 //
1181 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001182 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001183 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001184 Converted.getFlatArguments(),
1185 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001186
Douglas Gregora8e02e72009-07-28 23:00:59 +00001187 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001188 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001189 // In the future, we need to teach getTemplateSpecializationType to only
1190 // build the canonical type and return that to us.
1191 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001192 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001193 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001194 // Find the class template specialization declaration that
1195 // corresponds to these arguments.
1196 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001197 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001198 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001199 Converted.flatSize(),
1200 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001201 void *InsertPos = 0;
1202 ClassTemplateSpecializationDecl *Decl
1203 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1204 if (!Decl) {
1205 // This is the first time we have referenced this class template
1206 // specialization. Create the canonical declaration and add it to
1207 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001208 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001209 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001210 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001211 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001212 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001213 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1214 Decl->setLexicalDeclContext(CurContext);
1215 }
1216
1217 CanonType = Context.getTypeDeclType(Decl);
1218 }
Mike Stump11289f42009-09-09 15:08:12 +00001219
Douglas Gregorc40290e2009-03-09 23:48:35 +00001220 // Build the fully-sugared type for this class template
1221 // specialization, which refers back to the class template
1222 // specialization we created or found.
Douglas Gregordc572a32009-03-30 22:58:21 +00001223 return Context.getTemplateSpecializationType(Name, TemplateArgs,
1224 NumTemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001225}
1226
Douglas Gregor67a65642009-02-17 23:15:12 +00001227Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001228Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001229 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001230 ASTTemplateArgsPtr TemplateArgsIn,
John McCall0ad16662009-10-29 08:12:44 +00001231 SourceLocation *TemplateArgLocsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001232 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001233 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001234
Douglas Gregorc40290e2009-03-09 23:48:35 +00001235 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001236 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
1237 translateTemplateArguments(TemplateArgsIn, TemplateArgLocsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001238
Douglas Gregordc572a32009-03-30 22:58:21 +00001239 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +00001240 TemplateArgs.data(),
1241 TemplateArgs.size(),
Douglas Gregordc572a32009-03-30 22:58:21 +00001242 RAngleLoc);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001243 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001244
1245 if (Result.isNull())
1246 return true;
1247
John McCall0ad16662009-10-29 08:12:44 +00001248 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1249 TemplateSpecializationTypeLoc TL
1250 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1251 TL.setTemplateNameLoc(TemplateLoc);
1252 TL.setLAngleLoc(LAngleLoc);
1253 TL.setRAngleLoc(RAngleLoc);
1254 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1255 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1256
1257 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001258}
John McCall06f6fe8d2009-09-04 01:14:41 +00001259
John McCalld8fe9af2009-09-08 17:47:29 +00001260Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1261 TagUseKind TUK,
1262 DeclSpec::TST TagSpec,
1263 SourceLocation TagLoc) {
1264 if (TypeResult.isInvalid())
1265 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001266
John McCall0ad16662009-10-29 08:12:44 +00001267 // FIXME: preserve source info, ideally without copying the DI.
1268 DeclaratorInfo *DI;
1269 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001270
John McCalld8fe9af2009-09-08 17:47:29 +00001271 // Verify the tag specifier.
1272 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001273
John McCalld8fe9af2009-09-08 17:47:29 +00001274 if (const RecordType *RT = Type->getAs<RecordType>()) {
1275 RecordDecl *D = RT->getDecl();
1276
1277 IdentifierInfo *Id = D->getIdentifier();
1278 assert(Id && "templated class must have an identifier");
1279
1280 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1281 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001282 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001283 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1284 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001285 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001286 }
1287 }
1288
John McCalld8fe9af2009-09-08 17:47:29 +00001289 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1290
1291 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001292}
1293
Douglas Gregord019ff62009-10-22 17:20:55 +00001294Sema::OwningExprResult Sema::BuildTemplateIdExpr(NestedNameSpecifier *Qualifier,
1295 SourceRange QualifierRange,
1296 TemplateName Template,
Douglas Gregora727cb92009-06-30 22:34:41 +00001297 SourceLocation TemplateNameLoc,
1298 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001299 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001300 unsigned NumTemplateArgs,
1301 SourceLocation RAngleLoc) {
1302 // FIXME: Can we do any checking at this point? I guess we could check the
1303 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001304 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001305 // though.
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001306
1307 // Cope with an implicit member access in a C++ non-static member function.
1308 NamedDecl *D = Template.getAsTemplateDecl();
1309 if (!D)
1310 D = Template.getAsOverloadedFunctionDecl();
1311
Douglas Gregord019ff62009-10-22 17:20:55 +00001312 CXXScopeSpec SS;
1313 SS.setRange(QualifierRange);
1314 SS.setScopeRep(Qualifier);
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001315 QualType ThisType, MemberType;
Douglas Gregord019ff62009-10-22 17:20:55 +00001316 if (D && isImplicitMemberReference(&SS, D, TemplateNameLoc,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001317 ThisType, MemberType)) {
1318 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1319 return Owned(MemberExpr::Create(Context, This, true,
Douglas Gregord019ff62009-10-22 17:20:55 +00001320 Qualifier, QualifierRange,
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001321 D, TemplateNameLoc, true,
1322 LAngleLoc, TemplateArgs,
1323 NumTemplateArgs, RAngleLoc,
1324 Context.OverloadTy));
1325 }
1326
Douglas Gregord019ff62009-10-22 17:20:55 +00001327 return Owned(TemplateIdRefExpr::Create(Context, Context.OverloadTy,
1328 Qualifier, QualifierRange,
Douglas Gregora727cb92009-06-30 22:34:41 +00001329 Template, TemplateNameLoc, LAngleLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001330 TemplateArgs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001331 NumTemplateArgs, RAngleLoc));
1332}
1333
Douglas Gregord019ff62009-10-22 17:20:55 +00001334Sema::OwningExprResult Sema::ActOnTemplateIdExpr(const CXXScopeSpec &SS,
1335 TemplateTy TemplateD,
Douglas Gregora727cb92009-06-30 22:34:41 +00001336 SourceLocation TemplateNameLoc,
1337 SourceLocation LAngleLoc,
1338 ASTTemplateArgsPtr TemplateArgsIn,
John McCall0ad16662009-10-29 08:12:44 +00001339 SourceLocation *TemplateArgSLs,
Douglas Gregora727cb92009-06-30 22:34:41 +00001340 SourceLocation RAngleLoc) {
1341 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00001342
Douglas Gregora727cb92009-06-30 22:34:41 +00001343 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00001344 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
1345 translateTemplateArguments(TemplateArgsIn, TemplateArgSLs, TemplateArgs);
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001346 TemplateArgsIn.release();
Mike Stump11289f42009-09-09 15:08:12 +00001347
Douglas Gregord019ff62009-10-22 17:20:55 +00001348 return BuildTemplateIdExpr((NestedNameSpecifier *)SS.getScopeRep(),
1349 SS.getRange(),
1350 Template, TemplateNameLoc, LAngleLoc,
Douglas Gregora727cb92009-06-30 22:34:41 +00001351 TemplateArgs.data(), TemplateArgs.size(),
1352 RAngleLoc);
1353}
1354
Douglas Gregorb67535d2009-03-31 00:43:58 +00001355/// \brief Form a dependent template name.
1356///
1357/// This action forms a dependent template name given the template
1358/// name and its (presumably dependent) scope specifier. For
1359/// example, given "MetaFun::template apply", the scope specifier \p
1360/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1361/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001362Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001363Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001364 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001365 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001366 TypeTy *ObjectType) {
Mike Stump11289f42009-09-09 15:08:12 +00001367 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001368 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
1369 (SS.isSet() && computeDeclContext(SS, false))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001370 // C++0x [temp.names]p5:
1371 // If a name prefixed by the keyword template is not the name of
1372 // a template, the program is ill-formed. [Note: the keyword
1373 // template may not be applied to non-template members of class
1374 // templates. -end note ] [ Note: as is the case with the
1375 // typename prefix, the template prefix is allowed in cases
1376 // where it is not strictly necessary; i.e., when the
1377 // nested-name-specifier or the expression on the left of the ->
1378 // or . is not dependent on a template-parameter, or the use
1379 // does not appear in the scope of a template. -end note]
1380 //
1381 // Note: C++03 was more strict here, because it banned the use of
1382 // the "template" keyword prior to a template-name that was not a
1383 // dependent name. C++ DR468 relaxed this requirement (the
1384 // "template" keyword is now permitted). We follow the C++0x
1385 // rules, even in C++03 mode, retroactively applying the DR.
1386 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001387 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001388 false, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001389 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001390 Diag(Name.getSourceRange().getBegin(),
1391 diag::err_template_kw_refers_to_non_template)
1392 << GetNameFromUnqualifiedId(Name)
1393 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001394 return TemplateTy();
1395 }
1396
1397 return Template;
1398 }
1399
Mike Stump11289f42009-09-09 15:08:12 +00001400 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001401 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001402
1403 switch (Name.getKind()) {
1404 case UnqualifiedId::IK_Identifier:
1405 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1406 Name.Identifier));
1407
1408 default:
1409 break;
1410 }
1411
1412 Diag(Name.getSourceRange().getBegin(),
1413 diag::err_template_kw_refers_to_non_template)
1414 << GetNameFromUnqualifiedId(Name)
1415 << Name.getSourceRange();
1416 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001417}
1418
Mike Stump11289f42009-09-09 15:08:12 +00001419bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001420 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001421 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001422 const TemplateArgument &Arg = AL.getArgument();
1423
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001424 // Check template type parameter.
1425 if (Arg.getKind() != TemplateArgument::Type) {
1426 // C++ [temp.arg.type]p1:
1427 // A template-argument for a template-parameter which is a
1428 // type shall be a type-id.
1429
1430 // We have a template type parameter but the template argument
1431 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001432 SourceRange SR = AL.getSourceRange();
1433 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001434 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001435
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001436 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001437 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001438
John McCall0ad16662009-10-29 08:12:44 +00001439 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001440 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001441
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001442 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001443 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001444 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001445 return false;
1446}
1447
Douglas Gregord32e0282009-02-09 23:23:08 +00001448/// \brief Check that the given template argument list is well-formed
1449/// for specializing the given template.
1450bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1451 SourceLocation TemplateLoc,
1452 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00001453 const TemplateArgumentLoc *TemplateArgs,
Douglas Gregorc40290e2009-03-09 23:48:35 +00001454 unsigned NumTemplateArgs,
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001455 SourceLocation RAngleLoc,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001456 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001457 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001458 TemplateParameterList *Params = Template->getTemplateParameters();
1459 unsigned NumParams = Params->size();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001460 unsigned NumArgs = NumTemplateArgs;
Douglas Gregord32e0282009-02-09 23:23:08 +00001461 bool Invalid = false;
1462
Mike Stump11289f42009-09-09 15:08:12 +00001463 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001464 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001465
Anders Carlsson15201f12009-06-13 02:08:00 +00001466 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001467 (NumArgs < Params->getMinRequiredArguments() &&
1468 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001469 // FIXME: point at either the first arg beyond what we can handle,
1470 // or the '>', depending on whether we have too many or too few
1471 // arguments.
1472 SourceRange Range;
1473 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001474 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001475 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1476 << (NumArgs > NumParams)
1477 << (isa<ClassTemplateDecl>(Template)? 0 :
1478 isa<FunctionTemplateDecl>(Template)? 1 :
1479 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
1480 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00001481 Diag(Template->getLocation(), diag::note_template_decl_here)
1482 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00001483 Invalid = true;
1484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
1486 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00001487 // [...] The type and form of each template-argument specified in
1488 // a template-id shall match the type and form specified for the
1489 // corresponding parameter declared by the template in its
1490 // template-parameter-list.
1491 unsigned ArgIdx = 0;
1492 for (TemplateParameterList::iterator Param = Params->begin(),
1493 ParamEnd = Params->end();
1494 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00001495 if (ArgIdx > NumArgs && PartialTemplateArgs)
1496 break;
Mike Stump11289f42009-09-09 15:08:12 +00001497
Douglas Gregord32e0282009-02-09 23:23:08 +00001498 // Decode the template argument
John McCall0ad16662009-10-29 08:12:44 +00001499 TemplateArgumentLoc Arg;
1500
Douglas Gregord32e0282009-02-09 23:23:08 +00001501 if (ArgIdx >= NumArgs) {
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001502 // Retrieve the default template argument from the template
1503 // parameter.
1504 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001505 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001506 // We have an empty argument pack.
1507 Converted.BeginPack();
1508 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001509 break;
1510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001512 if (!TTP->hasDefaultArgument())
1513 break;
1514
John McCall0ad16662009-10-29 08:12:44 +00001515 DeclaratorInfo *ArgType = TTP->getDefaultArgumentInfo();
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001516
1517 // If the argument type is dependent, instantiate it now based
1518 // on the previously-computed template arguments.
John McCall0ad16662009-10-29 08:12:44 +00001519 if (ArgType->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001520 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001521 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001522 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001523 SourceRange(TemplateLoc, RAngleLoc));
Douglas Gregord002c7b2009-05-11 23:53:27 +00001524
Anders Carlssonc8e71132009-06-05 04:47:51 +00001525 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001526 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001527 ArgType = SubstType(ArgType,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001528 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001529 TTP->getDefaultArgumentLoc(),
1530 TTP->getDeclName());
Douglas Gregor79cf6032009-03-10 20:44:00 +00001531 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001532
John McCall0ad16662009-10-29 08:12:44 +00001533 if (!ArgType)
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001534 return true;
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001535
John McCall0ad16662009-10-29 08:12:44 +00001536 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00001537 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001538 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1539 if (!NTTP->hasDefaultArgument())
1540 break;
1541
Mike Stump11289f42009-09-09 15:08:12 +00001542 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001543 Template, Converted.getFlatArguments(),
Anders Carlsson40ed3442009-06-11 16:06:49 +00001544 Converted.flatSize(),
1545 SourceRange(TemplateLoc, RAngleLoc));
Mike Stump11289f42009-09-09 15:08:12 +00001546
Anders Carlsson40ed3442009-06-11 16:06:49 +00001547 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001548 /*TakeArgs=*/false);
Anders Carlsson40ed3442009-06-11 16:06:49 +00001549
Mike Stump11289f42009-09-09 15:08:12 +00001550 Sema::OwningExprResult E
1551 = SubstExpr(NTTP->getDefaultArgument(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00001552 MultiLevelTemplateArgumentList(TemplateArgs));
Anders Carlsson40ed3442009-06-11 16:06:49 +00001553 if (E.isInvalid())
1554 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001555
John McCall0ad16662009-10-29 08:12:44 +00001556 Expr *Ex = E.takeAs<Expr>();
1557 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001558 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001559 TemplateTemplateParmDecl *TempParm
1560 = cast<TemplateTemplateParmDecl>(*Param);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001561
1562 if (!TempParm->hasDefaultArgument())
1563 break;
1564
John McCall76d824f2009-08-25 22:02:44 +00001565 // FIXME: Subst default argument
John McCall0d07eb32009-10-29 18:45:58 +00001566 Arg = TemplateArgumentLoc(TemplateArgument(TempParm->getDefaultArgument()),
1567 TempParm->getDefaultArgument());
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001568 }
1569 } else {
1570 // Retrieve the template argument produced by the user.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001571 Arg = TemplateArgs[ArgIdx];
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001572 }
1573
Douglas Gregord32e0282009-02-09 23:23:08 +00001574
1575 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Anders Carlsson15201f12009-06-13 02:08:00 +00001576 if (TTP->isParameterPack()) {
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001577 Converted.BeginPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001578 // Check all the remaining arguments (if any).
1579 for (; ArgIdx < NumArgs; ++ArgIdx) {
1580 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
1581 Invalid = true;
1582 }
Mike Stump11289f42009-09-09 15:08:12 +00001583
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001584 Converted.EndPack();
Anders Carlsson15201f12009-06-13 02:08:00 +00001585 } else {
1586 if (CheckTemplateTypeArgument(TTP, Arg, Converted))
1587 Invalid = true;
1588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589 } else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord32e0282009-02-09 23:23:08 +00001590 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
1591 // Check non-type template parameters.
Douglas Gregor463421d2009-03-03 04:44:36 +00001592
John McCall76d824f2009-08-25 22:02:44 +00001593 // Do substitution on the type of the non-type template parameter
1594 // with the template arguments we've seen thus far.
Douglas Gregor463421d2009-03-03 04:44:36 +00001595 QualType NTTPType = NTTP->getType();
1596 if (NTTPType->isDependentType()) {
John McCall76d824f2009-08-25 22:02:44 +00001597 // Do substitution on the type of the non-type template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001598 InstantiatingTemplate Inst(*this, TemplateLoc,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001599 Template, Converted.getFlatArguments(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001600 Converted.flatSize(),
Douglas Gregor79cf6032009-03-10 20:44:00 +00001601 SourceRange(TemplateLoc, RAngleLoc));
1602
Anders Carlssonc8e71132009-06-05 04:47:51 +00001603 TemplateArgumentList TemplateArgs(Context, Converted,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001604 /*TakeArgs=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001605 NTTPType = SubstType(NTTPType,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001606 MultiLevelTemplateArgumentList(TemplateArgs),
John McCall76d824f2009-08-25 22:02:44 +00001607 NTTP->getLocation(),
1608 NTTP->getDeclName());
Douglas Gregor463421d2009-03-03 04:44:36 +00001609 // If that worked, check the non-type template parameter type
1610 // for validity.
1611 if (!NTTPType.isNull())
Mike Stump11289f42009-09-09 15:08:12 +00001612 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
Douglas Gregor463421d2009-03-03 04:44:36 +00001613 NTTP->getLocation());
Douglas Gregor463421d2009-03-03 04:44:36 +00001614 if (NTTPType.isNull()) {
1615 Invalid = true;
1616 break;
1617 }
1618 }
1619
John McCall0ad16662009-10-29 08:12:44 +00001620 switch (Arg.getArgument().getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001621 case TemplateArgument::Null:
1622 assert(false && "Should never see a NULL template argument here");
1623 break;
Mike Stump11289f42009-09-09 15:08:12 +00001624
Douglas Gregorc40290e2009-03-09 23:48:35 +00001625 case TemplateArgument::Expression: {
John McCall0ad16662009-10-29 08:12:44 +00001626 Expr *E = Arg.getArgument().getAsExpr();
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001627 TemplateArgument Result;
1628 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
Douglas Gregord32e0282009-02-09 23:23:08 +00001629 Invalid = true;
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001630 else
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001631 Converted.Append(Result);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001632 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001633 }
1634
Douglas Gregorc40290e2009-03-09 23:48:35 +00001635 case TemplateArgument::Declaration:
1636 case TemplateArgument::Integral:
1637 // We've already checked this template argument, so just copy
1638 // it to the list of converted arguments.
John McCall0ad16662009-10-29 08:12:44 +00001639 Converted.Append(Arg.getArgument());
Douglas Gregorc40290e2009-03-09 23:48:35 +00001640 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001641
John McCall0ad16662009-10-29 08:12:44 +00001642 case TemplateArgument::Type: {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001643 // We have a non-type template parameter but the template
1644 // argument is a type.
Mike Stump11289f42009-09-09 15:08:12 +00001645
Douglas Gregorc40290e2009-03-09 23:48:35 +00001646 // C++ [temp.arg]p2:
1647 // In a template-argument, an ambiguity between a type-id and
1648 // an expression is resolved to a type-id, regardless of the
1649 // form of the corresponding template-parameter.
1650 //
1651 // We warn specifically about this case, since it can be rather
1652 // confusing for users.
John McCall0ad16662009-10-29 08:12:44 +00001653 QualType T = Arg.getArgument().getAsType();
John McCall0d07eb32009-10-29 18:45:58 +00001654 SourceRange SR = Arg.getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00001655 if (T->isFunctionType())
John McCall0d07eb32009-10-29 18:45:58 +00001656 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig)
1657 << SR << T;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001658 else
John McCall0d07eb32009-10-29 18:45:58 +00001659 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001660 Diag((*Param)->getLocation(), diag::note_template_param_here);
1661 Invalid = true;
Anders Carlssonbc343912009-06-15 17:04:53 +00001662 break;
John McCall0ad16662009-10-29 08:12:44 +00001663 }
Mike Stump11289f42009-09-09 15:08:12 +00001664
Anders Carlssonbc343912009-06-15 17:04:53 +00001665 case TemplateArgument::Pack:
1666 assert(0 && "FIXME: Implement!");
1667 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001668 }
Mike Stump11289f42009-09-09 15:08:12 +00001669 } else {
Douglas Gregord32e0282009-02-09 23:23:08 +00001670 // Check template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001671 TemplateTemplateParmDecl *TempParm
Douglas Gregord32e0282009-02-09 23:23:08 +00001672 = cast<TemplateTemplateParmDecl>(*Param);
Mike Stump11289f42009-09-09 15:08:12 +00001673
John McCall0ad16662009-10-29 08:12:44 +00001674 switch (Arg.getArgument().getKind()) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001675 case TemplateArgument::Null:
1676 assert(false && "Should never see a NULL template argument here");
1677 break;
Mike Stump11289f42009-09-09 15:08:12 +00001678
Douglas Gregorc40290e2009-03-09 23:48:35 +00001679 case TemplateArgument::Expression: {
John McCall0ad16662009-10-29 08:12:44 +00001680 Expr *ArgExpr = Arg.getArgument().getAsExpr();
Douglas Gregorc40290e2009-03-09 23:48:35 +00001681 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
1682 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
1683 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
1684 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001685
Douglas Gregorc40290e2009-03-09 23:48:35 +00001686 // Add the converted template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001687 Decl *D
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001688 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl();
John McCall0ad16662009-10-29 08:12:44 +00001689 Converted.Append(TemplateArgument(D));
Douglas Gregorc40290e2009-03-09 23:48:35 +00001690 continue;
1691 }
1692 }
1693 // fall through
Mike Stump11289f42009-09-09 15:08:12 +00001694
Douglas Gregorc40290e2009-03-09 23:48:35 +00001695 case TemplateArgument::Type: {
1696 // We have a template template parameter but the template
1697 // argument does not refer to a template.
1698 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1699 Invalid = true;
1700 break;
Douglas Gregord32e0282009-02-09 23:23:08 +00001701 }
1702
Douglas Gregorc40290e2009-03-09 23:48:35 +00001703 case TemplateArgument::Declaration:
1704 // We've already checked this template argument, so just copy
1705 // it to the list of converted arguments.
John McCall0ad16662009-10-29 08:12:44 +00001706 Converted.Append(Arg.getArgument());
Douglas Gregorc40290e2009-03-09 23:48:35 +00001707 break;
Mike Stump11289f42009-09-09 15:08:12 +00001708
Douglas Gregorc40290e2009-03-09 23:48:35 +00001709 case TemplateArgument::Integral:
1710 assert(false && "Integral argument with template template parameter");
1711 break;
Mike Stump11289f42009-09-09 15:08:12 +00001712
Anders Carlssonbc343912009-06-15 17:04:53 +00001713 case TemplateArgument::Pack:
1714 assert(0 && "FIXME: Implement!");
1715 break;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001716 }
Douglas Gregord32e0282009-02-09 23:23:08 +00001717 }
1718 }
1719
1720 return Invalid;
1721}
1722
1723/// \brief Check a template argument against its corresponding
1724/// template type parameter.
1725///
1726/// This routine implements the semantics of C++ [temp.arg.type]. It
1727/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001728bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001729 DeclaratorInfo *ArgInfo) {
1730 assert(ArgInfo && "invalid DeclaratorInfo");
1731 QualType Arg = ArgInfo->getType();
1732
Douglas Gregord32e0282009-02-09 23:23:08 +00001733 // C++ [temp.arg.type]p2:
1734 // A local type, a type with no linkage, an unnamed type or a type
1735 // compounded from any of these types shall not be used as a
1736 // template-argument for a template type-parameter.
1737 //
1738 // FIXME: Perform the recursive and no-linkage type checks.
1739 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00001740 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001741 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001742 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00001743 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00001744 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
1745 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1746 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
1747 << QualType(Tag, 0) << SR;
1748 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00001749 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00001750 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
1751 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00001752 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
1753 return true;
1754 }
1755
1756 return false;
1757}
1758
Douglas Gregorccb07762009-02-11 19:52:55 +00001759/// \brief Checks whether the given template argument is the address
1760/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001761bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
1762 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001763 bool Invalid = false;
1764
1765 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001766 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001767 Arg = Cast->getSubExpr();
1768
Sebastian Redl576fd422009-05-10 18:38:11 +00001769 // C++0x allows nullptr, and there's no further checking to be done for that.
1770 if (Arg->getType()->isNullPtrType())
1771 return false;
1772
Douglas Gregorccb07762009-02-11 19:52:55 +00001773 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001774 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001775 // A template-argument for a non-type, non-template
1776 // template-parameter shall be one of: [...]
1777 //
1778 // -- the address of an object or function with external
1779 // linkage, including function templates and function
1780 // template-ids but excluding non-static class members,
1781 // expressed as & id-expression where the & is optional if
1782 // the name refers to a function or array, or if the
1783 // corresponding template-parameter is a reference; or
1784 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001785
Douglas Gregorccb07762009-02-11 19:52:55 +00001786 // Ignore (and complain about) any excess parentheses.
1787 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1788 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001789 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001790 diag::err_template_arg_extra_parens)
1791 << Arg->getSourceRange();
1792 Invalid = true;
1793 }
1794
1795 Arg = Parens->getSubExpr();
1796 }
1797
1798 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
1799 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
1800 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1801 } else
1802 DRE = dyn_cast<DeclRefExpr>(Arg);
1803
1804 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00001805 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001806 diag::err_template_arg_not_object_or_func_form)
1807 << Arg->getSourceRange();
1808
1809 // Cannot refer to non-static data members
1810 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
1811 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
1812 << Field << Arg->getSourceRange();
1813
1814 // Cannot refer to non-static member functions
1815 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
1816 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00001817 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001818 diag::err_template_arg_method)
1819 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001820
Douglas Gregorccb07762009-02-11 19:52:55 +00001821 // Functions must have external linkage.
1822 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1823 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00001824 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001825 diag::err_template_arg_function_not_extern)
1826 << Func << Arg->getSourceRange();
1827 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
1828 << true;
1829 return true;
1830 }
1831
1832 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001833 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00001834 return Invalid;
1835 }
1836
1837 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
1838 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00001839 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001840 diag::err_template_arg_object_not_extern)
1841 << Var << Arg->getSourceRange();
1842 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
1843 << true;
1844 return true;
1845 }
1846
1847 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001848 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00001849 return Invalid;
1850 }
Mike Stump11289f42009-09-09 15:08:12 +00001851
Douglas Gregorccb07762009-02-11 19:52:55 +00001852 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001853 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001854 diag::err_template_arg_not_object_or_func)
1855 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001856 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001857 diag::note_template_arg_refers_here);
1858 return true;
1859}
1860
1861/// \brief Checks whether the given template argument is a pointer to
1862/// member constant according to C++ [temp.arg.nontype]p1.
Mike Stump11289f42009-09-09 15:08:12 +00001863bool
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001864Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
Douglas Gregorccb07762009-02-11 19:52:55 +00001865 bool Invalid = false;
1866
1867 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001868 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00001869 Arg = Cast->getSubExpr();
1870
Sebastian Redl576fd422009-05-10 18:38:11 +00001871 // C++0x allows nullptr, and there's no further checking to be done for that.
1872 if (Arg->getType()->isNullPtrType())
1873 return false;
1874
Douglas Gregorccb07762009-02-11 19:52:55 +00001875 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00001876 //
Douglas Gregorccb07762009-02-11 19:52:55 +00001877 // A template-argument for a non-type, non-template
1878 // template-parameter shall be one of: [...]
1879 //
1880 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00001881 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00001882
1883 // Ignore (and complain about) any excess parentheses.
1884 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
1885 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00001886 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001887 diag::err_template_arg_extra_parens)
1888 << Arg->getSourceRange();
1889 Invalid = true;
1890 }
1891
1892 Arg = Parens->getSubExpr();
1893 }
1894
1895 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00001896 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
1897 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
1898 if (DRE && !DRE->getQualifier())
1899 DRE = 0;
1900 }
Douglas Gregorccb07762009-02-11 19:52:55 +00001901
1902 if (!DRE)
1903 return Diag(Arg->getSourceRange().getBegin(),
1904 diag::err_template_arg_not_pointer_to_member_form)
1905 << Arg->getSourceRange();
1906
1907 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
1908 assert((isa<FieldDecl>(DRE->getDecl()) ||
1909 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
1910 "Only non-static member pointers can make it here");
1911
1912 // Okay: this is the address of a non-static member, and therefore
1913 // a member pointer constant.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001914 Member = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00001915 return Invalid;
1916 }
1917
1918 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00001919 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001920 diag::err_template_arg_not_pointer_to_member_form)
1921 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001922 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00001923 diag::note_template_arg_refers_here);
1924 return true;
1925}
1926
Douglas Gregord32e0282009-02-09 23:23:08 +00001927/// \brief Check a template argument against its corresponding
1928/// non-type template parameter.
1929///
Douglas Gregor463421d2009-03-03 04:44:36 +00001930/// This routine implements the semantics of C++ [temp.arg.nontype].
1931/// It returns true if an error occurred, and false otherwise. \p
1932/// InstantiatedParamType is the type of the non-type template
1933/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001934///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001935/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00001936bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00001937 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001938 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001939 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
1940
Douglas Gregor86560402009-02-10 23:36:10 +00001941 // If either the parameter has a dependent type or the argument is
1942 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001943 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00001944 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
1945 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00001946 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00001947 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001948 }
Douglas Gregor86560402009-02-10 23:36:10 +00001949
1950 // C++ [temp.arg.nontype]p5:
1951 // The following conversions are performed on each expression used
1952 // as a non-type template-argument. If a non-type
1953 // template-argument cannot be converted to the type of the
1954 // corresponding template-parameter then the program is
1955 // ill-formed.
1956 //
1957 // -- for a non-type template-parameter of integral or
1958 // enumeration type, integral promotions (4.5) and integral
1959 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00001960 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00001961 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00001962 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00001963 // C++ [temp.arg.nontype]p1:
1964 // A template-argument for a non-type, non-template
1965 // template-parameter shall be one of:
1966 //
1967 // -- an integral constant-expression of integral or enumeration
1968 // type; or
1969 // -- the name of a non-type template-parameter; or
1970 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001971 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00001972 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001973 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00001974 diag::err_template_arg_not_integral_or_enumeral)
1975 << ArgType << Arg->getSourceRange();
1976 Diag(Param->getLocation(), diag::note_template_param_here);
1977 return true;
1978 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00001979 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00001980 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
1981 << ArgType << Arg->getSourceRange();
1982 return true;
1983 }
1984
1985 // FIXME: We need some way to more easily get the unqualified form
1986 // of the types without going all the way to the
1987 // canonical type.
1988 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
1989 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
1990 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
1991 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
1992
1993 // Try to convert the argument to the parameter's type.
1994 if (ParamType == ArgType) {
1995 // Okay: no conversion necessary
1996 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
1997 !ParamType->isEnumeralType()) {
1998 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00001999 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002000 } else {
2001 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002002 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002003 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002004 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002005 Diag(Param->getLocation(), diag::note_template_param_here);
2006 return true;
2007 }
2008
Douglas Gregor52aba872009-03-14 00:20:21 +00002009 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002010 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002011 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002012
2013 if (!Arg->isValueDependent()) {
2014 // Check that an unsigned parameter does not receive a negative
2015 // value.
2016 if (IntegerType->isUnsignedIntegerType()
2017 && (Value.isSigned() && Value.isNegative())) {
2018 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2019 << Value.toString(10) << Param->getType()
2020 << Arg->getSourceRange();
2021 Diag(Param->getLocation(), diag::note_template_param_here);
2022 return true;
2023 }
2024
2025 // Check that we don't overflow the template parameter type.
2026 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2027 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002028 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002029 diag::err_template_arg_too_large)
2030 << Value.toString(10) << Param->getType()
2031 << Arg->getSourceRange();
2032 Diag(Param->getLocation(), diag::note_template_param_here);
2033 return true;
2034 }
2035
2036 if (Value.getBitWidth() != AllowedBits)
2037 Value.extOrTrunc(AllowedBits);
2038 Value.setIsSigned(IntegerType->isSignedIntegerType());
2039 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002040
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002041 // Add the value of this argument to the list of converted
2042 // arguments. We use the bitwidth and signedness of the template
2043 // parameter.
2044 if (Arg->isValueDependent()) {
2045 // The argument is value-dependent. Create a new
2046 // TemplateArgument with the converted expression.
2047 Converted = TemplateArgument(Arg);
2048 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002049 }
2050
John McCall0ad16662009-10-29 08:12:44 +00002051 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002052 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002053 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002054 return false;
2055 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002056
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002057 // Handle pointer-to-function, reference-to-function, and
2058 // pointer-to-member-function all in (roughly) the same way.
2059 if (// -- For a non-type template-parameter of type pointer to
2060 // function, only the function-to-pointer conversion (4.3) is
2061 // applied. If the template-argument represents a set of
2062 // overloaded functions (or a pointer to such), the matching
2063 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002064 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002065 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002066 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002067 // -- For a non-type template-parameter of type reference to
2068 // function, no conversions apply. If the template-argument
2069 // represents a set of overloaded functions, the matching
2070 // function is selected from the set (13.4).
2071 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002072 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002073 // -- For a non-type template-parameter of type pointer to
2074 // member function, no conversions apply. If the
2075 // template-argument represents a set of overloaded member
2076 // functions, the matching member function is selected from
2077 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002078 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002079 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002080 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002081 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002082 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002083 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002084 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002085 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2086 ParamType->isMemberPointerType())) {
2087 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002088 if (ParamType->isMemberPointerType())
2089 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2090 else
2091 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002092 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002093 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002094 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002095 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002096 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002097 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2098 return true;
2099
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002100 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002101 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002102 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002103 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002104 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002105 }
2106 }
2107
Mike Stump11289f42009-09-09 15:08:12 +00002108 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002109 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002110 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002111 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002112 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002113 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002114 Diag(Param->getLocation(), diag::note_template_param_here);
2115 return true;
2116 }
Mike Stump11289f42009-09-09 15:08:12 +00002117
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002118 if (ParamType->isMemberPointerType()) {
2119 NamedDecl *Member = 0;
2120 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2121 return true;
2122
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002123 if (Member)
2124 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002125 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002126 return false;
2127 }
Mike Stump11289f42009-09-09 15:08:12 +00002128
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002129 NamedDecl *Entity = 0;
2130 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2131 return true;
2132
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002133 if (Entity)
2134 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002135 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002136 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002137 }
2138
Chris Lattner696197c2009-02-20 21:37:53 +00002139 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002140 // -- for a non-type template-parameter of type pointer to
2141 // object, qualification conversions (4.4) and the
2142 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002143 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002144 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002145 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002146
Sebastian Redl576fd422009-05-10 18:38:11 +00002147 if (ArgType->isNullPtrType()) {
2148 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002149 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002150 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002151 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002152 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002153 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002154
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002155 if (IsQualificationConversion(ArgType, ParamType)) {
2156 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002157 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002158 }
Mike Stump11289f42009-09-09 15:08:12 +00002159
Douglas Gregor1515f762009-02-11 18:22:40 +00002160 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002161 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002162 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002163 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002164 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002165 Diag(Param->getLocation(), diag::note_template_param_here);
2166 return true;
2167 }
Mike Stump11289f42009-09-09 15:08:12 +00002168
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002169 NamedDecl *Entity = 0;
2170 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2171 return true;
2172
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002173 if (Entity)
2174 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002175 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002176 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002177 }
Mike Stump11289f42009-09-09 15:08:12 +00002178
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002179 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002180 // -- For a non-type template-parameter of type reference to
2181 // object, no conversions apply. The type referred to by the
2182 // reference may be more cv-qualified than the (otherwise
2183 // identical) type of the template-argument. The
2184 // template-parameter is bound directly to the
2185 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002186 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002187 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002188
Douglas Gregor1515f762009-02-11 18:22:40 +00002189 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002190 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002191 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002192 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002193 << Arg->getSourceRange();
2194 Diag(Param->getLocation(), diag::note_template_param_here);
2195 return true;
2196 }
2197
Mike Stump11289f42009-09-09 15:08:12 +00002198 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002199 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2200 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002201
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002202 if ((ParamQuals | ArgQuals) != ParamQuals) {
2203 Diag(Arg->getSourceRange().getBegin(),
2204 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002205 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002206 << Arg->getSourceRange();
2207 Diag(Param->getLocation(), diag::note_template_param_here);
2208 return true;
2209 }
Mike Stump11289f42009-09-09 15:08:12 +00002210
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002211 NamedDecl *Entity = 0;
2212 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2213 return true;
2214
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002215 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002216 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002217 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002218 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002219
2220 // -- For a non-type template-parameter of type pointer to data
2221 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002222 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002223 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2224
Douglas Gregor1515f762009-02-11 18:22:40 +00002225 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002226 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002227 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002228 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002229 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002230 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002231 } else {
2232 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002233 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002234 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002235 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002236 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002237 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002238 }
2239
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002240 NamedDecl *Member = 0;
2241 if (CheckTemplateArgumentPointerToMember(Arg, Member))
2242 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002243
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002244 if (Member)
2245 Member = cast<NamedDecl>(Member->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002246 Converted = TemplateArgument(Member);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002247 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00002248}
2249
2250/// \brief Check a template argument against its corresponding
2251/// template template parameter.
2252///
2253/// This routine implements the semantics of C++ [temp.arg.template].
2254/// It returns true if an error occurred, and false otherwise.
2255bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
2256 DeclRefExpr *Arg) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002257 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
2258 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
2259
2260 // C++ [temp.arg.template]p1:
2261 // A template-argument for a template template-parameter shall be
2262 // the name of a class template, expressed as id-expression. Only
2263 // primary class templates are considered when matching the
2264 // template template argument with the corresponding parameter;
2265 // partial specializations are not considered even if their
2266 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002267 //
2268 // Note that we also allow template template parameters here, which
2269 // will happen when we are dealing with, e.g., class template
2270 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002271 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002272 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002273 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002274 "Only function templates are possible here");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002275 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template);
2276 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002277 << Template;
2278 }
2279
2280 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2281 Param->getTemplateParameters(),
2282 true, true,
2283 Arg->getSourceRange().getBegin());
Douglas Gregord32e0282009-02-09 23:23:08 +00002284}
2285
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002286/// \brief Determine whether the given template parameter lists are
2287/// equivalent.
2288///
Mike Stump11289f42009-09-09 15:08:12 +00002289/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002290/// source code as part of a new template declaration.
2291///
2292/// \param Old The old template parameter list, typically found via
2293/// name lookup of the template declared with this template parameter
2294/// list.
2295///
2296/// \param Complain If true, this routine will produce a diagnostic if
2297/// the template parameter lists are not equivalent.
2298///
Douglas Gregor85e0f662009-02-10 00:24:35 +00002299/// \param IsTemplateTemplateParm If true, this routine is being
2300/// called to compare the template parameter lists of a template
2301/// template parameter.
2302///
2303/// \param TemplateArgLoc If this source location is valid, then we
2304/// are actually checking the template parameter list of a template
2305/// argument (New) against the template parameter list of its
2306/// corresponding template template parameter (Old). We produce
2307/// slightly different diagnostics in this scenario.
2308///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002309/// \returns True if the template parameter lists are equal, false
2310/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002311bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002312Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2313 TemplateParameterList *Old,
2314 bool Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002315 bool IsTemplateTemplateParm,
2316 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002317 if (Old->size() != New->size()) {
2318 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002319 unsigned NextDiag = diag::err_template_param_list_different_arity;
2320 if (TemplateArgLoc.isValid()) {
2321 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2322 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002323 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002324 Diag(New->getTemplateLoc(), NextDiag)
2325 << (New->size() > Old->size())
2326 << IsTemplateTemplateParm
2327 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002328 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
2329 << IsTemplateTemplateParm
2330 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2331 }
2332
2333 return false;
2334 }
2335
2336 for (TemplateParameterList::iterator OldParm = Old->begin(),
2337 OldParmEnd = Old->end(), NewParm = New->begin();
2338 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2339 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002340 if (Complain) {
2341 unsigned NextDiag = diag::err_template_param_different_kind;
2342 if (TemplateArgLoc.isValid()) {
2343 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2344 NextDiag = diag::note_template_param_different_kind;
2345 }
2346 Diag((*NewParm)->getLocation(), NextDiag)
2347 << IsTemplateTemplateParm;
2348 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
2349 << IsTemplateTemplateParm;
Douglas Gregor85e0f662009-02-10 00:24:35 +00002350 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002351 return false;
2352 }
2353
2354 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2355 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002356 // know we're at the same index).
2357#if 0
Mike Stump87c57ac2009-05-16 07:39:55 +00002358 // FIXME: Enable this code in debug mode *after* we properly go through
2359 // and "instantiate" the template parameter lists of template template
2360 // parameters. It's only after this instantiation that (1) any dependent
2361 // types within the template parameter list of the template template
2362 // parameter can be checked, and (2) the template type parameter depths
Douglas Gregor85e0f662009-02-10 00:24:35 +00002363 // will match up.
Mike Stump11289f42009-09-09 15:08:12 +00002364 QualType OldParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002365 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
Mike Stump11289f42009-09-09 15:08:12 +00002366 QualType NewParmType
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002367 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
Mike Stump11289f42009-09-09 15:08:12 +00002368 assert(Context.getCanonicalType(OldParmType) ==
2369 Context.getCanonicalType(NewParmType) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002370 "type parameter mismatch?");
2371#endif
Mike Stump11289f42009-09-09 15:08:12 +00002372 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002373 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2374 // The types of non-type template parameters must agree.
2375 NonTypeTemplateParmDecl *NewNTTP
2376 = cast<NonTypeTemplateParmDecl>(*NewParm);
2377 if (Context.getCanonicalType(OldNTTP->getType()) !=
2378 Context.getCanonicalType(NewNTTP->getType())) {
2379 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002380 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2381 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002382 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002383 diag::err_template_arg_template_params_mismatch);
2384 NextDiag = diag::note_template_nontype_parm_different_type;
2385 }
2386 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002387 << NewNTTP->getType()
2388 << IsTemplateTemplateParm;
Mike Stump11289f42009-09-09 15:08:12 +00002389 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002390 diag::note_template_nontype_parm_prev_declaration)
2391 << OldNTTP->getType();
2392 }
2393 return false;
2394 }
2395 } else {
2396 // The template parameter lists of template template
2397 // parameters must agree.
2398 // FIXME: Could we perform a faster "type" comparison here?
Mike Stump11289f42009-09-09 15:08:12 +00002399 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002400 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002401 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002402 = cast<TemplateTemplateParmDecl>(*OldParm);
2403 TemplateTemplateParmDecl *NewTTP
2404 = cast<TemplateTemplateParmDecl>(*NewParm);
2405 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2406 OldTTP->getTemplateParameters(),
2407 Complain,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002408 /*IsTemplateTemplateParm=*/true,
2409 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002410 return false;
2411 }
2412 }
2413
2414 return true;
2415}
2416
2417/// \brief Check whether a template can be declared within this scope.
2418///
2419/// If the template declaration is valid in this scope, returns
2420/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002421bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002422Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002423 // Find the nearest enclosing declaration scope.
2424 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2425 (S->getFlags() & Scope::TemplateParamScope) != 0)
2426 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002427
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002428 // C++ [temp]p2:
2429 // A template-declaration can appear only as a namespace scope or
2430 // class scope declaration.
2431 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002432 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2433 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002434 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002435 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002436
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002437 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002438 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002439
2440 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2441 return false;
2442
Mike Stump11289f42009-09-09 15:08:12 +00002443 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002444 diag::err_template_outside_namespace_or_class_scope)
2445 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002446}
Douglas Gregor67a65642009-02-17 23:15:12 +00002447
Douglas Gregor54888652009-10-07 00:13:32 +00002448/// \brief Determine what kind of template specialization the given declaration
2449/// is.
2450static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2451 if (!D)
2452 return TSK_Undeclared;
2453
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002454 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2455 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002456 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2457 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002458 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2459 return Var->getTemplateSpecializationKind();
2460
Douglas Gregor54888652009-10-07 00:13:32 +00002461 return TSK_Undeclared;
2462}
2463
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002464/// \brief Check whether a specialization is well-formed in the current
2465/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002466///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002467/// This routine determines whether a template specialization can be declared
2468/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002469///
2470/// \param S the semantic analysis object for which this check is being
2471/// performed.
2472///
2473/// \param Specialized the entity being specialized or instantiated, which
2474/// may be a kind of template (class template, function template, etc.) or
2475/// a member of a class template (member function, static data member,
2476/// member class).
2477///
2478/// \param PrevDecl the previous declaration of this entity, if any.
2479///
2480/// \param Loc the location of the explicit specialization or instantiation of
2481/// this entity.
2482///
2483/// \param IsPartialSpecialization whether this is a partial specialization of
2484/// a class template.
2485///
Douglas Gregor54888652009-10-07 00:13:32 +00002486/// \returns true if there was an error that we cannot recover from, false
2487/// otherwise.
2488static bool CheckTemplateSpecializationScope(Sema &S,
2489 NamedDecl *Specialized,
2490 NamedDecl *PrevDecl,
2491 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002492 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002493 // Keep these "kind" numbers in sync with the %select statements in the
2494 // various diagnostics emitted by this routine.
2495 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002496 bool isTemplateSpecialization = false;
2497 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002498 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002499 isTemplateSpecialization = true;
2500 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002501 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002502 isTemplateSpecialization = true;
2503 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002504 EntityKind = 3;
2505 else if (isa<VarDecl>(Specialized))
2506 EntityKind = 4;
2507 else if (isa<RecordDecl>(Specialized))
2508 EntityKind = 5;
2509 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002510 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2511 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002512 return true;
2513 }
2514
Douglas Gregorf47b9112009-02-25 22:02:03 +00002515 // C++ [temp.expl.spec]p2:
2516 // An explicit specialization shall be declared in the namespace
2517 // of which the template is a member, or, for member templates, in
2518 // the namespace of which the enclosing class or enclosing class
2519 // template is a member. An explicit specialization of a member
2520 // function, member class or static data member of a class
2521 // template shall be declared in the namespace of which the class
2522 // template is a member. Such a declaration may also be a
2523 // definition. If the declaration is not a definition, the
2524 // specialization may be defined later in the name- space in which
2525 // the explicit specialization was declared, or in a namespace
2526 // that encloses the one in which the explicit specialization was
2527 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002528 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2529 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002530 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002531 return true;
2532 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002533
Douglas Gregor40fb7442009-10-07 17:30:37 +00002534 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2535 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002536 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002537 return true;
2538 }
2539
Douglas Gregore4b05162009-10-07 17:21:34 +00002540 // C++ [temp.class.spec]p6:
2541 // A class template partial specialization may be declared or redeclared
2542 // in any namespace scope in which its definition may be defined (14.5.1
2543 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002544 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002545 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002546 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002547 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002548 if ((!PrevDecl ||
2549 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2550 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2551 // There is no prior declaration of this entity, so this
2552 // specialization must be in the same context as the template
2553 // itself.
2554 if (!DC->Equals(SpecializedContext)) {
2555 if (isa<TranslationUnitDecl>(SpecializedContext))
2556 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2557 << EntityKind << Specialized;
2558 else if (isa<NamespaceDecl>(SpecializedContext))
2559 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2560 << EntityKind << Specialized
2561 << cast<NamedDecl>(SpecializedContext);
2562
2563 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2564 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002565 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002566 }
Douglas Gregor54888652009-10-07 00:13:32 +00002567
2568 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002569 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002570 // Note that HandleDeclarator() performs this check for explicit
2571 // specializations of function templates, static data members, and member
2572 // functions, so we skip the check here for those kinds of entities.
2573 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002574 // Should we refactor that check, so that it occurs later?
2575 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002576 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2577 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002578 if (isa<TranslationUnitDecl>(SpecializedContext))
2579 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2580 << EntityKind << Specialized;
2581 else if (isa<NamespaceDecl>(SpecializedContext))
2582 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2583 << EntityKind << Specialized
2584 << cast<NamedDecl>(SpecializedContext);
2585
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002586 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002587 }
Douglas Gregor54888652009-10-07 00:13:32 +00002588
2589 // FIXME: check for specialization-after-instantiation errors and such.
2590
Douglas Gregorf47b9112009-02-25 22:02:03 +00002591 return false;
2592}
Douglas Gregor54888652009-10-07 00:13:32 +00002593
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002594/// \brief Check the non-type template arguments of a class template
2595/// partial specialization according to C++ [temp.class.spec]p9.
2596///
Douglas Gregor09a30232009-06-12 22:08:06 +00002597/// \param TemplateParams the template parameters of the primary class
2598/// template.
2599///
2600/// \param TemplateArg the template arguments of the class template
2601/// partial specialization.
2602///
2603/// \param MirrorsPrimaryTemplate will be set true if the class
2604/// template partial specialization arguments are identical to the
2605/// implicit template arguments of the primary template. This is not
2606/// necessarily an error (C++0x), and it is left to the caller to diagnose
2607/// this condition when it is an error.
2608///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002609/// \returns true if there was an error, false otherwise.
2610bool Sema::CheckClassTemplatePartialSpecializationArgs(
2611 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002612 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00002613 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002614 // FIXME: the interface to this function will have to change to
2615 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00002616 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00002617
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002618 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00002619
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002620 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002621 // Determine whether the template argument list of the partial
2622 // specialization is identical to the implicit argument list of
2623 // the primary template. The caller may need to diagnostic this as
2624 // an error per C++ [temp.class.spec]p9b3.
2625 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00002626 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002627 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
2628 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00002629 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002630 MirrorsPrimaryTemplate = false;
2631 } else if (TemplateTemplateParmDecl *TTP
2632 = dyn_cast<TemplateTemplateParmDecl>(
2633 TemplateParams->getParam(I))) {
2634 // FIXME: We should settle on either Declaration storage or
2635 // Expression storage for template template parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002636 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor09a30232009-06-12 22:08:06 +00002637 = dyn_cast_or_null<TemplateTemplateParmDecl>(
Anders Carlsson40c1d492009-06-13 18:20:51 +00002638 ArgList[I].getAsDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00002639 if (!ArgDecl)
Mike Stump11289f42009-09-09 15:08:12 +00002640 if (DeclRefExpr *DRE
Anders Carlsson40c1d492009-06-13 18:20:51 +00002641 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr()))
Douglas Gregor09a30232009-06-12 22:08:06 +00002642 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
2643
2644 if (!ArgDecl ||
2645 ArgDecl->getIndex() != TTP->getIndex() ||
2646 ArgDecl->getDepth() != TTP->getDepth())
2647 MirrorsPrimaryTemplate = false;
2648 }
2649 }
2650
Mike Stump11289f42009-09-09 15:08:12 +00002651 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002652 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00002653 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002654 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002655 }
2656
Anders Carlsson40c1d492009-06-13 18:20:51 +00002657 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00002658 if (!ArgExpr) {
2659 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002660 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002661 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002662
2663 // C++ [temp.class.spec]p8:
2664 // A non-type argument is non-specialized if it is the name of a
2665 // non-type parameter. All other non-type arguments are
2666 // specialized.
2667 //
2668 // Below, we check the two conditions that only apply to
2669 // specialized non-type arguments, so skip any non-specialized
2670 // arguments.
2671 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00002672 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00002673 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00002674 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00002675 (Param->getIndex() != NTTP->getIndex() ||
2676 Param->getDepth() != NTTP->getDepth()))
2677 MirrorsPrimaryTemplate = false;
2678
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002679 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00002680 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002681
2682 // C++ [temp.class.spec]p9:
2683 // Within the argument list of a class template partial
2684 // specialization, the following restrictions apply:
2685 // -- A partially specialized non-type argument expression
2686 // shall not involve a template parameter of the partial
2687 // specialization except when the argument expression is a
2688 // simple identifier.
2689 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002690 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002691 diag::err_dependent_non_type_arg_in_partial_spec)
2692 << ArgExpr->getSourceRange();
2693 return true;
2694 }
2695
2696 // -- The type of a template parameter corresponding to a
2697 // specialized non-type argument shall not be dependent on a
2698 // parameter of the specialization.
2699 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002700 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002701 diag::err_dependent_typed_non_type_arg_in_partial_spec)
2702 << Param->getType()
2703 << ArgExpr->getSourceRange();
2704 Diag(Param->getLocation(), diag::note_template_param_here);
2705 return true;
2706 }
Douglas Gregor09a30232009-06-12 22:08:06 +00002707
2708 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002709 }
2710
2711 return false;
2712}
2713
Douglas Gregorc08f4892009-03-25 00:13:59 +00002714Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00002715Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
2716 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00002717 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00002718 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00002719 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00002720 SourceLocation TemplateNameLoc,
2721 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00002722 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00002723 SourceLocation *TemplateArgLocs,
2724 SourceLocation RAngleLoc,
2725 AttributeList *Attr,
2726 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00002727 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00002728
Douglas Gregor67a65642009-02-17 23:15:12 +00002729 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00002730 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00002731 ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002732 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
Douglas Gregor67a65642009-02-17 23:15:12 +00002733
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002734 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00002735 bool isPartialSpecialization = false;
2736
Douglas Gregorf47b9112009-02-25 22:02:03 +00002737 // Check the validity of the template headers that introduce this
2738 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00002739 // FIXME: We probably shouldn't complain about these headers for
2740 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002741 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00002742 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
2743 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002744 TemplateParameterLists.size(),
2745 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002746 if (TemplateParams && TemplateParams->size() > 0) {
2747 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002748
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002749 // C++ [temp.class.spec]p10:
2750 // The template parameter list of a specialization shall not
2751 // contain default template argument values.
2752 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2753 Decl *Param = TemplateParams->getParam(I);
2754 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
2755 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002756 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002757 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00002758 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002759 }
2760 } else if (NonTypeTemplateParmDecl *NTTP
2761 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2762 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002763 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002764 diag::err_default_arg_in_partial_spec)
2765 << DefArg->getSourceRange();
2766 NTTP->setDefaultArgument(0);
2767 DefArg->Destroy(Context);
2768 }
2769 } else {
2770 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
2771 if (Expr *DefArg = TTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00002772 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002773 diag::err_default_arg_in_partial_spec)
2774 << DefArg->getSourceRange();
2775 TTP->setDefaultArgument(0);
2776 DefArg->Destroy(Context);
Douglas Gregord5222052009-06-12 19:43:02 +00002777 }
2778 }
2779 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00002780 } else if (TemplateParams) {
2781 if (TUK == TUK_Friend)
2782 Diag(KWLoc, diag::err_template_spec_friend)
2783 << CodeModificationHint::CreateRemoval(
2784 SourceRange(TemplateParams->getTemplateLoc(),
2785 TemplateParams->getRAngleLoc()))
2786 << SourceRange(LAngleLoc, RAngleLoc);
2787 else
2788 isExplicitSpecialization = true;
2789 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002790 Diag(KWLoc, diag::err_template_spec_needs_header)
2791 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002792 isExplicitSpecialization = true;
2793 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002794
Douglas Gregor67a65642009-02-17 23:15:12 +00002795 // Check that the specialization uses the same tag kind as the
2796 // original template.
2797 TagDecl::TagKind Kind;
2798 switch (TagSpec) {
2799 default: assert(0 && "Unknown tag type!");
2800 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2801 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2802 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2803 }
Douglas Gregord9034f02009-05-14 16:41:31 +00002804 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00002805 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00002806 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00002807 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00002808 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00002809 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00002810 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00002811 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00002812 diag::note_previous_use);
2813 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
2814 }
2815
Douglas Gregorc40290e2009-03-09 23:48:35 +00002816 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00002817 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002818 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
2819
Douglas Gregor67a65642009-02-17 23:15:12 +00002820 // Check that the template argument list is well-formed for this
2821 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002822 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
2823 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00002824 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlsson40c1d492009-06-13 18:20:51 +00002825 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00002826 RAngleLoc, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002827 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00002828
Mike Stump11289f42009-09-09 15:08:12 +00002829 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00002830 ClassTemplate->getTemplateParameters()->size()) &&
2831 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00002832
Douglas Gregor2373c592009-05-31 09:31:02 +00002833 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00002834 // corresponds to these arguments.
2835 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00002836 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00002837 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002838 if (CheckClassTemplatePartialSpecializationArgs(
2839 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002840 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002841 return true;
2842
Douglas Gregor09a30232009-06-12 22:08:06 +00002843 if (MirrorsPrimaryTemplate) {
2844 // C++ [temp.class.spec]p9b3:
2845 //
Mike Stump11289f42009-09-09 15:08:12 +00002846 // -- The argument list of the specialization shall not be identical
2847 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00002848 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00002849 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00002850 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00002851 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00002852 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00002853 ClassTemplate->getIdentifier(),
2854 TemplateNameLoc,
2855 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002856 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00002857 AS_none);
2858 }
2859
Douglas Gregor2208a292009-09-26 20:57:03 +00002860 // FIXME: Diagnose friend partial specializations
2861
Douglas Gregor2373c592009-05-31 09:31:02 +00002862 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00002863 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002864 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002865 Converted.flatSize(),
2866 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002867 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002868 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002869 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00002870 Converted.flatSize(),
2871 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00002872 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002873 ClassTemplateSpecializationDecl *PrevDecl = 0;
2874
2875 if (isPartialSpecialization)
2876 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00002877 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00002878 InsertPos);
2879 else
2880 PrevDecl
2881 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00002882
2883 ClassTemplateSpecializationDecl *Specialization = 0;
2884
Douglas Gregorf47b9112009-02-25 22:02:03 +00002885 // Check whether we can declare a class template specialization in
2886 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00002887 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00002888 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002889 TemplateNameLoc,
2890 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00002891 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002892
Douglas Gregor15301382009-07-30 17:40:51 +00002893 // The canonical type
2894 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00002895 if (PrevDecl &&
2896 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
2897 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00002898 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00002899 // arguments was referenced but not declared, or we're only
2900 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00002901 // declaration node as our own, updating its source location to
2902 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002903 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00002904 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00002905 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00002906 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00002907 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00002908 // Build the canonical type that describes the converted template
2909 // arguments of the class template partial specialization.
2910 CanonType = Context.getTemplateSpecializationType(
2911 TemplateName(ClassTemplate),
2912 Converted.getFlatArguments(),
2913 Converted.flatSize());
2914
Douglas Gregor2373c592009-05-31 09:31:02 +00002915 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00002916 ClassTemplatePartialSpecializationDecl *PrevPartial
2917 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002918 ClassTemplatePartialSpecializationDecl *Partial
2919 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00002920 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002921 TemplateNameLoc,
2922 TemplateParams,
2923 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002924 Converted,
John McCall0ad16662009-10-29 08:12:44 +00002925 TemplateArgs.data(),
2926 TemplateArgs.size(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00002927 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00002928
2929 if (PrevPartial) {
2930 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
2931 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
2932 } else {
2933 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
2934 }
2935 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00002936
Douglas Gregor21610382009-10-29 00:04:11 +00002937 // If we are providing an explicit specialization of a member class
2938 // template specialization, make a note of that.
2939 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2940 PrevPartial->setMemberSpecialization();
2941
Douglas Gregor91772d12009-06-13 00:26:55 +00002942 // Check that all of the template parameters of the class template
2943 // partial specialization are deducible from the template
2944 // arguments. If not, this class template partial specialization
2945 // will never be used.
2946 llvm::SmallVector<bool, 8> DeducibleParams;
2947 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002948 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00002949 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002950 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00002951 unsigned NumNonDeducible = 0;
2952 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
2953 if (!DeducibleParams[I])
2954 ++NumNonDeducible;
2955
2956 if (NumNonDeducible) {
2957 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2958 << (NumNonDeducible > 1)
2959 << SourceRange(TemplateNameLoc, RAngleLoc);
2960 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2961 if (!DeducibleParams[I]) {
2962 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2963 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00002964 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002965 diag::note_partial_spec_unused_parameter)
2966 << Param->getDeclName();
2967 else
Mike Stump11289f42009-09-09 15:08:12 +00002968 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00002969 diag::note_partial_spec_unused_parameter)
2970 << std::string("<anonymous>");
2971 }
2972 }
2973 }
Douglas Gregor67a65642009-02-17 23:15:12 +00002974 } else {
2975 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00002976 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00002977 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00002978 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00002979 ClassTemplate->getDeclContext(),
2980 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002981 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00002982 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00002983 PrevDecl);
2984
2985 if (PrevDecl) {
2986 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
2987 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
2988 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002989 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00002990 InsertPos);
2991 }
Douglas Gregor15301382009-07-30 17:40:51 +00002992
2993 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00002994 }
2995
Douglas Gregor06db9f52009-10-12 20:18:28 +00002996 // C++ [temp.expl.spec]p6:
2997 // If a template, a member template or the member of a class template is
2998 // explicitly specialized then that specialization shall be declared
2999 // before the first use of that specialization that would cause an implicit
3000 // instantiation to take place, in every translation unit in which such a
3001 // use occurs; no diagnostic is required.
3002 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3003 SourceRange Range(TemplateNameLoc, RAngleLoc);
3004 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3005 << Context.getTypeDeclType(Specialization) << Range;
3006
3007 Diag(PrevDecl->getPointOfInstantiation(),
3008 diag::note_instantiation_required_here)
3009 << (PrevDecl->getTemplateSpecializationKind()
3010 != TSK_ImplicitInstantiation);
3011 return true;
3012 }
3013
Douglas Gregor2208a292009-09-26 20:57:03 +00003014 // If this is not a friend, note that this is an explicit specialization.
3015 if (TUK != TUK_Friend)
3016 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003017
3018 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003019 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003020 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003021 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003022 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003023 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003024 Diag(Def->getLocation(), diag::note_previous_definition);
3025 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003026 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003027 }
3028 }
3029
Douglas Gregord56a91e2009-02-26 22:19:44 +00003030 // Build the fully-sugared type for this class template
3031 // specialization as the user wrote in the specialization
3032 // itself. This means that we'll pretty-print the type retrieved
3033 // from the specialization's declaration the way that the user
3034 // actually wrote the specialization, rather than formatting the
3035 // name based on the "canonical" representation used to store the
3036 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003037 QualType WrittenTy
3038 = Context.getTemplateSpecializationType(Name,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003039 TemplateArgs.data(),
Douglas Gregordc572a32009-03-30 22:58:21 +00003040 TemplateArgs.size(),
Douglas Gregor15301382009-07-30 17:40:51 +00003041 CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003042 if (TUK != TUK_Friend)
3043 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003044 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003045
Douglas Gregor1e249f82009-02-25 22:18:32 +00003046 // C++ [temp.expl.spec]p9:
3047 // A template explicit specialization is in the scope of the
3048 // namespace in which the template was defined.
3049 //
3050 // We actually implement this paragraph where we set the semantic
3051 // context (in the creation of the ClassTemplateSpecializationDecl),
3052 // but we also maintain the lexical context where the actual
3053 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003054 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003055
Douglas Gregor67a65642009-02-17 23:15:12 +00003056 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003057 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003058 Specialization->startDefinition();
3059
Douglas Gregor2208a292009-09-26 20:57:03 +00003060 if (TUK == TUK_Friend) {
3061 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3062 TemplateNameLoc,
3063 WrittenTy.getTypePtr(),
3064 /*FIXME:*/KWLoc);
3065 Friend->setAccess(AS_public);
3066 CurContext->addDecl(Friend);
3067 } else {
3068 // Add the specialization into its lexical context, so that it can
3069 // be seen when iterating through the list of declarations in that
3070 // context. However, specializations are not found by name lookup.
3071 CurContext->addDecl(Specialization);
3072 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003073 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003074}
Douglas Gregor333489b2009-03-27 23:10:48 +00003075
Mike Stump11289f42009-09-09 15:08:12 +00003076Sema::DeclPtrTy
3077Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003078 MultiTemplateParamsArg TemplateParameterLists,
3079 Declarator &D) {
3080 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3081}
3082
Mike Stump11289f42009-09-09 15:08:12 +00003083Sema::DeclPtrTy
3084Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003085 MultiTemplateParamsArg TemplateParameterLists,
3086 Declarator &D) {
3087 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3088 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3089 "Not a function declarator!");
3090 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003091
Douglas Gregor17a7c122009-06-24 00:54:41 +00003092 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003093 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003094 }
Mike Stump11289f42009-09-09 15:08:12 +00003095
Douglas Gregor17a7c122009-06-24 00:54:41 +00003096 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003097
3098 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003099 move(TemplateParameterLists),
3100 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003101 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003102 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003103 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003104 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003105 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3106 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003107 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003108}
3109
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003110/// \brief Diagnose cases where we have an explicit template specialization
3111/// before/after an explicit template instantiation, producing diagnostics
3112/// for those cases where they are required and determining whether the
3113/// new specialization/instantiation will have any effect.
3114///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003115/// \param NewLoc the location of the new explicit specialization or
3116/// instantiation.
3117///
3118/// \param NewTSK the kind of the new explicit specialization or instantiation.
3119///
3120/// \param PrevDecl the previous declaration of the entity.
3121///
3122/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3123///
3124/// \param PrevPointOfInstantiation if valid, indicates where the previus
3125/// declaration was instantiated (either implicitly or explicitly).
3126///
3127/// \param SuppressNew will be set to true to indicate that the new
3128/// specialization or instantiation has no effect and should be ignored.
3129///
3130/// \returns true if there was an error that should prevent the introduction of
3131/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003132bool
3133Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3134 TemplateSpecializationKind NewTSK,
3135 NamedDecl *PrevDecl,
3136 TemplateSpecializationKind PrevTSK,
3137 SourceLocation PrevPointOfInstantiation,
3138 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003139 SuppressNew = false;
3140
3141 switch (NewTSK) {
3142 case TSK_Undeclared:
3143 case TSK_ImplicitInstantiation:
3144 assert(false && "Don't check implicit instantiations here");
3145 return false;
3146
3147 case TSK_ExplicitSpecialization:
3148 switch (PrevTSK) {
3149 case TSK_Undeclared:
3150 case TSK_ExplicitSpecialization:
3151 // Okay, we're just specializing something that is either already
3152 // explicitly specialized or has merely been mentioned without any
3153 // instantiation.
3154 return false;
3155
3156 case TSK_ImplicitInstantiation:
3157 if (PrevPointOfInstantiation.isInvalid()) {
3158 // The declaration itself has not actually been instantiated, so it is
3159 // still okay to specialize it.
3160 return false;
3161 }
3162 // Fall through
3163
3164 case TSK_ExplicitInstantiationDeclaration:
3165 case TSK_ExplicitInstantiationDefinition:
3166 assert((PrevTSK == TSK_ImplicitInstantiation ||
3167 PrevPointOfInstantiation.isValid()) &&
3168 "Explicit instantiation without point of instantiation?");
3169
3170 // C++ [temp.expl.spec]p6:
3171 // If a template, a member template or the member of a class template
3172 // is explicitly specialized then that specialization shall be declared
3173 // before the first use of that specialization that would cause an
3174 // implicit instantiation to take place, in every translation unit in
3175 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003176 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003177 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003178 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003179 << (PrevTSK != TSK_ImplicitInstantiation);
3180
3181 return true;
3182 }
3183 break;
3184
3185 case TSK_ExplicitInstantiationDeclaration:
3186 switch (PrevTSK) {
3187 case TSK_ExplicitInstantiationDeclaration:
3188 // This explicit instantiation declaration is redundant (that's okay).
3189 SuppressNew = true;
3190 return false;
3191
3192 case TSK_Undeclared:
3193 case TSK_ImplicitInstantiation:
3194 // We're explicitly instantiating something that may have already been
3195 // implicitly instantiated; that's fine.
3196 return false;
3197
3198 case TSK_ExplicitSpecialization:
3199 // C++0x [temp.explicit]p4:
3200 // For a given set of template parameters, if an explicit instantiation
3201 // of a template appears after a declaration of an explicit
3202 // specialization for that template, the explicit instantiation has no
3203 // effect.
3204 return false;
3205
3206 case TSK_ExplicitInstantiationDefinition:
3207 // C++0x [temp.explicit]p10:
3208 // If an entity is the subject of both an explicit instantiation
3209 // declaration and an explicit instantiation definition in the same
3210 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003211 Diag(NewLoc,
3212 diag::err_explicit_instantiation_declaration_after_definition);
3213 Diag(PrevPointOfInstantiation,
3214 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003215 assert(PrevPointOfInstantiation.isValid() &&
3216 "Explicit instantiation without point of instantiation?");
3217 SuppressNew = true;
3218 return false;
3219 }
3220 break;
3221
3222 case TSK_ExplicitInstantiationDefinition:
3223 switch (PrevTSK) {
3224 case TSK_Undeclared:
3225 case TSK_ImplicitInstantiation:
3226 // We're explicitly instantiating something that may have already been
3227 // implicitly instantiated; that's fine.
3228 return false;
3229
3230 case TSK_ExplicitSpecialization:
3231 // C++ DR 259, C++0x [temp.explicit]p4:
3232 // For a given set of template parameters, if an explicit
3233 // instantiation of a template appears after a declaration of
3234 // an explicit specialization for that template, the explicit
3235 // instantiation has no effect.
3236 //
3237 // In C++98/03 mode, we only give an extension warning here, because it
3238 // is not not harmful to try to explicitly instantiate something that
3239 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003240 if (!getLangOptions().CPlusPlus0x) {
3241 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003242 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003243 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003244 diag::note_previous_template_specialization);
3245 }
3246 SuppressNew = true;
3247 return false;
3248
3249 case TSK_ExplicitInstantiationDeclaration:
3250 // We're explicity instantiating a definition for something for which we
3251 // were previously asked to suppress instantiations. That's fine.
3252 return false;
3253
3254 case TSK_ExplicitInstantiationDefinition:
3255 // C++0x [temp.spec]p5:
3256 // For a given template and a given set of template-arguments,
3257 // - an explicit instantiation definition shall appear at most once
3258 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003259 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003260 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003261 Diag(PrevPointOfInstantiation,
3262 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003263 SuppressNew = true;
3264 return false;
3265 }
3266 break;
3267 }
3268
3269 assert(false && "Missing specialization/instantiation case?");
3270
3271 return false;
3272}
3273
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003274/// \brief Perform semantic analysis for the given function template
3275/// specialization.
3276///
3277/// This routine performs all of the semantic analysis required for an
3278/// explicit function template specialization. On successful completion,
3279/// the function declaration \p FD will become a function template
3280/// specialization.
3281///
3282/// \param FD the function declaration, which will be updated to become a
3283/// function template specialization.
3284///
3285/// \param HasExplicitTemplateArgs whether any template arguments were
3286/// explicitly provided.
3287///
3288/// \param LAngleLoc the location of the left angle bracket ('<'), if
3289/// template arguments were explicitly provided.
3290///
3291/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3292/// if any.
3293///
3294/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3295/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3296/// true as in, e.g., \c void sort<>(char*, char*);
3297///
3298/// \param RAngleLoc the location of the right angle bracket ('>'), if
3299/// template arguments were explicitly provided.
3300///
3301/// \param PrevDecl the set of declarations that
3302bool
3303Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
3304 bool HasExplicitTemplateArgs,
3305 SourceLocation LAngleLoc,
John McCall0ad16662009-10-29 08:12:44 +00003306 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003307 unsigned NumExplicitTemplateArgs,
3308 SourceLocation RAngleLoc,
3309 NamedDecl *&PrevDecl) {
3310 // The set of function template specializations that could match this
3311 // explicit function template specialization.
3312 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3313 CandidateSet Candidates;
3314
3315 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
3316 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3317 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) {
3318 // Only consider templates found within the same semantic lookup scope as
3319 // FD.
3320 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3321 continue;
3322
3323 // C++ [temp.expl.spec]p11:
3324 // A trailing template-argument can be left unspecified in the
3325 // template-id naming an explicit function template specialization
3326 // provided it can be deduced from the function argument type.
3327 // Perform template argument deduction to determine whether we may be
3328 // specializing this template.
3329 // FIXME: It is somewhat wasteful to build
3330 TemplateDeductionInfo Info(Context);
3331 FunctionDecl *Specialization = 0;
3332 if (TemplateDeductionResult TDK
3333 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
3334 ExplicitTemplateArgs,
3335 NumExplicitTemplateArgs,
3336 FD->getType(),
3337 Specialization,
3338 Info)) {
3339 // FIXME: Template argument deduction failed; record why it failed, so
3340 // that we can provide nifty diagnostics.
3341 (void)TDK;
3342 continue;
3343 }
3344
3345 // Record this candidate.
3346 Candidates.push_back(Specialization);
3347 }
3348 }
3349
Douglas Gregor5de279c2009-09-26 03:41:46 +00003350 // Find the most specialized function template.
3351 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3352 Candidates.size(),
3353 TPOC_Other,
3354 FD->getLocation(),
3355 PartialDiagnostic(diag::err_function_template_spec_no_match)
3356 << FD->getDeclName(),
3357 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
3358 << FD->getDeclName() << HasExplicitTemplateArgs,
3359 PartialDiagnostic(diag::note_function_template_spec_matched));
3360 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003361 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003362
3363 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003364 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003365
Douglas Gregor54888652009-10-07 00:13:32 +00003366 // Check the scope of this explicit specialization.
3367 if (CheckTemplateSpecializationScope(*this,
3368 Specialization->getPrimaryTemplate(),
3369 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003370 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003371 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003372
3373 // C++ [temp.expl.spec]p6:
3374 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003375 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003376 // before the first use of that specialization that would cause an implicit
3377 // instantiation to take place, in every translation unit in which such a
3378 // use occurs; no diagnostic is required.
3379 FunctionTemplateSpecializationInfo *SpecInfo
3380 = Specialization->getTemplateSpecializationInfo();
3381 assert(SpecInfo && "Function template specialization info missing?");
3382 if (SpecInfo->getPointOfInstantiation().isValid()) {
3383 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3384 << FD;
3385 Diag(SpecInfo->getPointOfInstantiation(),
3386 diag::note_instantiation_required_here)
3387 << (Specialization->getTemplateSpecializationKind()
3388 != TSK_ImplicitInstantiation);
3389 return true;
3390 }
Douglas Gregor54888652009-10-07 00:13:32 +00003391
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003392 // Mark the prior declaration as an explicit specialization, so that later
3393 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003394 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003395
3396 // Turn the given function declaration into a function template
3397 // specialization, with the template arguments from the previous
3398 // specialization.
3399 FD->setFunctionTemplateSpecialization(Context,
3400 Specialization->getPrimaryTemplate(),
3401 new (Context) TemplateArgumentList(
3402 *Specialization->getTemplateSpecializationArgs()),
3403 /*InsertPos=*/0,
3404 TSK_ExplicitSpecialization);
3405
3406 // The "previous declaration" for this function template specialization is
3407 // the prior function template specialization.
3408 PrevDecl = Specialization;
3409 return false;
3410}
3411
Douglas Gregor86d142a2009-10-08 07:24:58 +00003412/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003413/// specialization.
3414///
3415/// This routine performs all of the semantic analysis required for an
3416/// explicit member function specialization. On successful completion,
3417/// the function declaration \p FD will become a member function
3418/// specialization.
3419///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003420/// \param Member the member declaration, which will be updated to become a
3421/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003422///
3423/// \param PrevDecl the set of declarations, one of which may be specialized
3424/// by this function specialization.
3425bool
Douglas Gregor86d142a2009-10-08 07:24:58 +00003426Sema::CheckMemberSpecialization(NamedDecl *Member, NamedDecl *&PrevDecl) {
3427 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3428
3429 // Try to find the member we are instantiating.
3430 NamedDecl *Instantiation = 0;
3431 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003432 MemberSpecializationInfo *MSInfo = 0;
3433
Douglas Gregor86d142a2009-10-08 07:24:58 +00003434 if (!PrevDecl) {
3435 // Nowhere to look anyway.
3436 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
3437 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) {
3438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Ovl)) {
3439 if (Context.hasSameType(Function->getType(), Method->getType())) {
3440 Instantiation = Method;
3441 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003442 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003443 break;
3444 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003445 }
3446 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003447 } else if (isa<VarDecl>(Member)) {
3448 if (VarDecl *PrevVar = dyn_cast<VarDecl>(PrevDecl))
3449 if (PrevVar->isStaticDataMember()) {
3450 Instantiation = PrevDecl;
3451 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003452 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003453 }
3454 } else if (isa<RecordDecl>(Member)) {
3455 if (CXXRecordDecl *PrevRecord = dyn_cast<CXXRecordDecl>(PrevDecl)) {
3456 Instantiation = PrevDecl;
3457 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003458 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003459 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003460 }
3461
3462 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003463 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003464 // specializations are always out-of-line, the caller will complain about
3465 // this mismatch later.
3466 return false;
3467 }
3468
Douglas Gregor86d142a2009-10-08 07:24:58 +00003469 // Make sure that this is a specialization of a member.
3470 if (!InstantiatedFrom) {
3471 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3472 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003473 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3474 return true;
3475 }
3476
Douglas Gregor06db9f52009-10-12 20:18:28 +00003477 // C++ [temp.expl.spec]p6:
3478 // If a template, a member template or the member of a class template is
3479 // explicitly specialized then that spe- cialization shall be declared
3480 // before the first use of that specialization that would cause an implicit
3481 // instantiation to take place, in every translation unit in which such a
3482 // use occurs; no diagnostic is required.
3483 assert(MSInfo && "Member specialization info missing?");
3484 if (MSInfo->getPointOfInstantiation().isValid()) {
3485 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3486 << Member;
3487 Diag(MSInfo->getPointOfInstantiation(),
3488 diag::note_instantiation_required_here)
3489 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3490 return true;
3491 }
3492
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003493 // Check the scope of this explicit specialization.
3494 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003495 InstantiatedFrom,
3496 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003497 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003498 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003499
Douglas Gregor86d142a2009-10-08 07:24:58 +00003500 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003501 // the original declaration to note that it is an explicit specialization
3502 // (if it was previously an implicit instantiation). This latter step
3503 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003504 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003505 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3506 if (InstantiationFunction->getTemplateSpecializationKind() ==
3507 TSK_ImplicitInstantiation) {
3508 InstantiationFunction->setTemplateSpecializationKind(
3509 TSK_ExplicitSpecialization);
3510 InstantiationFunction->setLocation(Member->getLocation());
3511 }
3512
Douglas Gregor86d142a2009-10-08 07:24:58 +00003513 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3514 cast<CXXMethodDecl>(InstantiatedFrom),
3515 TSK_ExplicitSpecialization);
3516 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003517 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3518 if (InstantiationVar->getTemplateSpecializationKind() ==
3519 TSK_ImplicitInstantiation) {
3520 InstantiationVar->setTemplateSpecializationKind(
3521 TSK_ExplicitSpecialization);
3522 InstantiationVar->setLocation(Member->getLocation());
3523 }
3524
Douglas Gregor86d142a2009-10-08 07:24:58 +00003525 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3526 cast<VarDecl>(InstantiatedFrom),
3527 TSK_ExplicitSpecialization);
3528 } else {
3529 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003530 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3531 if (InstantiationClass->getTemplateSpecializationKind() ==
3532 TSK_ImplicitInstantiation) {
3533 InstantiationClass->setTemplateSpecializationKind(
3534 TSK_ExplicitSpecialization);
3535 InstantiationClass->setLocation(Member->getLocation());
3536 }
3537
Douglas Gregor86d142a2009-10-08 07:24:58 +00003538 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003539 cast<CXXRecordDecl>(InstantiatedFrom),
3540 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003541 }
3542
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003543 // Save the caller the trouble of having to figure out which declaration
3544 // this specialization matches.
3545 PrevDecl = Instantiation;
3546 return false;
3547}
3548
Douglas Gregore47f5a72009-10-14 23:41:34 +00003549/// \brief Check the scope of an explicit instantiation.
3550static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3551 SourceLocation InstLoc,
3552 bool WasQualifiedName) {
3553 DeclContext *ExpectedContext
3554 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3555 DeclContext *CurContext = S.CurContext->getLookupContext();
3556
3557 // C++0x [temp.explicit]p2:
3558 // An explicit instantiation shall appear in an enclosing namespace of its
3559 // template.
3560 //
3561 // This is DR275, which we do not retroactively apply to C++98/03.
3562 if (S.getLangOptions().CPlusPlus0x &&
3563 !CurContext->Encloses(ExpectedContext)) {
3564 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3565 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3566 << D << NS;
3567 else
3568 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3569 << D;
3570 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3571 return;
3572 }
3573
3574 // C++0x [temp.explicit]p2:
3575 // If the name declared in the explicit instantiation is an unqualified
3576 // name, the explicit instantiation shall appear in the namespace where
3577 // its template is declared or, if that namespace is inline (7.3.1), any
3578 // namespace from its enclosing namespace set.
3579 if (WasQualifiedName)
3580 return;
3581
3582 if (CurContext->Equals(ExpectedContext))
3583 return;
3584
3585 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3586 << D << ExpectedContext;
3587 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3588}
3589
3590/// \brief Determine whether the given scope specifier has a template-id in it.
3591static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3592 if (!SS.isSet())
3593 return false;
3594
3595 // C++0x [temp.explicit]p2:
3596 // If the explicit instantiation is for a member function, a member class
3597 // or a static data member of a class template specialization, the name of
3598 // the class template specialization in the qualified-id for the member
3599 // name shall be a simple-template-id.
3600 //
3601 // C++98 has the same restriction, just worded differently.
3602 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3603 NNS; NNS = NNS->getPrefix())
3604 if (Type *T = NNS->getAsType())
3605 if (isa<TemplateSpecializationType>(T))
3606 return true;
3607
3608 return false;
3609}
3610
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003611// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00003612// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00003613Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003614Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003615 SourceLocation ExternLoc,
3616 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003617 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00003618 SourceLocation KWLoc,
3619 const CXXScopeSpec &SS,
3620 TemplateTy TemplateD,
3621 SourceLocation TemplateNameLoc,
3622 SourceLocation LAngleLoc,
3623 ASTTemplateArgsPtr TemplateArgsIn,
3624 SourceLocation *TemplateArgLocs,
3625 SourceLocation RAngleLoc,
3626 AttributeList *Attr) {
3627 // Find the class template we're specializing
3628 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003629 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00003630 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
3631
3632 // Check that the specialization uses the same tag kind as the
3633 // original template.
3634 TagDecl::TagKind Kind;
3635 switch (TagSpec) {
3636 default: assert(0 && "Unknown tag type!");
3637 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3638 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3639 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3640 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003641 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003642 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003643 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003644 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00003645 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003646 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00003647 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003648 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003649 diag::note_previous_use);
3650 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3651 }
3652
Douglas Gregore47f5a72009-10-14 23:41:34 +00003653 // C++0x [temp.explicit]p2:
3654 // There are two forms of explicit instantiation: an explicit instantiation
3655 // definition and an explicit instantiation declaration. An explicit
3656 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00003657 TemplateSpecializationKind TSK
3658 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3659 : TSK_ExplicitInstantiationDeclaration;
3660
Douglas Gregora1f49972009-05-13 00:25:59 +00003661 // Translate the parser's template argument list in our AST format.
John McCall0ad16662009-10-29 08:12:44 +00003662 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregora1f49972009-05-13 00:25:59 +00003663 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
3664
3665 // Check that the template argument list is well-formed for this
3666 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003667 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3668 TemplateArgs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003669 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
Anders Carlssondd096d82009-06-05 02:12:32 +00003670 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregore3f1f352009-07-01 00:28:38 +00003671 RAngleLoc, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00003672 return true;
3673
Mike Stump11289f42009-09-09 15:08:12 +00003674 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00003675 ClassTemplate->getTemplateParameters()->size()) &&
3676 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003677
Douglas Gregora1f49972009-05-13 00:25:59 +00003678 // Find the class template specialization declaration that
3679 // corresponds to these arguments.
3680 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003681 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003682 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003683 Converted.flatSize(),
3684 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00003685 void *InsertPos = 0;
3686 ClassTemplateSpecializationDecl *PrevDecl
3687 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3688
Douglas Gregor54888652009-10-07 00:13:32 +00003689 // C++0x [temp.explicit]p2:
3690 // [...] An explicit instantiation shall appear in an enclosing
3691 // namespace of its template. [...]
3692 //
3693 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003694 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
3695 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00003696
Douglas Gregora1f49972009-05-13 00:25:59 +00003697 ClassTemplateSpecializationDecl *Specialization = 0;
3698
3699 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00003700 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003701 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00003702 PrevDecl,
3703 PrevDecl->getSpecializationKind(),
3704 PrevDecl->getPointOfInstantiation(),
3705 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00003706 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003707
Douglas Gregor12e49d32009-10-15 22:53:21 +00003708 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003709 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00003710
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003711 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
3712 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3713 // Since the only prior class template specialization with these
3714 // arguments was referenced but not declared, reuse that
3715 // declaration node as our own, updating its source location to
3716 // reflect our new declaration.
3717 Specialization = PrevDecl;
3718 Specialization->setLocation(TemplateNameLoc);
3719 PrevDecl = 0;
3720 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00003721 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003722
3723 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00003724 // Create a new class template specialization declaration node for
3725 // this explicit specialization.
3726 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003727 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00003728 ClassTemplate->getDeclContext(),
3729 TemplateNameLoc,
3730 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003731 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00003732
Douglas Gregor4aa04b12009-09-11 21:19:12 +00003733 if (PrevDecl) {
3734 // Remove the previous declaration from the folding set, since we want
3735 // to introduce a new declaration.
3736 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3737 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3738 }
3739
3740 // Insert the new specialization.
3741 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00003742 }
3743
3744 // Build the fully-sugared type for this explicit instantiation as
3745 // the user wrote in the explicit instantiation itself. This means
3746 // that we'll pretty-print the type retrieved from the
3747 // specialization's declaration the way that the user actually wrote
3748 // the explicit instantiation, rather than formatting the name based
3749 // on the "canonical" representation used to store the template
3750 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003751 QualType WrittenTy
3752 = Context.getTemplateSpecializationType(Name,
Anders Carlsson03c9e872009-06-05 02:45:24 +00003753 TemplateArgs.data(),
Douglas Gregora1f49972009-05-13 00:25:59 +00003754 TemplateArgs.size(),
3755 Context.getTypeDeclType(Specialization));
3756 Specialization->setTypeAsWritten(WrittenTy);
3757 TemplateArgsIn.release();
3758
3759 // Add the explicit instantiation into its lexical context. However,
3760 // since explicit instantiations are never found by name lookup, we
3761 // just put it into the declaration context directly.
3762 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003763 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00003764
3765 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00003766 // A definition of a class template or class member template
3767 // shall be in scope at the point of the explicit instantiation of
3768 // the class template or class member template.
3769 //
3770 // This check comes when we actually try to perform the
3771 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00003772 ClassTemplateSpecializationDecl *Def
3773 = cast_or_null<ClassTemplateSpecializationDecl>(
3774 Specialization->getDefinition(Context));
3775 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00003776 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00003777
3778 // Instantiate the members of this class template specialization.
3779 Def = cast_or_null<ClassTemplateSpecializationDecl>(
3780 Specialization->getDefinition(Context));
3781 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00003782 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00003783
3784 return DeclPtrTy::make(Specialization);
3785}
3786
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003787// Explicit instantiation of a member class of a class template.
3788Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00003789Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00003790 SourceLocation ExternLoc,
3791 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003792 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003793 SourceLocation KWLoc,
3794 const CXXScopeSpec &SS,
3795 IdentifierInfo *Name,
3796 SourceLocation NameLoc,
3797 AttributeList *Attr) {
3798
Douglas Gregord6ab8742009-05-28 23:31:59 +00003799 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00003800 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00003801 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00003802 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00003803 MultiTemplateParamsArg(*this, 0, 0),
3804 Owned, IsDependent);
3805 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
3806
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003807 if (!TagD)
3808 return true;
3809
3810 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
3811 if (Tag->isEnum()) {
3812 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
3813 << Context.getTypeDeclType(Tag);
3814 return true;
3815 }
3816
Douglas Gregorb8006faf2009-05-27 17:30:49 +00003817 if (Tag->isInvalidDecl())
3818 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00003819
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003820 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
3821 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3822 if (!Pattern) {
3823 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
3824 << Context.getTypeDeclType(Record);
3825 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
3826 return true;
3827 }
3828
Douglas Gregore47f5a72009-10-14 23:41:34 +00003829 // C++0x [temp.explicit]p2:
3830 // If the explicit instantiation is for a class or member class, the
3831 // elaborated-type-specifier in the declaration shall include a
3832 // simple-template-id.
3833 //
3834 // C++98 has the same restriction, just worded differently.
3835 if (!ScopeSpecifierHasTemplateId(SS))
3836 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
3837 << Record << SS.getRange();
3838
3839 // C++0x [temp.explicit]p2:
3840 // There are two forms of explicit instantiation: an explicit instantiation
3841 // definition and an explicit instantiation declaration. An explicit
3842 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00003843 TemplateSpecializationKind TSK
3844 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3845 : TSK_ExplicitInstantiationDeclaration;
3846
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003847 // C++0x [temp.explicit]p2:
3848 // [...] An explicit instantiation shall appear in an enclosing
3849 // namespace of its template. [...]
3850 //
3851 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00003852 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003853
3854 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00003855 CXXRecordDecl *PrevDecl
3856 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
3857 if (!PrevDecl && Record->getDefinition(Context))
3858 PrevDecl = Record;
3859 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003860 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
3861 bool SuppressNew = false;
3862 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00003863 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003864 PrevDecl,
3865 MSInfo->getTemplateSpecializationKind(),
3866 MSInfo->getPointOfInstantiation(),
3867 SuppressNew))
3868 return true;
3869 if (SuppressNew)
3870 return TagD;
3871 }
3872
Douglas Gregor12e49d32009-10-15 22:53:21 +00003873 CXXRecordDecl *RecordDef
3874 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3875 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00003876 // C++ [temp.explicit]p3:
3877 // A definition of a member class of a class template shall be in scope
3878 // at the point of an explicit instantiation of the member class.
3879 CXXRecordDecl *Def
3880 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
3881 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003882 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
3883 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00003884 Diag(Pattern->getLocation(), diag::note_forward_declaration)
3885 << Pattern;
3886 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003887 } else {
3888 if (InstantiateClass(NameLoc, Record, Def,
3889 getTemplateInstantiationArgs(Record),
3890 TSK))
3891 return true;
3892
3893 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
3894 if (!RecordDef)
3895 return true;
3896 }
3897 }
3898
3899 // Instantiate all of the members of the class.
3900 InstantiateClassMembers(NameLoc, RecordDef,
3901 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003902
Mike Stump87c57ac2009-05-16 07:39:55 +00003903 // FIXME: We don't have any representation for explicit instantiations of
3904 // member classes. Such a representation is not needed for compilation, but it
3905 // should be available for clients that want to see all of the declarations in
3906 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00003907 return TagD;
3908}
3909
Douglas Gregor450f00842009-09-25 18:43:00 +00003910Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
3911 SourceLocation ExternLoc,
3912 SourceLocation TemplateLoc,
3913 Declarator &D) {
3914 // Explicit instantiations always require a name.
3915 DeclarationName Name = GetNameForDeclarator(D);
3916 if (!Name) {
3917 if (!D.isInvalidType())
3918 Diag(D.getDeclSpec().getSourceRange().getBegin(),
3919 diag::err_explicit_instantiation_requires_name)
3920 << D.getDeclSpec().getSourceRange()
3921 << D.getSourceRange();
3922
3923 return true;
3924 }
3925
3926 // The scope passed in may not be a decl scope. Zip up the scope tree until
3927 // we find one that is.
3928 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3929 (S->getFlags() & Scope::TemplateParamScope) != 0)
3930 S = S->getParent();
3931
3932 // Determine the type of the declaration.
3933 QualType R = GetTypeForDeclarator(D, S, 0);
3934 if (R.isNull())
3935 return true;
3936
3937 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3938 // Cannot explicitly instantiate a typedef.
3939 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
3940 << Name;
3941 return true;
3942 }
3943
Douglas Gregor3c74d412009-10-14 20:14:33 +00003944 // C++0x [temp.explicit]p1:
3945 // [...] An explicit instantiation of a function template shall not use the
3946 // inline or constexpr specifiers.
3947 // Presumably, this also applies to member functions of class templates as
3948 // well.
3949 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
3950 Diag(D.getDeclSpec().getInlineSpecLoc(),
3951 diag::err_explicit_instantiation_inline)
3952 << CodeModificationHint::CreateRemoval(
3953 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
3954
3955 // FIXME: check for constexpr specifier.
3956
Douglas Gregore47f5a72009-10-14 23:41:34 +00003957 // C++0x [temp.explicit]p2:
3958 // There are two forms of explicit instantiation: an explicit instantiation
3959 // definition and an explicit instantiation declaration. An explicit
3960 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00003961 TemplateSpecializationKind TSK
3962 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
3963 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00003964
John McCall9f3059a2009-10-09 21:13:30 +00003965 LookupResult Previous;
3966 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
3967 Name, LookupOrdinaryName);
Douglas Gregor450f00842009-09-25 18:43:00 +00003968
3969 if (!R->isFunctionType()) {
3970 // C++ [temp.explicit]p1:
3971 // A [...] static data member of a class template can be explicitly
3972 // instantiated from the member definition associated with its class
3973 // template.
3974 if (Previous.isAmbiguous()) {
3975 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(),
3976 D.getSourceRange());
3977 }
3978
John McCall9f3059a2009-10-09 21:13:30 +00003979 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
3980 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00003981 if (!Prev || !Prev->isStaticDataMember()) {
3982 // We expect to see a data data member here.
3983 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
3984 << Name;
3985 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
3986 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00003987 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00003988 return true;
3989 }
3990
3991 if (!Prev->getInstantiatedFromStaticDataMember()) {
3992 // FIXME: Check for explicit specialization?
3993 Diag(D.getIdentifierLoc(),
3994 diag::err_explicit_instantiation_data_member_not_instantiated)
3995 << Prev;
3996 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
3997 // FIXME: Can we provide a note showing where this was declared?
3998 return true;
3999 }
4000
Douglas Gregore47f5a72009-10-14 23:41:34 +00004001 // C++0x [temp.explicit]p2:
4002 // If the explicit instantiation is for a member function, a member class
4003 // or a static data member of a class template specialization, the name of
4004 // the class template specialization in the qualified-id for the member
4005 // name shall be a simple-template-id.
4006 //
4007 // C++98 has the same restriction, just worded differently.
4008 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4009 Diag(D.getIdentifierLoc(),
4010 diag::err_explicit_instantiation_without_qualified_id)
4011 << Prev << D.getCXXScopeSpec().getRange();
4012
4013 // Check the scope of this explicit instantiation.
4014 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4015
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004016 // Verify that it is okay to explicitly instantiate here.
4017 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4018 assert(MSInfo && "Missing static data member specialization info?");
4019 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004020 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004021 MSInfo->getTemplateSpecializationKind(),
4022 MSInfo->getPointOfInstantiation(),
4023 SuppressNew))
4024 return true;
4025 if (SuppressNew)
4026 return DeclPtrTy();
4027
Douglas Gregor450f00842009-09-25 18:43:00 +00004028 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004029 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004030 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004031 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4032 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004033
4034 // FIXME: Create an ExplicitInstantiation node?
4035 return DeclPtrTy();
4036 }
4037
Douglas Gregor0e876e02009-09-25 23:53:26 +00004038 // If the declarator is a template-id, translate the parser's template
4039 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004040 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004041 llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004042 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4043 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Douglas Gregord90fd522009-09-25 21:45:23 +00004044 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4045 TemplateId->getTemplateArgs(),
4046 TemplateId->getTemplateArgIsType(),
4047 TemplateId->NumArgs);
4048 translateTemplateArguments(TemplateArgsPtr,
4049 TemplateId->getTemplateArgLocations(),
4050 TemplateArgs);
4051 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004052 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004053 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004054
Douglas Gregor450f00842009-09-25 18:43:00 +00004055 // C++ [temp.explicit]p1:
4056 // A [...] function [...] can be explicitly instantiated from its template.
4057 // A member function [...] of a class template can be explicitly
4058 // instantiated from the member definition associated with its class
4059 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004060 llvm::SmallVector<FunctionDecl *, 8> Matches;
4061 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4062 P != PEnd; ++P) {
4063 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004064 if (!HasExplicitTemplateArgs) {
4065 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4066 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4067 Matches.clear();
4068 Matches.push_back(Method);
4069 break;
4070 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004071 }
4072 }
4073
4074 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4075 if (!FunTmpl)
4076 continue;
4077
4078 TemplateDeductionInfo Info(Context);
4079 FunctionDecl *Specialization = 0;
4080 if (TemplateDeductionResult TDK
Douglas Gregord90fd522009-09-25 21:45:23 +00004081 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs,
4082 TemplateArgs.data(), TemplateArgs.size(),
Douglas Gregor450f00842009-09-25 18:43:00 +00004083 R, Specialization, Info)) {
4084 // FIXME: Keep track of almost-matches?
4085 (void)TDK;
4086 continue;
4087 }
4088
4089 Matches.push_back(Specialization);
4090 }
4091
4092 // Find the most specialized function template specialization.
4093 FunctionDecl *Specialization
4094 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4095 D.getIdentifierLoc(),
4096 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4097 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4098 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4099
4100 if (!Specialization)
4101 return true;
4102
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004103 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004104 Diag(D.getIdentifierLoc(),
4105 diag::err_explicit_instantiation_member_function_not_instantiated)
4106 << Specialization
4107 << (Specialization->getTemplateSpecializationKind() ==
4108 TSK_ExplicitSpecialization);
4109 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4110 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004111 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004112
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004113 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004114 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4115 PrevDecl = Specialization;
4116
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004117 if (PrevDecl) {
4118 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004119 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004120 PrevDecl,
4121 PrevDecl->getTemplateSpecializationKind(),
4122 PrevDecl->getPointOfInstantiation(),
4123 SuppressNew))
4124 return true;
4125
4126 // FIXME: We may still want to build some representation of this
4127 // explicit specialization.
4128 if (SuppressNew)
4129 return DeclPtrTy();
4130 }
4131
4132 if (TSK == TSK_ExplicitInstantiationDefinition)
4133 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4134 false, /*DefinitionRequired=*/true);
4135
4136 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
4137
Douglas Gregore47f5a72009-10-14 23:41:34 +00004138 // C++0x [temp.explicit]p2:
4139 // If the explicit instantiation is for a member function, a member class
4140 // or a static data member of a class template specialization, the name of
4141 // the class template specialization in the qualified-id for the member
4142 // name shall be a simple-template-id.
4143 //
4144 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004145 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004146 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004147 D.getCXXScopeSpec().isSet() &&
4148 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4149 Diag(D.getIdentifierLoc(),
4150 diag::err_explicit_instantiation_without_qualified_id)
4151 << Specialization << D.getCXXScopeSpec().getRange();
4152
4153 CheckExplicitInstantiationScope(*this,
4154 FunTmpl? (NamedDecl *)FunTmpl
4155 : Specialization->getInstantiatedFromMemberFunction(),
4156 D.getIdentifierLoc(),
4157 D.getCXXScopeSpec().isSet());
4158
Douglas Gregor450f00842009-09-25 18:43:00 +00004159 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4160 return DeclPtrTy();
4161}
4162
Douglas Gregor333489b2009-03-27 23:10:48 +00004163Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004164Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4165 const CXXScopeSpec &SS, IdentifierInfo *Name,
4166 SourceLocation TagLoc, SourceLocation NameLoc) {
4167 // This has to hold, because SS is expected to be defined.
4168 assert(Name && "Expected a name in a dependent tag");
4169
4170 NestedNameSpecifier *NNS
4171 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4172 if (!NNS)
4173 return true;
4174
4175 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4176 if (T.isNull())
4177 return true;
4178
4179 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4180 QualType ElabType = Context.getElaboratedType(T, TagKind);
4181
4182 return ElabType.getAsOpaquePtr();
4183}
4184
4185Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004186Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4187 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004188 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004189 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4190 if (!NNS)
4191 return true;
4192
4193 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004194 if (T.isNull())
4195 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004196 return T.getAsOpaquePtr();
4197}
4198
Douglas Gregordce2b622009-04-01 00:28:59 +00004199Sema::TypeResult
4200Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4201 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004202 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004203 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004204 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004205 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004206 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004207 assert(TemplateId && "Expected a template specialization type");
4208
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004209 if (computeDeclContext(SS, false)) {
4210 // If we can compute a declaration context, then the "typename"
4211 // keyword was superfluous. Just build a QualifiedNameType to keep
4212 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004213
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004214 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4215 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4216 }
Mike Stump11289f42009-09-09 15:08:12 +00004217
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004218 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004219}
4220
Douglas Gregor333489b2009-03-27 23:10:48 +00004221/// \brief Build the type that describes a C++ typename specifier,
4222/// e.g., "typename T::type".
4223QualType
4224Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4225 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004226 CXXRecordDecl *CurrentInstantiation = 0;
4227 if (NNS->isDependent()) {
4228 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004229
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004230 // If the nested-name-specifier does not refer to the current
4231 // instantiation, then build a typename type.
4232 if (!CurrentInstantiation)
4233 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004234
Douglas Gregorc707da62009-09-02 13:12:51 +00004235 // The nested-name-specifier refers to the current instantiation, so the
4236 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004237 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004238 // extraneous "typename" keywords, and we retroactively apply this DR to
4239 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004240 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004241
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004242 DeclContext *Ctx = 0;
4243
4244 if (CurrentInstantiation)
4245 Ctx = CurrentInstantiation;
4246 else {
4247 CXXScopeSpec SS;
4248 SS.setScopeRep(NNS);
4249 SS.setRange(Range);
4250 if (RequireCompleteDeclContext(SS))
4251 return QualType();
4252
4253 Ctx = computeDeclContext(SS);
4254 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004255 assert(Ctx && "No declaration context?");
4256
4257 DeclarationName Name(&II);
John McCall9f3059a2009-10-09 21:13:30 +00004258 LookupResult Result;
4259 LookupQualifiedName(Result, Ctx, Name, LookupOrdinaryName, false);
Douglas Gregor333489b2009-03-27 23:10:48 +00004260 unsigned DiagID = 0;
4261 Decl *Referenced = 0;
4262 switch (Result.getKind()) {
4263 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004264 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004265 break;
4266
4267 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004268 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004269 // We found a type. Build a QualifiedNameType, since the
4270 // typename-specifier was just sugar. FIXME: Tell
4271 // QualifiedNameType that it has a "typename" prefix.
4272 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4273 }
4274
4275 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004276 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004277 break;
4278
4279 case LookupResult::FoundOverloaded:
4280 DiagID = diag::err_typename_nested_not_type;
4281 Referenced = *Result.begin();
4282 break;
4283
John McCall6538c932009-10-10 05:48:19 +00004284 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004285 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
4286 return QualType();
4287 }
4288
4289 // If we get here, it's because name lookup did not find a
4290 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004291 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004292 if (Referenced)
4293 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4294 << Name;
4295 return QualType();
4296}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004297
4298namespace {
4299 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004300 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4301 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004302 SourceLocation Loc;
4303 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004304
Douglas Gregor15acfb92009-08-06 16:20:37 +00004305 public:
Mike Stump11289f42009-09-09 15:08:12 +00004306 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004307 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004308 DeclarationName Entity)
4309 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004310 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004311
4312 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004313 /// transformed.
4314 ///
4315 /// For the purposes of type reconstruction, a type has already been
4316 /// transformed if it is NULL or if it is not dependent.
4317 bool AlreadyTransformed(QualType T) {
4318 return T.isNull() || !T->isDependentType();
4319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320
4321 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004322 /// rebuilt.
4323 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004324
Douglas Gregor15acfb92009-08-06 16:20:37 +00004325 /// \brief Returns the name of the entity whose type is being rebuilt.
4326 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004327
Douglas Gregoref6ab412009-10-27 06:26:26 +00004328 /// \brief Sets the "base" location and entity when that
4329 /// information is known based on another transformation.
4330 void setBase(SourceLocation Loc, DeclarationName Entity) {
4331 this->Loc = Loc;
4332 this->Entity = Entity;
4333 }
4334
Douglas Gregor15acfb92009-08-06 16:20:37 +00004335 /// \brief Transforms an expression by returning the expression itself
4336 /// (an identity function).
4337 ///
4338 /// FIXME: This is completely unsafe; we will need to actually clone the
4339 /// expressions.
4340 Sema::OwningExprResult TransformExpr(Expr *E) {
4341 return getSema().Owned(E);
4342 }
Mike Stump11289f42009-09-09 15:08:12 +00004343
Douglas Gregor15acfb92009-08-06 16:20:37 +00004344 /// \brief Transforms a typename type by determining whether the type now
4345 /// refers to a member of the current instantiation, and then
4346 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004347 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004348 };
4349}
4350
Mike Stump11289f42009-09-09 15:08:12 +00004351QualType
John McCall550e0c22009-10-21 00:40:46 +00004352CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4353 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004354 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004355
Douglas Gregor15acfb92009-08-06 16:20:37 +00004356 NestedNameSpecifier *NNS
4357 = TransformNestedNameSpecifier(T->getQualifier(),
4358 /*FIXME:*/SourceRange(getBaseLocation()));
4359 if (!NNS)
4360 return QualType();
4361
4362 // If the nested-name-specifier did not change, and we cannot compute the
4363 // context corresponding to the nested-name-specifier, then this
4364 // typename type will not change; exit early.
4365 CXXScopeSpec SS;
4366 SS.setRange(SourceRange(getBaseLocation()));
4367 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004368
4369 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004370 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004371 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004372
4373 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004374 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004375 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004376 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004377 = TransformType(QualType(TemplateId, 0));
4378 if (NewTemplateId.isNull())
4379 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004380
Douglas Gregor15acfb92009-08-06 16:20:37 +00004381 if (NNS == T->getQualifier() &&
4382 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004383 Result = QualType(T, 0);
4384 else
4385 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4386 } else
4387 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4388 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004389
John McCall0ad16662009-10-29 08:12:44 +00004390 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4391 NewTL.setNameLoc(TL.getNameLoc());
4392 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004393}
4394
4395/// \brief Rebuilds a type within the context of the current instantiation.
4396///
Mike Stump11289f42009-09-09 15:08:12 +00004397/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004398/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004399/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004400/// partial specialization thereof). This routine will rebuild that type now
4401/// that we have entered the declarator's scope, which may produce different
4402/// canonical types, e.g.,
4403///
4404/// \code
4405/// template<typename T>
4406/// struct X {
4407/// typedef T* pointer;
4408/// pointer data();
4409/// };
4410///
4411/// template<typename T>
4412/// typename X<T>::pointer X<T>::data() { ... }
4413/// \endcode
4414///
4415/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4416/// since we do not know that we can look into X<T> when we parsed the type.
4417/// This function will rebuild the type, performing the lookup of "pointer"
4418/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4419/// as the canonical type of T*, allowing the return types of the out-of-line
4420/// definition and the declaration to match.
4421QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4422 DeclarationName Name) {
4423 if (T.isNull() || !T->isDependentType())
4424 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004425
Douglas Gregor15acfb92009-08-06 16:20:37 +00004426 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4427 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004428}
Douglas Gregorbe999392009-09-15 16:23:51 +00004429
4430/// \brief Produces a formatted string that describes the binding of
4431/// template parameters to template arguments.
4432std::string
4433Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4434 const TemplateArgumentList &Args) {
4435 std::string Result;
4436
4437 if (!Params || Params->size() == 0)
4438 return Result;
4439
4440 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
4441 if (I == 0)
4442 Result += "[with ";
4443 else
4444 Result += ", ";
4445
4446 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4447 Result += Id->getName();
4448 } else {
4449 Result += '$';
4450 Result += llvm::utostr(I);
4451 }
4452
4453 Result += " = ";
4454
4455 switch (Args[I].getKind()) {
4456 case TemplateArgument::Null:
4457 Result += "<no value>";
4458 break;
4459
4460 case TemplateArgument::Type: {
4461 std::string TypeStr;
4462 Args[I].getAsType().getAsStringInternal(TypeStr,
4463 Context.PrintingPolicy);
4464 Result += TypeStr;
4465 break;
4466 }
4467
4468 case TemplateArgument::Declaration: {
4469 bool Unnamed = true;
4470 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4471 if (ND->getDeclName()) {
4472 Unnamed = false;
4473 Result += ND->getNameAsString();
4474 }
4475 }
4476
4477 if (Unnamed) {
4478 Result += "<anonymous>";
4479 }
4480 break;
4481 }
4482
4483 case TemplateArgument::Integral: {
4484 Result += Args[I].getAsIntegral()->toString(10);
4485 break;
4486 }
4487
4488 case TemplateArgument::Expression: {
4489 assert(false && "No expressions in deduced template arguments!");
4490 Result += "<expression>";
4491 break;
4492 }
4493
4494 case TemplateArgument::Pack:
4495 // FIXME: Format template argument packs
4496 Result += "<template argument pack>";
4497 break;
4498 }
4499 }
4500
4501 Result += ']';
4502 return Result;
4503}