blob: 0773a0f1e4dee4f1a385385a5df7d4dd62b2c52d [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-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 Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000024using namespace clang;
25
Douglas Gregor2dd078a2009-09-02 22:59:36 +000026/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30 if (!D)
31 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000032
Douglas Gregor2dd078a2009-09-02 22:59:36 +000033 if (isa<TemplateDecl>(D))
34 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000035
Douglas Gregor2dd078a2009-09-02 22:59:36 +000036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37 // C++ [temp.local]p1:
38 // Like normal (non-template) classes, class templates have an
39 // injected-class-name (Clause 9). The injected-class-name
40 // can be used with or without a template-argument-list. When
41 // it is used without a template-argument-list, it is
42 // equivalent to the injected-class-name followed by the
43 // template-parameters of the class template enclosed in
44 // <>. When it is used with a template-argument-list, it
45 // refers to the specified class template specialization,
46 // which could be the current specialization or another
47 // specialization.
48 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000049 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000050 if (Record->getDescribedClassTemplate())
51 return Record->getDescribedClassTemplate();
52
53 if (ClassTemplateSpecializationDecl *Spec
54 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55 return Spec->getSpecializedTemplate();
56 }
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor2dd078a2009-09-02 22:59:36 +000058 return 0;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Douglas Gregor2dd078a2009-09-02 22:59:36 +000061 return 0;
62}
63
John McCallf7a1a742009-11-24 19:00:30 +000064static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
65 LookupResult::Filter filter = R.makeFilter();
66 while (filter.hasNext()) {
67 NamedDecl *Orig = filter.next();
68 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
69 if (!Repl)
70 filter.erase();
71 else if (Repl != Orig)
72 filter.replace(Repl);
73 }
74 filter.done();
75}
76
Douglas Gregor2dd078a2009-09-02 22:59:36 +000077TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor014e88d2009-11-03 23:16:33 +000078 const CXXScopeSpec &SS,
79 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +000080 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +000081 bool EnteringContext,
Douglas Gregor2dd078a2009-09-02 22:59:36 +000082 TemplateTy &TemplateResult) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +000083 assert(getLangOptions().CPlusPlus && "No template names in C!");
84
Douglas Gregor014e88d2009-11-03 23:16:33 +000085 DeclarationName TName;
86
87 switch (Name.getKind()) {
88 case UnqualifiedId::IK_Identifier:
89 TName = DeclarationName(Name.Identifier);
90 break;
91
92 case UnqualifiedId::IK_OperatorFunctionId:
93 TName = Context.DeclarationNames.getCXXOperatorName(
94 Name.OperatorFunctionId.Operator);
95 break;
96
Sean Hunte6252d12009-11-28 08:58:14 +000097 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +000098 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
99 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000100
Douglas Gregor014e88d2009-11-03 23:16:33 +0000101 default:
102 return TNK_Non_template;
103 }
Mike Stump1eb44332009-09-09 15:08:12 +0000104
John McCallf7a1a742009-11-24 19:00:30 +0000105 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Douglas Gregorbfea2392009-12-31 08:11:17 +0000107 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
108 LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +0000109 R.suppressDiagnostics();
110 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
111 if (R.empty())
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000112 return TNK_Non_template;
113
John McCall0bd6feb2009-12-02 08:04:21 +0000114 TemplateName Template;
115 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000116
John McCall0bd6feb2009-12-02 08:04:21 +0000117 unsigned ResultCount = R.end() - R.begin();
118 if (ResultCount > 1) {
119 // We assume that we'll preserve the qualifier from a function
120 // template name in other ways.
121 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
122 TemplateKind = TNK_Function_template;
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000123 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000124 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
125
126 if (SS.isSet() && !SS.isInvalid()) {
127 NestedNameSpecifier *Qualifier
128 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
129 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
130 } else {
131 Template = TemplateName(TD);
132 }
133
134 if (isa<FunctionTemplateDecl>(TD))
135 TemplateKind = TNK_Function_template;
136 else {
137 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
138 TemplateKind = TNK_Type_template;
139 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000140 }
Mike Stump1eb44332009-09-09 15:08:12 +0000141
John McCall0bd6feb2009-12-02 08:04:21 +0000142 TemplateResult = TemplateTy::make(Template);
143 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000144}
145
Douglas Gregor84d0a192010-01-12 21:28:44 +0000146bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
147 SourceLocation IILoc,
148 Scope *S,
149 const CXXScopeSpec *SS,
150 TemplateTy &SuggestedTemplate,
151 TemplateNameKind &SuggestedKind) {
152 // We can't recover unless there's a dependent scope specifier preceding the
153 // template name.
154 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
155 computeDeclContext(*SS))
156 return false;
157
158 // The code is missing a 'template' keyword prior to the dependent template
159 // name.
160 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
161 Diag(IILoc, diag::err_template_kw_missing)
162 << Qualifier << II.getName()
163 << CodeModificationHint::CreateInsertion(IILoc, "template ");
164 SuggestedTemplate
165 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
166 SuggestedKind = TNK_Dependent_template_name;
167 return true;
168}
169
John McCallf7a1a742009-11-24 19:00:30 +0000170void Sema::LookupTemplateName(LookupResult &Found,
171 Scope *S, const CXXScopeSpec &SS,
172 QualType ObjectType,
173 bool EnteringContext) {
174 // Determine where to perform name lookup
175 DeclContext *LookupCtx = 0;
176 bool isDependent = false;
177 if (!ObjectType.isNull()) {
178 // This nested-name-specifier occurs in a member access expression, e.g.,
179 // x->B::f, and we are looking into the type of the object.
180 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
181 LookupCtx = computeDeclContext(ObjectType);
182 isDependent = ObjectType->isDependentType();
183 assert((isDependent || !ObjectType->isIncompleteType()) &&
184 "Caller should have completed object type");
185 } else if (SS.isSet()) {
186 // This nested-name-specifier occurs after another nested-name-specifier,
187 // so long into the context associated with the prior nested-name-specifier.
188 LookupCtx = computeDeclContext(SS, EnteringContext);
189 isDependent = isDependentScopeSpecifier(SS);
190
191 // The declaration context must be complete.
192 if (LookupCtx && RequireCompleteDeclContext(SS))
193 return;
194 }
195
196 bool ObjectTypeSearchedInScope = false;
197 if (LookupCtx) {
198 // Perform "qualified" name lookup into the declaration context we
199 // computed, which is either the type of the base of a member access
200 // expression or the declaration context associated with a prior
201 // nested-name-specifier.
202 LookupQualifiedName(Found, LookupCtx);
203
204 if (!ObjectType.isNull() && Found.empty()) {
205 // C++ [basic.lookup.classref]p1:
206 // In a class member access expression (5.2.5), if the . or -> token is
207 // immediately followed by an identifier followed by a <, the
208 // identifier must be looked up to determine whether the < is the
209 // beginning of a template argument list (14.2) or a less-than operator.
210 // The identifier is first looked up in the class of the object
211 // expression. If the identifier is not found, it is then looked up in
212 // the context of the entire postfix-expression and shall name a class
213 // or function template.
214 //
215 // FIXME: When we're instantiating a template, do we actually have to
216 // look in the scope of the template? Seems fishy...
217 if (S) LookupName(Found, S);
218 ObjectTypeSearchedInScope = true;
219 }
220 } else if (isDependent) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000221 // We cannot look into a dependent object type or nested nme
222 // specifier.
John McCallf7a1a742009-11-24 19:00:30 +0000223 return;
224 } else {
225 // Perform unqualified name lookup in the current scope.
226 LookupName(Found, S);
227 }
228
229 // FIXME: Cope with ambiguous name-lookup results.
230 assert(!Found.isAmbiguous() &&
231 "Cannot handle template name-lookup ambiguities");
232
Douglas Gregor2e933882010-01-12 17:06:20 +0000233 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000234 // If we did not find any names, attempt to correct any typos.
235 DeclarationName Name = Found.getLookupName();
236 if (CorrectTypo(Found, S, &SS, LookupCtx)) {
237 FilterAcceptableTemplateNames(Context, Found);
238 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
239 if (LookupCtx)
240 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
241 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
242 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
243 Found.getLookupName().getAsString());
244 else
245 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
246 << Name << Found.getLookupName()
247 << CodeModificationHint::CreateReplacement(Found.getNameLoc(),
248 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000249 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
250 Diag(Template->getLocation(), diag::note_previous_decl)
251 << Template->getDeclName();
Douglas Gregorbfea2392009-12-31 08:11:17 +0000252 } else
253 Found.clear();
254 } else {
255 Found.clear();
256 }
257 }
258
John McCallf7a1a742009-11-24 19:00:30 +0000259 FilterAcceptableTemplateNames(Context, Found);
260 if (Found.empty())
261 return;
262
263 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
264 // C++ [basic.lookup.classref]p1:
265 // [...] If the lookup in the class of the object expression finds a
266 // template, the name is also looked up in the context of the entire
267 // postfix-expression and [...]
268 //
269 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
270 LookupOrdinaryName);
271 LookupName(FoundOuter, S);
272 FilterAcceptableTemplateNames(Context, FoundOuter);
273 // FIXME: Handle ambiguities in this lookup better
274
275 if (FoundOuter.empty()) {
276 // - if the name is not found, the name found in the class of the
277 // object expression is used, otherwise
278 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
279 // - if the name is found in the context of the entire
280 // postfix-expression and does not name a class template, the name
281 // found in the class of the object expression is used, otherwise
282 } else {
283 // - if the name found is a class template, it must refer to the same
284 // entity as the one found in the class of the object expression,
285 // otherwise the program is ill-formed.
286 if (!Found.isSingleResult() ||
287 Found.getFoundDecl()->getCanonicalDecl()
288 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
289 Diag(Found.getNameLoc(),
290 diag::err_nested_name_member_ref_lookup_ambiguous)
291 << Found.getLookupName();
292 Diag(Found.getRepresentativeDecl()->getLocation(),
293 diag::note_ambig_member_ref_object_type)
294 << ObjectType;
295 Diag(FoundOuter.getFoundDecl()->getLocation(),
296 diag::note_ambig_member_ref_scope);
297
298 // Recover by taking the template that we found in the object
299 // expression's type.
300 }
301 }
302 }
303}
304
John McCall2f841ba2009-12-02 03:53:29 +0000305/// ActOnDependentIdExpression - Handle a dependent id-expression that
306/// was just parsed. This is only possible with an explicit scope
307/// specifier naming a dependent type.
John McCallf7a1a742009-11-24 19:00:30 +0000308Sema::OwningExprResult
309Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
310 DeclarationName Name,
311 SourceLocation NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000312 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000313 const TemplateArgumentListInfo *TemplateArgs) {
314 NestedNameSpecifier *Qualifier
315 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
316
John McCall2f841ba2009-12-02 03:53:29 +0000317 if (!isAddressOfOperand &&
318 isa<CXXMethodDecl>(CurContext) &&
319 cast<CXXMethodDecl>(CurContext)->isInstance()) {
320 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
321
John McCallf7a1a742009-11-24 19:00:30 +0000322 // Since the 'this' expression is synthesized, we don't need to
323 // perform the double-lookup check.
324 NamedDecl *FirstQualifierInScope = 0;
325
John McCallaa81e162009-12-01 22:10:20 +0000326 return Owned(CXXDependentScopeMemberExpr::Create(Context,
327 /*This*/ 0, ThisType,
328 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000329 /*Op*/ SourceLocation(),
330 Qualifier, SS.getRange(),
331 FirstQualifierInScope,
332 Name, NameLoc,
333 TemplateArgs));
334 }
335
336 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
337}
338
339Sema::OwningExprResult
340Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
341 DeclarationName Name,
342 SourceLocation NameLoc,
343 const TemplateArgumentListInfo *TemplateArgs) {
344 return Owned(DependentScopeDeclRefExpr::Create(Context,
345 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
346 SS.getRange(),
347 Name, NameLoc,
348 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000349}
350
Douglas Gregor72c3f312008-12-05 18:15:24 +0000351/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
352/// that the template parameter 'PrevDecl' is being shadowed by a new
353/// declaration at location Loc. Returns true to indicate that this is
354/// an error, and false otherwise.
355bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000356 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000357
358 // Microsoft Visual C++ permits template parameters to be shadowed.
359 if (getLangOptions().Microsoft)
360 return false;
361
362 // C++ [temp.local]p4:
363 // A template-parameter shall not be redeclared within its
364 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000365 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000366 << cast<NamedDecl>(PrevDecl)->getDeclName();
367 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
368 return true;
369}
370
Douglas Gregor2943aed2009-03-03 04:44:36 +0000371/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000372/// the parameter D to reference the templated declaration and return a pointer
373/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000374TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000375 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000376 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000377 return Temp;
378 }
379 return 0;
380}
381
Douglas Gregor788cd062009-11-11 01:00:40 +0000382static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
383 const ParsedTemplateArgument &Arg) {
384
385 switch (Arg.getKind()) {
386 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000387 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000388 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
389 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000390 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000391 return TemplateArgumentLoc(TemplateArgument(T), DI);
392 }
393
394 case ParsedTemplateArgument::NonType: {
395 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
396 return TemplateArgumentLoc(TemplateArgument(E), E);
397 }
398
399 case ParsedTemplateArgument::Template: {
400 TemplateName Template
401 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
402 return TemplateArgumentLoc(TemplateArgument(Template),
403 Arg.getScopeSpec().getRange(),
404 Arg.getLocation());
405 }
406 }
407
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000408 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000409 return TemplateArgumentLoc();
410}
411
412/// \brief Translates template arguments as provided by the parser
413/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000414void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
415 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000416 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000417 TemplateArgs.addArgument(translateTemplateArgument(*this,
418 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000419}
420
Douglas Gregor72c3f312008-12-05 18:15:24 +0000421/// ActOnTypeParameter - Called when a C++ template type parameter
422/// (e.g., "typename T") has been parsed. Typename specifies whether
423/// the keyword "typename" was used to declare the type parameter
424/// (otherwise, "class" was used), and KeyLoc is the location of the
425/// "class" or "typename" keyword. ParamName is the name of the
426/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000427/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000428/// If the type parameter has a default argument, it will be added
429/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000430Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000431 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000432 SourceLocation KeyLoc,
433 IdentifierInfo *ParamName,
434 SourceLocation ParamNameLoc,
435 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000436 assert(S->isTemplateParamScope() &&
437 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000438 bool Invalid = false;
439
440 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000441 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000442 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000443 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000444 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000445 }
446
Douglas Gregorddc29e12009-02-06 22:42:48 +0000447 SourceLocation Loc = ParamNameLoc;
448 if (!ParamName)
449 Loc = KeyLoc;
450
Douglas Gregor72c3f312008-12-05 18:15:24 +0000451 TemplateTypeParmDecl *Param
Mike Stump1eb44332009-09-09 15:08:12 +0000452 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
453 Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000454 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000455 if (Invalid)
456 Param->setInvalidDecl();
457
458 if (ParamName) {
459 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000460 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000461 IdResolver.AddDecl(Param);
462 }
463
Chris Lattnerb28317a2009-03-28 19:18:32 +0000464 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000465}
466
Douglas Gregord684b002009-02-10 19:49:53 +0000467/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000468/// Default) to the given template type parameter (TypeParam).
469void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000470 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000471 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000472 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000473 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000474 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000475
John McCalla93c9342009-12-07 02:54:59 +0000476 TypeSourceInfo *DefaultTInfo;
477 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000478
John McCalla93c9342009-12-07 02:54:59 +0000479 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000480
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000481 // C++0x [temp.param]p9:
482 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000483 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000484 if (Parm->isParameterPack()) {
485 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000486 return;
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregord684b002009-02-10 19:49:53 +0000489 // C++ [temp.param]p14:
490 // A template-parameter shall not be used in its own default argument.
491 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Douglas Gregord684b002009-02-10 19:49:53 +0000493 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000494 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000495 Parm->setInvalidDecl();
496 return;
497 }
498
John McCalla93c9342009-12-07 02:54:59 +0000499 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000500}
501
Douglas Gregor2943aed2009-03-03 04:44:36 +0000502/// \brief Check that the type of a non-type template parameter is
503/// well-formed.
504///
505/// \returns the (possibly-promoted) parameter type if valid;
506/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000507QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000508Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
509 // C++ [temp.param]p4:
510 //
511 // A non-type template-parameter shall have one of the following
512 // (optionally cv-qualified) types:
513 //
514 // -- integral or enumeration type,
515 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000516 // -- pointer to object or pointer to function,
517 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000518 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
519 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000520 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000521 T->isReferenceType() ||
522 // -- pointer to member.
523 T->isMemberPointerType() ||
524 // If T is a dependent type, we can't do the check now, so we
525 // assume that it is well-formed.
526 T->isDependentType())
527 return T;
528 // C++ [temp.param]p8:
529 //
530 // A non-type template-parameter of type "array of T" or
531 // "function returning T" is adjusted to be of type "pointer to
532 // T" or "pointer to function returning T", respectively.
533 else if (T->isArrayType())
534 // FIXME: Keep the type prior to promotion?
535 return Context.getArrayDecayedType(T);
536 else if (T->isFunctionType())
537 // FIXME: Keep the type prior to promotion?
538 return Context.getPointerType(T);
539
540 Diag(Loc, diag::err_template_nontype_parm_bad_type)
541 << T;
542
543 return QualType();
544}
545
Douglas Gregor72c3f312008-12-05 18:15:24 +0000546/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
547/// template parameter (e.g., "int Size" in "template<int Size>
548/// class Array") has been parsed. S is the current scope and D is
549/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000550Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000551 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000552 unsigned Position) {
John McCalla93c9342009-12-07 02:54:59 +0000553 TypeSourceInfo *TInfo = 0;
554 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000555
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000556 assert(S->isTemplateParamScope() &&
557 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000558 bool Invalid = false;
559
560 IdentifierInfo *ParamName = D.getIdentifier();
561 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000562 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000563 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000564 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000565 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000566 }
567
Douglas Gregor2943aed2009-03-03 04:44:36 +0000568 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000569 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000570 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000571 Invalid = true;
572 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000573
Douglas Gregor72c3f312008-12-05 18:15:24 +0000574 NonTypeTemplateParmDecl *Param
575 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000576 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000577 if (Invalid)
578 Param->setInvalidDecl();
579
580 if (D.getIdentifier()) {
581 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000582 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000583 IdResolver.AddDecl(Param);
584 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000585 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000586}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000587
Douglas Gregord684b002009-02-10 19:49:53 +0000588/// \brief Adds a default argument to the given non-type template
589/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000590void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000591 SourceLocation EqualLoc,
592 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000593 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000594 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000595 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Douglas Gregord684b002009-02-10 19:49:53 +0000597 // C++ [temp.param]p14:
598 // A template-parameter shall not be used in its own default argument.
599 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Douglas Gregord684b002009-02-10 19:49:53 +0000601 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000602 TemplateArgument Converted;
603 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
604 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000605 TemplateParm->setInvalidDecl();
606 return;
607 }
608
Anders Carlssone9146f22009-05-01 19:49:17 +0000609 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000610}
611
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000612
613/// ActOnTemplateTemplateParameter - Called when a C++ template template
614/// parameter (e.g. T in template <template <typename> class T> class array)
615/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000616Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
617 SourceLocation TmpLoc,
618 TemplateParamsTy *Params,
619 IdentifierInfo *Name,
620 SourceLocation NameLoc,
621 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000622 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000623 assert(S->isTemplateParamScope() &&
624 "Template template parameter not in template parameter scope!");
625
626 // Construct the parameter object.
627 TemplateTemplateParmDecl *Param =
628 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
629 Position, Name,
630 (TemplateParameterList*)Params);
631
632 // Make sure the parameter is valid.
633 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
634 // do anything yet. However, if the template parameter list or (eventual)
635 // default value is ever invalidated, that will propagate here.
636 bool Invalid = false;
637 if (Invalid) {
638 Param->setInvalidDecl();
639 }
640
641 // If the tt-param has a name, then link the identifier into the scope
642 // and lookup mechanisms.
643 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000644 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000645 IdResolver.AddDecl(Param);
646 }
647
Chris Lattnerb28317a2009-03-28 19:18:32 +0000648 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000649}
650
Douglas Gregord684b002009-02-10 19:49:53 +0000651/// \brief Adds a default argument to the given template template
652/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000653void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000654 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000655 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000656 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000657 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000658
Douglas Gregord684b002009-02-10 19:49:53 +0000659 // C++ [temp.param]p14:
660 // A template-parameter shall not be used in its own default argument.
661 // FIXME: Implement this check! Needs a recursive walk over the types.
662
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000663 // Check only that we have a template template argument. We don't want to
664 // try to check well-formedness now, because our template template parameter
665 // might have dependent types in its template parameters, which we wouldn't
666 // be able to match now.
667 //
668 // If none of the template template parameter's template arguments mention
669 // other template parameters, we could actually perform more checking here.
670 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000671 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000672 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
673 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
674 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000675 return;
676 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000677
Douglas Gregor788cd062009-11-11 01:00:40 +0000678 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000679}
680
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000681/// ActOnTemplateParameterList - Builds a TemplateParameterList that
682/// contains the template parameters in Params/NumParams.
683Sema::TemplateParamsTy *
684Sema::ActOnTemplateParameterList(unsigned Depth,
685 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000686 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000687 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000688 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000689 SourceLocation RAngleLoc) {
690 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000691 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000692
Douglas Gregorddc29e12009-02-06 22:42:48 +0000693 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000694 (NamedDecl**)Params, NumParams,
695 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000696}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000697
Douglas Gregor212e81c2009-03-25 00:13:59 +0000698Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000699Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000700 SourceLocation KWLoc, const CXXScopeSpec &SS,
701 IdentifierInfo *Name, SourceLocation NameLoc,
702 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000703 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000704 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000705 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000706 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000707 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000708 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000709
710 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000711 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000712 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000713
John McCall05b23ea2009-09-14 21:59:20 +0000714 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
715 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000716
717 // There is no such thing as an unnamed class template.
718 if (!Name) {
719 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000720 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000721 }
722
723 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000724 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000725 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000726 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000727 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000728 if (RequireCompleteDeclContext(SS))
729 return true;
730
Douglas Gregor05396e22009-08-25 17:23:04 +0000731 SemanticContext = computeDeclContext(SS, true);
732 if (!SemanticContext) {
733 // FIXME: Produce a reasonable diagnostic here
734 return true;
735 }
Mike Stump1eb44332009-09-09 15:08:12 +0000736
John McCalla24dc2e2009-11-17 02:14:36 +0000737 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000738 } else {
739 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000740 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000741 }
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Douglas Gregorddc29e12009-02-06 22:42:48 +0000743 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
744 NamedDecl *PrevDecl = 0;
745 if (Previous.begin() != Previous.end())
746 PrevDecl = *Previous.begin();
747
Douglas Gregorddc29e12009-02-06 22:42:48 +0000748 // If there is a previous declaration with the same name, check
749 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000750 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000751 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000752
753 // We may have found the injected-class-name of a class template,
754 // class template partial specialization, or class template specialization.
755 // In these cases, grab the template that is being defined or specialized.
756 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
757 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
758 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
759 PrevClassTemplate
760 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
761 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
762 PrevClassTemplate
763 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
764 ->getSpecializedTemplate();
765 }
766 }
767
John McCall65c49462009-12-18 11:25:59 +0000768 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000769 // C++ [namespace.memdef]p3:
770 // [...] When looking for a prior declaration of a class or a function
771 // declared as a friend, and when the name of the friend class or
772 // function is neither a qualified name nor a template-id, scopes outside
773 // the innermost enclosing namespace scope are not considered.
774 DeclContext *OutermostContext = CurContext;
775 while (!OutermostContext->isFileContext())
776 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000777
778 if (PrevDecl &&
779 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
780 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCalle129d442009-12-17 23:21:11 +0000781 SemanticContext = PrevDecl->getDeclContext();
782 } else {
783 // Declarations in outer scopes don't matter. However, the outermost
784 // context we computed is the semantic context for our new
785 // declaration.
786 PrevDecl = PrevClassTemplate = 0;
787 SemanticContext = OutermostContext;
788 }
789
790 if (CurContext->isDependentContext()) {
791 // If this is a dependent context, we don't want to link the friend
792 // class template to the template in scope, because that would perform
793 // checking of the template parameter lists that can't be performed
794 // until the outer context is instantiated.
795 PrevDecl = PrevClassTemplate = 0;
796 }
797 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
798 PrevDecl = PrevClassTemplate = 0;
799
Douglas Gregorddc29e12009-02-06 22:42:48 +0000800 if (PrevClassTemplate) {
801 // Ensure that the template parameter lists are compatible.
802 if (!TemplateParameterListsAreEqual(TemplateParams,
803 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000804 /*Complain=*/true,
805 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000806 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000807
808 // C++ [temp.class]p4:
809 // In a redeclaration, partial specialization, explicit
810 // specialization or explicit instantiation of a class template,
811 // the class-key shall agree in kind with the original class
812 // template declaration (7.1.5.3).
813 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000814 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000815 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000816 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000817 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000818 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000819 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000820 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000821 }
822
Douglas Gregorddc29e12009-02-06 22:42:48 +0000823 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000824 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000825 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
826 Diag(NameLoc, diag::err_redefinition) << Name;
827 Diag(Def->getLocation(), diag::note_previous_definition);
828 // FIXME: Would it make sense to try to "forget" the previous
829 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000830 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000831 }
832 }
833 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
834 // Maybe we will complain about the shadowed template parameter.
835 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
836 // Just pretend that we didn't see the previous declaration.
837 PrevDecl = 0;
838 } else if (PrevDecl) {
839 // C++ [temp]p5:
840 // A class template shall not have the same name as any other
841 // template, class, function, object, enumeration, enumerator,
842 // namespace, or type in the same scope (3.3), except as specified
843 // in (14.5.4).
844 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
845 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000846 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000847 }
848
Douglas Gregord684b002009-02-10 19:49:53 +0000849 // Check the template parameter list of this declaration, possibly
850 // merging in the template parameter list from the previous class
851 // template declaration.
852 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000853 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
854 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000855 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Douglas Gregor7da97d02009-05-10 22:57:19 +0000857 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000858 // declaration!
859
Mike Stump1eb44332009-09-09 15:08:12 +0000860 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000861 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000862 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000863 PrevClassTemplate->getTemplatedDecl() : 0,
864 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000865
866 ClassTemplateDecl *NewTemplate
867 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
868 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000869 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000870 NewClass->setDescribedClassTemplate(NewTemplate);
871
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000872 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000873 QualType T =
874 Context.getTypeDeclType(NewClass,
875 PrevClassTemplate?
876 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000877 assert(T->isDependentType() && "Class template type is not dependent?");
878 (void)T;
879
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000880 // If we are providing an explicit specialization of a member that is a
881 // class template, make a note of that.
882 if (PrevClassTemplate &&
883 PrevClassTemplate->getInstantiatedFromMemberTemplate())
884 PrevClassTemplate->setMemberSpecialization();
885
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000886 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000887 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000888 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Douglas Gregorddc29e12009-02-06 22:42:48 +0000890 // Set the lexical context of these templates
891 NewClass->setLexicalDeclContext(CurContext);
892 NewTemplate->setLexicalDeclContext(CurContext);
893
John McCall0f434ec2009-07-31 02:45:11 +0000894 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000895 NewClass->startDefinition();
896
897 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000898 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000899
John McCall05b23ea2009-09-14 21:59:20 +0000900 if (TUK != TUK_Friend)
901 PushOnScopeChains(NewTemplate, S);
902 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000903 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000904 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000905 NewClass->setAccess(PrevClassTemplate->getAccess());
906 }
John McCall05b23ea2009-09-14 21:59:20 +0000907
Douglas Gregord85bea22009-09-26 06:47:28 +0000908 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
909 PrevClassTemplate != NULL);
910
John McCall05b23ea2009-09-14 21:59:20 +0000911 // Friend templates are visible in fairly strange ways.
912 if (!CurContext->isDependentContext()) {
913 DeclContext *DC = SemanticContext->getLookupContext();
914 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
915 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
916 PushOnScopeChains(NewTemplate, EnclosingScope,
917 /* AddToContext = */ false);
918 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000919
920 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
921 NewClass->getLocation(),
922 NewTemplate,
923 /*FIXME:*/NewClass->getLocation());
924 Friend->setAccess(AS_public);
925 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000926 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000927
Douglas Gregord684b002009-02-10 19:49:53 +0000928 if (Invalid) {
929 NewTemplate->setInvalidDecl();
930 NewClass->setInvalidDecl();
931 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000932 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000933}
934
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000935/// \brief Diagnose the presence of a default template argument on a
936/// template parameter, which is ill-formed in certain contexts.
937///
938/// \returns true if the default template argument should be dropped.
939static bool DiagnoseDefaultTemplateArgument(Sema &S,
940 Sema::TemplateParamListContext TPC,
941 SourceLocation ParamLoc,
942 SourceRange DefArgRange) {
943 switch (TPC) {
944 case Sema::TPC_ClassTemplate:
945 return false;
946
947 case Sema::TPC_FunctionTemplate:
948 // C++ [temp.param]p9:
949 // A default template-argument shall not be specified in a
950 // function template declaration or a function template
951 // definition [...]
952 // (This sentence is not in C++0x, per DR226).
953 if (!S.getLangOptions().CPlusPlus0x)
954 S.Diag(ParamLoc,
955 diag::err_template_parameter_default_in_function_template)
956 << DefArgRange;
957 return false;
958
959 case Sema::TPC_ClassTemplateMember:
960 // C++0x [temp.param]p9:
961 // A default template-argument shall not be specified in the
962 // template-parameter-lists of the definition of a member of a
963 // class template that appears outside of the member's class.
964 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
965 << DefArgRange;
966 return true;
967
968 case Sema::TPC_FriendFunctionTemplate:
969 // C++ [temp.param]p9:
970 // A default template-argument shall not be specified in a
971 // friend template declaration.
972 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
973 << DefArgRange;
974 return true;
975
976 // FIXME: C++0x [temp.param]p9 allows default template-arguments
977 // for friend function templates if there is only a single
978 // declaration (and it is a definition). Strange!
979 }
980
981 return false;
982}
983
Douglas Gregord684b002009-02-10 19:49:53 +0000984/// \brief Checks the validity of a template parameter list, possibly
985/// considering the template parameter list from a previous
986/// declaration.
987///
988/// If an "old" template parameter list is provided, it must be
989/// equivalent (per TemplateParameterListsAreEqual) to the "new"
990/// template parameter list.
991///
992/// \param NewParams Template parameter list for a new template
993/// declaration. This template parameter list will be updated with any
994/// default arguments that are carried through from the previous
995/// template parameter list.
996///
997/// \param OldParams If provided, template parameter list from a
998/// previous declaration of the same template. Default template
999/// arguments will be merged from the old template parameter list to
1000/// the new template parameter list.
1001///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001002/// \param TPC Describes the context in which we are checking the given
1003/// template parameter list.
1004///
Douglas Gregord684b002009-02-10 19:49:53 +00001005/// \returns true if an error occurred, false otherwise.
1006bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001007 TemplateParameterList *OldParams,
1008 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001009 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Douglas Gregord684b002009-02-10 19:49:53 +00001011 // C++ [temp.param]p10:
1012 // The set of default template-arguments available for use with a
1013 // template declaration or definition is obtained by merging the
1014 // default arguments from the definition (if in scope) and all
1015 // declarations in scope in the same way default function
1016 // arguments are (8.3.6).
1017 bool SawDefaultArgument = false;
1018 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001019
Anders Carlsson49d25572009-06-12 23:20:15 +00001020 bool SawParameterPack = false;
1021 SourceLocation ParameterPackLoc;
1022
Mike Stump1a35fde2009-02-11 23:03:27 +00001023 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001024 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001025 if (OldParams)
1026 OldParam = OldParams->begin();
1027
1028 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1029 NewParamEnd = NewParams->end();
1030 NewParam != NewParamEnd; ++NewParam) {
1031 // Variables used to diagnose redundant default arguments
1032 bool RedundantDefaultArg = false;
1033 SourceLocation OldDefaultLoc;
1034 SourceLocation NewDefaultLoc;
1035
1036 // Variables used to diagnose missing default arguments
1037 bool MissingDefaultArg = false;
1038
Anders Carlsson49d25572009-06-12 23:20:15 +00001039 // C++0x [temp.param]p11:
1040 // If a template parameter of a class template is a template parameter pack,
1041 // it must be the last template parameter.
1042 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001043 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001044 diag::err_template_param_pack_must_be_last_template_parameter);
1045 Invalid = true;
1046 }
1047
Douglas Gregord684b002009-02-10 19:49:53 +00001048 if (TemplateTypeParmDecl *NewTypeParm
1049 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001050 // Check the presence of a default argument here.
1051 if (NewTypeParm->hasDefaultArgument() &&
1052 DiagnoseDefaultTemplateArgument(*this, TPC,
1053 NewTypeParm->getLocation(),
1054 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1055 .getFullSourceRange()))
1056 NewTypeParm->removeDefaultArgument();
1057
1058 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001059 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001060 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Anders Carlsson49d25572009-06-12 23:20:15 +00001062 if (NewTypeParm->isParameterPack()) {
1063 assert(!NewTypeParm->hasDefaultArgument() &&
1064 "Parameter packs can't have a default argument!");
1065 SawParameterPack = true;
1066 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001067 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001068 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001069 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1070 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1071 SawDefaultArgument = true;
1072 RedundantDefaultArg = true;
1073 PreviousDefaultArgLoc = NewDefaultLoc;
1074 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1075 // Merge the default argument from the old declaration to the
1076 // new declaration.
1077 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001078 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001079 true);
1080 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1081 } else if (NewTypeParm->hasDefaultArgument()) {
1082 SawDefaultArgument = true;
1083 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1084 } else if (SawDefaultArgument)
1085 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001086 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001087 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001088 // Check the presence of a default argument here.
1089 if (NewNonTypeParm->hasDefaultArgument() &&
1090 DiagnoseDefaultTemplateArgument(*this, TPC,
1091 NewNonTypeParm->getLocation(),
1092 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1093 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1094 NewNonTypeParm->setDefaultArgument(0);
1095 }
1096
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001097 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001098 NonTypeTemplateParmDecl *OldNonTypeParm
1099 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001100 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001101 NewNonTypeParm->hasDefaultArgument()) {
1102 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1103 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1104 SawDefaultArgument = true;
1105 RedundantDefaultArg = true;
1106 PreviousDefaultArgLoc = NewDefaultLoc;
1107 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1108 // Merge the default argument from the old declaration to the
1109 // new declaration.
1110 SawDefaultArgument = true;
1111 // FIXME: We need to create a new kind of "default argument"
1112 // expression that points to a previous template template
1113 // parameter.
1114 NewNonTypeParm->setDefaultArgument(
1115 OldNonTypeParm->getDefaultArgument());
1116 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1117 } else if (NewNonTypeParm->hasDefaultArgument()) {
1118 SawDefaultArgument = true;
1119 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1120 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001121 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001122 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001123 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001124 TemplateTemplateParmDecl *NewTemplateParm
1125 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001126 if (NewTemplateParm->hasDefaultArgument() &&
1127 DiagnoseDefaultTemplateArgument(*this, TPC,
1128 NewTemplateParm->getLocation(),
1129 NewTemplateParm->getDefaultArgument().getSourceRange()))
1130 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1131
1132 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001133 TemplateTemplateParmDecl *OldTemplateParm
1134 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001135 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001136 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001137 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1138 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001139 SawDefaultArgument = true;
1140 RedundantDefaultArg = true;
1141 PreviousDefaultArgLoc = NewDefaultLoc;
1142 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1143 // Merge the default argument from the old declaration to the
1144 // new declaration.
1145 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001146 // FIXME: We need to create a new kind of "default argument" expression
1147 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001148 NewTemplateParm->setDefaultArgument(
1149 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001150 PreviousDefaultArgLoc
1151 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001152 } else if (NewTemplateParm->hasDefaultArgument()) {
1153 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001154 PreviousDefaultArgLoc
1155 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001156 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001157 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001158 }
1159
1160 if (RedundantDefaultArg) {
1161 // C++ [temp.param]p12:
1162 // A template-parameter shall not be given default arguments
1163 // by two different declarations in the same scope.
1164 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1165 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1166 Invalid = true;
1167 } else if (MissingDefaultArg) {
1168 // C++ [temp.param]p11:
1169 // If a template-parameter has a default template-argument,
1170 // all subsequent template-parameters shall have a default
1171 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001172 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001173 diag::err_template_param_default_arg_missing);
1174 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1175 Invalid = true;
1176 }
1177
1178 // If we have an old template parameter list that we're merging
1179 // in, move on to the next parameter.
1180 if (OldParams)
1181 ++OldParam;
1182 }
1183
1184 return Invalid;
1185}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001186
Mike Stump1eb44332009-09-09 15:08:12 +00001187/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001188/// specifier, returning the template parameter list that applies to the
1189/// name.
1190///
1191/// \param DeclStartLoc the start of the declaration that has a scope
1192/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001193///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001194/// \param SS the scope specifier that will be matched to the given template
1195/// parameter lists. This scope specifier precedes a qualified name that is
1196/// being declared.
1197///
1198/// \param ParamLists the template parameter lists, from the outermost to the
1199/// innermost template parameter lists.
1200///
1201/// \param NumParamLists the number of template parameter lists in ParamLists.
1202///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001203/// \param IsExplicitSpecialization will be set true if the entity being
1204/// declared is an explicit specialization, false otherwise.
1205///
Mike Stump1eb44332009-09-09 15:08:12 +00001206/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001207/// name that is preceded by the scope specifier @p SS. This template
1208/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001209/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001210/// template specialization), or may be NULL (if we were's declaring isn't
1211/// itself a template).
1212TemplateParameterList *
1213Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1214 const CXXScopeSpec &SS,
1215 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001216 unsigned NumParamLists,
1217 bool &IsExplicitSpecialization) {
1218 IsExplicitSpecialization = false;
1219
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001220 // Find the template-ids that occur within the nested-name-specifier. These
1221 // template-ids will match up with the template parameter lists.
1222 llvm::SmallVector<const TemplateSpecializationType *, 4>
1223 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001224 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1225 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001226 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1227 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001228 const Type *T = NNS->getAsType();
1229 if (!T) break;
1230
1231 // C++0x [temp.expl.spec]p17:
1232 // A member or a member template may be nested within many
1233 // enclosing class templates. In an explicit specialization for
1234 // such a member, the member declaration shall be preceded by a
1235 // template<> for each enclosing class template that is
1236 // explicitly specialized.
1237 // We interpret this as forbidding typedefs of template
1238 // specializations in the scope specifiers of out-of-line decls.
1239 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) {
1240 const Type *UnderlyingT = TT->LookThroughTypedefs().getTypePtr();
1241 if (isa<TemplateSpecializationType>(UnderlyingT))
1242 // FIXME: better source location information.
1243 Diag(DeclStartLoc, diag::err_typedef_in_def_scope) << QualType(T,0);
1244 T = UnderlyingT;
1245 }
1246
Mike Stump1eb44332009-09-09 15:08:12 +00001247 if (const TemplateSpecializationType *SpecType
John McCall4b2b02b2009-12-15 02:19:47 +00001248 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001249 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1250 if (!Template)
1251 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Ted Kremenek6217b802009-07-29 21:53:49 +00001253 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001254 ClassTemplateSpecializationDecl *SpecDecl
1255 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1256 // If the nested name specifier refers to an explicit specialization,
1257 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001258 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1259 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001260 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001261 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001262 }
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001264 TemplateIdsInSpecifier.push_back(SpecType);
1265 }
1266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001268 // Reverse the list of template-ids in the scope specifier, so that we can
1269 // more easily match up the template-ids and the template parameter lists.
1270 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001272 SourceLocation FirstTemplateLoc = DeclStartLoc;
1273 if (NumParamLists)
1274 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001276 // Match the template-ids found in the specifier to the template parameter
1277 // lists.
1278 unsigned Idx = 0;
1279 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1280 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001281 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1282 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001283 if (Idx >= NumParamLists) {
1284 // We have a template-id without a corresponding template parameter
1285 // list.
1286 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001287 // FIXME: the location information here isn't great.
1288 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001289 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001290 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001291 << SS.getRange();
1292 } else {
1293 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1294 << SS.getRange()
1295 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1296 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001297 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001298 }
1299 return 0;
1300 }
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001302 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001303 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001304 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001305 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1306
Mike Stump1eb44332009-09-09 15:08:12 +00001307 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001308 = dyn_cast<ClassTemplateDecl>(Template)) {
1309 TemplateParameterList *ExpectedTemplateParams = 0;
1310 // Is this template-id naming the primary template?
1311 if (Context.hasSameType(TemplateId,
1312 ClassTemplate->getInjectedClassNameType(Context)))
1313 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1314 // ... or a partial specialization?
1315 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1316 = ClassTemplate->findPartialSpecialization(TemplateId))
1317 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1318
1319 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001320 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001321 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001322 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001323 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001324
1325 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001326 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001327 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001328 diag::err_template_param_list_matches_nontemplate)
1329 << TemplateId
1330 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001331 else
1332 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001333 }
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001335 // If there were at least as many template-ids as there were template
1336 // parameter lists, then there are no template parameter lists remaining for
1337 // the declaration itself.
1338 if (Idx >= NumParamLists)
1339 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001341 // If there were too many template parameter lists, complain about that now.
1342 if (Idx != NumParamLists - 1) {
1343 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001344 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001345 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001346 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1347 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001348 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1349 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001350
1351 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1352 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1353 diag::note_explicit_template_spec_does_not_need_header)
1354 << ExplicitSpecializationsInSpecifier.back();
1355 ExplicitSpecializationsInSpecifier.pop_back();
1356 }
1357
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001358 ++Idx;
1359 }
1360 }
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001362 // Return the last template parameter list, which corresponds to the
1363 // entity being declared.
1364 return ParamLists[NumParamLists - 1];
1365}
1366
Douglas Gregor7532dc62009-03-30 22:58:21 +00001367QualType Sema::CheckTemplateIdType(TemplateName Name,
1368 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001369 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001370 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001371 if (!Template) {
1372 // The template name does not resolve to a template, so we just
1373 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001374 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001375 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001376
Douglas Gregor40808ce2009-03-09 23:48:35 +00001377 // Check that the template argument list is well-formed for this
1378 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001379 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001380 TemplateArgs.size());
1381 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001382 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001383 return QualType();
1384
Mike Stump1eb44332009-09-09 15:08:12 +00001385 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001386 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001387 "Converted template argument list is too short!");
1388
1389 QualType CanonType;
1390
Douglas Gregorcaddba02009-11-12 18:38:13 +00001391 if (Name.isDependent() ||
1392 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001393 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001394 // This class template specialization is a dependent
1395 // type. Therefore, its canonical type is another class template
1396 // specialization type that contains all of the converted
1397 // arguments in canonical form. This ensures that, e.g., A<T> and
1398 // A<T, T> have identical types when A is declared as:
1399 //
1400 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001401 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001402 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001403 Converted.getFlatArguments(),
1404 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Douglas Gregor1275ae02009-07-28 23:00:59 +00001406 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001407 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001408 // In the future, we need to teach getTemplateSpecializationType to only
1409 // build the canonical type and return that to us.
1410 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001411 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001412 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001413 // Find the class template specialization declaration that
1414 // corresponds to these arguments.
1415 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001416 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001417 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001418 Converted.flatSize(),
1419 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001420 void *InsertPos = 0;
1421 ClassTemplateSpecializationDecl *Decl
1422 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1423 if (!Decl) {
1424 // This is the first time we have referenced this class template
1425 // specialization. Create the canonical declaration and add it to
1426 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001427 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001428 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001429 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001430 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001431 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001432 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1433 Decl->setLexicalDeclContext(CurContext);
1434 }
1435
1436 CanonType = Context.getTypeDeclType(Decl);
1437 }
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Douglas Gregor40808ce2009-03-09 23:48:35 +00001439 // Build the fully-sugared type for this class template
1440 // specialization, which refers back to the class template
1441 // specialization we created or found.
John McCalld5532b62009-11-23 01:53:49 +00001442 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001443}
1444
Douglas Gregorcc636682009-02-17 23:15:12 +00001445Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001446Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001447 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001448 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001449 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001450 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001451
Douglas Gregor40808ce2009-03-09 23:48:35 +00001452 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001453 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001454 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001455
John McCalld5532b62009-11-23 01:53:49 +00001456 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001457 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001458
1459 if (Result.isNull())
1460 return true;
1461
John McCalla93c9342009-12-07 02:54:59 +00001462 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001463 TemplateSpecializationTypeLoc TL
1464 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1465 TL.setTemplateNameLoc(TemplateLoc);
1466 TL.setLAngleLoc(LAngleLoc);
1467 TL.setRAngleLoc(RAngleLoc);
1468 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1469 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1470
1471 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001472}
John McCallf1bbbb42009-09-04 01:14:41 +00001473
John McCall6b2becf2009-09-08 17:47:29 +00001474Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1475 TagUseKind TUK,
1476 DeclSpec::TST TagSpec,
1477 SourceLocation TagLoc) {
1478 if (TypeResult.isInvalid())
1479 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001480
John McCall833ca992009-10-29 08:12:44 +00001481 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001482 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001483 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001484
John McCall6b2becf2009-09-08 17:47:29 +00001485 // Verify the tag specifier.
1486 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
John McCall6b2becf2009-09-08 17:47:29 +00001488 if (const RecordType *RT = Type->getAs<RecordType>()) {
1489 RecordDecl *D = RT->getDecl();
1490
1491 IdentifierInfo *Id = D->getIdentifier();
1492 assert(Id && "templated class must have an identifier");
1493
1494 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1495 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001496 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001497 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1498 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001499 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001500 }
1501 }
1502
John McCall6b2becf2009-09-08 17:47:29 +00001503 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1504
1505 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001506}
1507
John McCallf7a1a742009-11-24 19:00:30 +00001508Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1509 LookupResult &R,
1510 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001511 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001512 // FIXME: Can we do any checking at this point? I guess we could check the
1513 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001514 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001515 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001516
1517 // These should be filtered out by our callers.
1518 assert(!R.empty() && "empty lookup results when building templateid");
1519 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1520
1521 NestedNameSpecifier *Qualifier = 0;
1522 SourceRange QualifierRange;
1523 if (SS.isSet()) {
1524 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1525 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001526 }
1527
John McCallf7a1a742009-11-24 19:00:30 +00001528 bool Dependent
1529 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1530 &TemplateArgs);
1531 UnresolvedLookupExpr *ULE
1532 = UnresolvedLookupExpr::Create(Context, Dependent,
1533 Qualifier, QualifierRange,
1534 R.getLookupName(), R.getNameLoc(),
1535 RequiresADL, TemplateArgs);
1536 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1537 ULE->addDecl(*I);
1538
1539 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001540}
1541
John McCallf7a1a742009-11-24 19:00:30 +00001542// We actually only call this from template instantiation.
1543Sema::OwningExprResult
1544Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1545 DeclarationName Name,
1546 SourceLocation NameLoc,
1547 const TemplateArgumentListInfo &TemplateArgs) {
1548 DeclContext *DC;
1549 if (!(DC = computeDeclContext(SS, false)) ||
1550 DC->isDependentContext() ||
1551 RequireCompleteDeclContext(SS))
1552 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001553
John McCallf7a1a742009-11-24 19:00:30 +00001554 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1555 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
John McCallf7a1a742009-11-24 19:00:30 +00001557 if (R.isAmbiguous())
1558 return ExprError();
1559
1560 if (R.empty()) {
1561 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1562 << Name << SS.getRange();
1563 return ExprError();
1564 }
1565
1566 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1567 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1568 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1569 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1570 return ExprError();
1571 }
1572
1573 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001574}
1575
Douglas Gregorc45c2322009-03-31 00:43:58 +00001576/// \brief Form a dependent template name.
1577///
1578/// This action forms a dependent template name given the template
1579/// name and its (presumably dependent) scope specifier. For
1580/// example, given "MetaFun::template apply", the scope specifier \p
1581/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1582/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001583Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001584Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001585 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001586 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001587 TypeTy *ObjectType,
1588 bool EnteringContext) {
Douglas Gregor0707bc52010-01-19 16:01:07 +00001589 DeclContext *LookupCtx = 0;
1590 if (SS.isSet())
1591 LookupCtx = computeDeclContext(SS, EnteringContext);
1592 if (!LookupCtx && ObjectType)
1593 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1594 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001595 // C++0x [temp.names]p5:
1596 // If a name prefixed by the keyword template is not the name of
1597 // a template, the program is ill-formed. [Note: the keyword
1598 // template may not be applied to non-template members of class
1599 // templates. -end note ] [ Note: as is the case with the
1600 // typename prefix, the template prefix is allowed in cases
1601 // where it is not strictly necessary; i.e., when the
1602 // nested-name-specifier or the expression on the left of the ->
1603 // or . is not dependent on a template-parameter, or the use
1604 // does not appear in the scope of a template. -end note]
1605 //
1606 // Note: C++03 was more strict here, because it banned the use of
1607 // the "template" keyword prior to a template-name that was not a
1608 // dependent name. C++ DR468 relaxed this requirement (the
1609 // "template" keyword is now permitted). We follow the C++0x
1610 // rules, even in C++03 mode, retroactively applying the DR.
1611 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001612 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001613 EnteringContext, Template);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001614 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1615 isa<CXXRecordDecl>(LookupCtx) &&
1616 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001617 // This is a dependent template.
1618 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001619 Diag(Name.getSourceRange().getBegin(),
1620 diag::err_template_kw_refers_to_non_template)
1621 << GetNameFromUnqualifiedId(Name)
1622 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001623 return TemplateTy();
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001624 } else {
1625 // We found something; return it.
1626 return Template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001627 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001628 }
1629
Mike Stump1eb44332009-09-09 15:08:12 +00001630 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001631 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001632
1633 switch (Name.getKind()) {
1634 case UnqualifiedId::IK_Identifier:
1635 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1636 Name.Identifier));
1637
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001638 case UnqualifiedId::IK_OperatorFunctionId:
1639 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1640 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001641
1642 case UnqualifiedId::IK_LiteralOperatorId:
1643 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1644
Douglas Gregor014e88d2009-11-03 23:16:33 +00001645 default:
1646 break;
1647 }
1648
1649 Diag(Name.getSourceRange().getBegin(),
1650 diag::err_template_kw_refers_to_non_template)
1651 << GetNameFromUnqualifiedId(Name)
1652 << Name.getSourceRange();
1653 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001654}
1655
Mike Stump1eb44332009-09-09 15:08:12 +00001656bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001657 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001658 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001659 const TemplateArgument &Arg = AL.getArgument();
1660
Anders Carlsson436b1562009-06-13 00:33:33 +00001661 // Check template type parameter.
1662 if (Arg.getKind() != TemplateArgument::Type) {
1663 // C++ [temp.arg.type]p1:
1664 // A template-argument for a template-parameter which is a
1665 // type shall be a type-id.
1666
1667 // We have a template type parameter but the template argument
1668 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001669 SourceRange SR = AL.getSourceRange();
1670 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001671 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Anders Carlsson436b1562009-06-13 00:33:33 +00001673 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001674 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001675
John McCalla93c9342009-12-07 02:54:59 +00001676 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001677 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Anders Carlsson436b1562009-06-13 00:33:33 +00001679 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001680 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001681 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001682 return false;
1683}
1684
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001685/// \brief Substitute template arguments into the default template argument for
1686/// the given template type parameter.
1687///
1688/// \param SemaRef the semantic analysis object for which we are performing
1689/// the substitution.
1690///
1691/// \param Template the template that we are synthesizing template arguments
1692/// for.
1693///
1694/// \param TemplateLoc the location of the template name that started the
1695/// template-id we are checking.
1696///
1697/// \param RAngleLoc the location of the right angle bracket ('>') that
1698/// terminates the template-id.
1699///
1700/// \param Param the template template parameter whose default we are
1701/// substituting into.
1702///
1703/// \param Converted the list of template arguments provided for template
1704/// parameters that precede \p Param in the template parameter list.
1705///
1706/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001707static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001708SubstDefaultTemplateArgument(Sema &SemaRef,
1709 TemplateDecl *Template,
1710 SourceLocation TemplateLoc,
1711 SourceLocation RAngleLoc,
1712 TemplateTypeParmDecl *Param,
1713 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001714 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001715
1716 // If the argument type is dependent, instantiate it now based
1717 // on the previously-computed template arguments.
1718 if (ArgType->getType()->isDependentType()) {
1719 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1720 /*TakeArgs=*/false);
1721
1722 MultiLevelTemplateArgumentList AllTemplateArgs
1723 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1724
1725 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1726 Template, Converted.getFlatArguments(),
1727 Converted.flatSize(),
1728 SourceRange(TemplateLoc, RAngleLoc));
1729
1730 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1731 Param->getDefaultArgumentLoc(),
1732 Param->getDeclName());
1733 }
1734
1735 return ArgType;
1736}
1737
1738/// \brief Substitute template arguments into the default template argument for
1739/// the given non-type template parameter.
1740///
1741/// \param SemaRef the semantic analysis object for which we are performing
1742/// the substitution.
1743///
1744/// \param Template the template that we are synthesizing template arguments
1745/// for.
1746///
1747/// \param TemplateLoc the location of the template name that started the
1748/// template-id we are checking.
1749///
1750/// \param RAngleLoc the location of the right angle bracket ('>') that
1751/// terminates the template-id.
1752///
Douglas Gregor788cd062009-11-11 01:00:40 +00001753/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001754/// substituting into.
1755///
1756/// \param Converted the list of template arguments provided for template
1757/// parameters that precede \p Param in the template parameter list.
1758///
1759/// \returns the substituted template argument, or NULL if an error occurred.
1760static Sema::OwningExprResult
1761SubstDefaultTemplateArgument(Sema &SemaRef,
1762 TemplateDecl *Template,
1763 SourceLocation TemplateLoc,
1764 SourceLocation RAngleLoc,
1765 NonTypeTemplateParmDecl *Param,
1766 TemplateArgumentListBuilder &Converted) {
1767 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1768 /*TakeArgs=*/false);
1769
1770 MultiLevelTemplateArgumentList AllTemplateArgs
1771 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1772
1773 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1774 Template, Converted.getFlatArguments(),
1775 Converted.flatSize(),
1776 SourceRange(TemplateLoc, RAngleLoc));
1777
1778 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1779}
1780
Douglas Gregor788cd062009-11-11 01:00:40 +00001781/// \brief Substitute template arguments into the default template argument for
1782/// the given template template parameter.
1783///
1784/// \param SemaRef the semantic analysis object for which we are performing
1785/// the substitution.
1786///
1787/// \param Template the template that we are synthesizing template arguments
1788/// for.
1789///
1790/// \param TemplateLoc the location of the template name that started the
1791/// template-id we are checking.
1792///
1793/// \param RAngleLoc the location of the right angle bracket ('>') that
1794/// terminates the template-id.
1795///
1796/// \param Param the template template parameter whose default we are
1797/// substituting into.
1798///
1799/// \param Converted the list of template arguments provided for template
1800/// parameters that precede \p Param in the template parameter list.
1801///
1802/// \returns the substituted template argument, or NULL if an error occurred.
1803static TemplateName
1804SubstDefaultTemplateArgument(Sema &SemaRef,
1805 TemplateDecl *Template,
1806 SourceLocation TemplateLoc,
1807 SourceLocation RAngleLoc,
1808 TemplateTemplateParmDecl *Param,
1809 TemplateArgumentListBuilder &Converted) {
1810 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1811 /*TakeArgs=*/false);
1812
1813 MultiLevelTemplateArgumentList AllTemplateArgs
1814 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1815
1816 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1817 Template, Converted.getFlatArguments(),
1818 Converted.flatSize(),
1819 SourceRange(TemplateLoc, RAngleLoc));
1820
1821 return SemaRef.SubstTemplateName(
1822 Param->getDefaultArgument().getArgument().getAsTemplate(),
1823 Param->getDefaultArgument().getTemplateNameLoc(),
1824 AllTemplateArgs);
1825}
1826
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001827/// \brief If the given template parameter has a default template
1828/// argument, substitute into that default template argument and
1829/// return the corresponding template argument.
1830TemplateArgumentLoc
1831Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1832 SourceLocation TemplateLoc,
1833 SourceLocation RAngleLoc,
1834 Decl *Param,
1835 TemplateArgumentListBuilder &Converted) {
1836 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1837 if (!TypeParm->hasDefaultArgument())
1838 return TemplateArgumentLoc();
1839
John McCalla93c9342009-12-07 02:54:59 +00001840 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001841 TemplateLoc,
1842 RAngleLoc,
1843 TypeParm,
1844 Converted);
1845 if (DI)
1846 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1847
1848 return TemplateArgumentLoc();
1849 }
1850
1851 if (NonTypeTemplateParmDecl *NonTypeParm
1852 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1853 if (!NonTypeParm->hasDefaultArgument())
1854 return TemplateArgumentLoc();
1855
1856 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1857 TemplateLoc,
1858 RAngleLoc,
1859 NonTypeParm,
1860 Converted);
1861 if (Arg.isInvalid())
1862 return TemplateArgumentLoc();
1863
1864 Expr *ArgE = Arg.takeAs<Expr>();
1865 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1866 }
1867
1868 TemplateTemplateParmDecl *TempTempParm
1869 = cast<TemplateTemplateParmDecl>(Param);
1870 if (!TempTempParm->hasDefaultArgument())
1871 return TemplateArgumentLoc();
1872
1873 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1874 TemplateLoc,
1875 RAngleLoc,
1876 TempTempParm,
1877 Converted);
1878 if (TName.isNull())
1879 return TemplateArgumentLoc();
1880
1881 return TemplateArgumentLoc(TemplateArgument(TName),
1882 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1883 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1884}
1885
Douglas Gregore7526412009-11-11 19:31:23 +00001886/// \brief Check that the given template argument corresponds to the given
1887/// template parameter.
1888bool Sema::CheckTemplateArgument(NamedDecl *Param,
1889 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001890 TemplateDecl *Template,
1891 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001892 SourceLocation RAngleLoc,
1893 TemplateArgumentListBuilder &Converted) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001894 // Check template type parameters.
1895 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001896 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001897
Douglas Gregord9e15302009-11-11 19:41:09 +00001898 // Check non-type template parameters.
1899 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001900 // Do substitution on the type of the non-type template parameter
1901 // with the template arguments we've seen thus far.
1902 QualType NTTPType = NTTP->getType();
1903 if (NTTPType->isDependentType()) {
1904 // Do substitution on the type of the non-type template parameter.
1905 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1906 NTTP, Converted.getFlatArguments(),
1907 Converted.flatSize(),
1908 SourceRange(TemplateLoc, RAngleLoc));
1909
1910 TemplateArgumentList TemplateArgs(Context, Converted,
1911 /*TakeArgs=*/false);
1912 NTTPType = SubstType(NTTPType,
1913 MultiLevelTemplateArgumentList(TemplateArgs),
1914 NTTP->getLocation(),
1915 NTTP->getDeclName());
1916 // If that worked, check the non-type template parameter type
1917 // for validity.
1918 if (!NTTPType.isNull())
1919 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1920 NTTP->getLocation());
1921 if (NTTPType.isNull())
1922 return true;
1923 }
1924
1925 switch (Arg.getArgument().getKind()) {
1926 case TemplateArgument::Null:
1927 assert(false && "Should never see a NULL template argument here");
1928 return true;
1929
1930 case TemplateArgument::Expression: {
1931 Expr *E = Arg.getArgument().getAsExpr();
1932 TemplateArgument Result;
1933 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1934 return true;
1935
1936 Converted.Append(Result);
1937 break;
1938 }
1939
1940 case TemplateArgument::Declaration:
1941 case TemplateArgument::Integral:
1942 // We've already checked this template argument, so just copy
1943 // it to the list of converted arguments.
1944 Converted.Append(Arg.getArgument());
1945 break;
1946
1947 case TemplateArgument::Template:
1948 // We were given a template template argument. It may not be ill-formed;
1949 // see below.
1950 if (DependentTemplateName *DTN
1951 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1952 // We have a template argument such as \c T::template X, which we
1953 // parsed as a template template argument. However, since we now
1954 // know that we need a non-type template argument, convert this
1955 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00001956 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1957 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00001958 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00001959 DTN->getIdentifier(),
1960 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00001961
1962 TemplateArgument Result;
1963 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1964 return true;
1965
1966 Converted.Append(Result);
1967 break;
1968 }
1969
1970 // We have a template argument that actually does refer to a class
1971 // template, template alias, or template template parameter, and
1972 // therefore cannot be a non-type template argument.
1973 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1974 << Arg.getSourceRange();
1975
1976 Diag(Param->getLocation(), diag::note_template_param_here);
1977 return true;
1978
1979 case TemplateArgument::Type: {
1980 // We have a non-type template parameter but the template
1981 // argument is a type.
1982
1983 // C++ [temp.arg]p2:
1984 // In a template-argument, an ambiguity between a type-id and
1985 // an expression is resolved to a type-id, regardless of the
1986 // form of the corresponding template-parameter.
1987 //
1988 // We warn specifically about this case, since it can be rather
1989 // confusing for users.
1990 QualType T = Arg.getArgument().getAsType();
1991 SourceRange SR = Arg.getSourceRange();
1992 if (T->isFunctionType())
1993 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1994 else
1995 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1996 Diag(Param->getLocation(), diag::note_template_param_here);
1997 return true;
1998 }
1999
2000 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002001 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002002 break;
2003 }
2004
2005 return false;
2006 }
2007
2008
2009 // Check template template parameters.
2010 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2011
2012 // Substitute into the template parameter list of the template
2013 // template parameter, since previously-supplied template arguments
2014 // may appear within the template template parameter.
2015 {
2016 // Set up a template instantiation context.
2017 LocalInstantiationScope Scope(*this);
2018 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2019 TempParm, Converted.getFlatArguments(),
2020 Converted.flatSize(),
2021 SourceRange(TemplateLoc, RAngleLoc));
2022
2023 TemplateArgumentList TemplateArgs(Context, Converted,
2024 /*TakeArgs=*/false);
2025 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2026 SubstDecl(TempParm, CurContext,
2027 MultiLevelTemplateArgumentList(TemplateArgs)));
2028 if (!TempParm)
2029 return true;
2030
2031 // FIXME: TempParam is leaked.
2032 }
2033
2034 switch (Arg.getArgument().getKind()) {
2035 case TemplateArgument::Null:
2036 assert(false && "Should never see a NULL template argument here");
2037 return true;
2038
2039 case TemplateArgument::Template:
2040 if (CheckTemplateArgument(TempParm, Arg))
2041 return true;
2042
2043 Converted.Append(Arg.getArgument());
2044 break;
2045
2046 case TemplateArgument::Expression:
2047 case TemplateArgument::Type:
2048 // We have a template template parameter but the template
2049 // argument does not refer to a template.
2050 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2051 return true;
2052
2053 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002054 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002055 "Declaration argument with template template parameter");
2056 break;
2057 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002058 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002059 "Integral argument with template template parameter");
2060 break;
2061
2062 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002063 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002064 break;
2065 }
2066
2067 return false;
2068}
2069
Douglas Gregorc15cb382009-02-09 23:23:08 +00002070/// \brief Check that the given template argument list is well-formed
2071/// for specializing the given template.
2072bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2073 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002074 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002075 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002076 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002077 TemplateParameterList *Params = Template->getTemplateParameters();
2078 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002079 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002080 bool Invalid = false;
2081
John McCalld5532b62009-11-23 01:53:49 +00002082 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2083
Mike Stump1eb44332009-09-09 15:08:12 +00002084 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002085 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002087 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002088 (NumArgs < Params->getMinRequiredArguments() &&
2089 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002090 // FIXME: point at either the first arg beyond what we can handle,
2091 // or the '>', depending on whether we have too many or too few
2092 // arguments.
2093 SourceRange Range;
2094 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002095 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002096 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2097 << (NumArgs > NumParams)
2098 << (isa<ClassTemplateDecl>(Template)? 0 :
2099 isa<FunctionTemplateDecl>(Template)? 1 :
2100 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2101 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002102 Diag(Template->getLocation(), diag::note_template_decl_here)
2103 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002104 Invalid = true;
2105 }
Mike Stump1eb44332009-09-09 15:08:12 +00002106
2107 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002108 // [...] The type and form of each template-argument specified in
2109 // a template-id shall match the type and form specified for the
2110 // corresponding parameter declared by the template in its
2111 // template-parameter-list.
2112 unsigned ArgIdx = 0;
2113 for (TemplateParameterList::iterator Param = Params->begin(),
2114 ParamEnd = Params->end();
2115 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002116 if (ArgIdx > NumArgs && PartialTemplateArgs)
2117 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Douglas Gregord9e15302009-11-11 19:41:09 +00002119 // If we have a template parameter pack, check every remaining template
2120 // argument against that template parameter pack.
2121 if ((*Param)->isTemplateParameterPack()) {
2122 Converted.BeginPack();
2123 for (; ArgIdx < NumArgs; ++ArgIdx) {
2124 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2125 TemplateLoc, RAngleLoc, Converted)) {
2126 Invalid = true;
2127 break;
2128 }
2129 }
2130 Converted.EndPack();
2131 continue;
2132 }
2133
Douglas Gregorf35f8282009-11-11 21:54:23 +00002134 if (ArgIdx < NumArgs) {
2135 // Check the template argument we were given.
2136 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2137 TemplateLoc, RAngleLoc, Converted))
2138 return true;
2139
2140 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002141 }
Douglas Gregore7526412009-11-11 19:31:23 +00002142
Douglas Gregorf35f8282009-11-11 21:54:23 +00002143 // We have a default template argument that we will use.
2144 TemplateArgumentLoc Arg;
2145
2146 // Retrieve the default template argument from the template
2147 // parameter. For each kind of template parameter, we substitute the
2148 // template arguments provided thus far and any "outer" template arguments
2149 // (when the template parameter was part of a nested template) into
2150 // the default argument.
2151 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2152 if (!TTP->hasDefaultArgument()) {
2153 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2154 break;
2155 }
2156
John McCalla93c9342009-12-07 02:54:59 +00002157 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002158 Template,
2159 TemplateLoc,
2160 RAngleLoc,
2161 TTP,
2162 Converted);
2163 if (!ArgType)
2164 return true;
2165
2166 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2167 ArgType);
2168 } else if (NonTypeTemplateParmDecl *NTTP
2169 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2170 if (!NTTP->hasDefaultArgument()) {
2171 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2172 break;
2173 }
2174
2175 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2176 TemplateLoc,
2177 RAngleLoc,
2178 NTTP,
2179 Converted);
2180 if (E.isInvalid())
2181 return true;
2182
2183 Expr *Ex = E.takeAs<Expr>();
2184 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2185 } else {
2186 TemplateTemplateParmDecl *TempParm
2187 = cast<TemplateTemplateParmDecl>(*Param);
2188
2189 if (!TempParm->hasDefaultArgument()) {
2190 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2191 break;
2192 }
2193
2194 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2195 TemplateLoc,
2196 RAngleLoc,
2197 TempParm,
2198 Converted);
2199 if (Name.isNull())
2200 return true;
2201
2202 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2203 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2204 TempParm->getDefaultArgument().getTemplateNameLoc());
2205 }
2206
2207 // Introduce an instantiation record that describes where we are using
2208 // the default template argument.
2209 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2210 Converted.getFlatArguments(),
2211 Converted.flatSize(),
2212 SourceRange(TemplateLoc, RAngleLoc));
2213
2214 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002215 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002216 RAngleLoc, Converted))
2217 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002218 }
2219
2220 return Invalid;
2221}
2222
2223/// \brief Check a template argument against its corresponding
2224/// template type parameter.
2225///
2226/// This routine implements the semantics of C++ [temp.arg.type]. It
2227/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002228bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002229 TypeSourceInfo *ArgInfo) {
2230 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002231 QualType Arg = ArgInfo->getType();
2232
Douglas Gregorc15cb382009-02-09 23:23:08 +00002233 // C++ [temp.arg.type]p2:
2234 // A local type, a type with no linkage, an unnamed type or a type
2235 // compounded from any of these types shall not be used as a
2236 // template-argument for a template type-parameter.
2237 //
2238 // FIXME: Perform the recursive and no-linkage type checks.
2239 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002240 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002241 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002242 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002243 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002244 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2245 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2246 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2247 << QualType(Tag, 0) << SR;
2248 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002249 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002250 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2251 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002252 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2253 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002254 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2255 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2256 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002257 }
2258
2259 return false;
2260}
2261
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002262/// \brief Checks whether the given template argument is the address
2263/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002264bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2265 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002266 bool Invalid = false;
2267
2268 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002269 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002270 Arg = Cast->getSubExpr();
2271
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002272 // C++0x allows nullptr, and there's no further checking to be done for that.
2273 if (Arg->getType()->isNullPtrType())
2274 return false;
2275
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002276 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002277 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002278 // A template-argument for a non-type, non-template
2279 // template-parameter shall be one of: [...]
2280 //
2281 // -- the address of an object or function with external
2282 // linkage, including function templates and function
2283 // template-ids but excluding non-static class members,
2284 // expressed as & id-expression where the & is optional if
2285 // the name refers to a function or array, or if the
2286 // corresponding template-parameter is a reference; or
2287 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002289 // Ignore (and complain about) any excess parentheses.
2290 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2291 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002292 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002293 diag::err_template_arg_extra_parens)
2294 << Arg->getSourceRange();
2295 Invalid = true;
2296 }
2297
2298 Arg = Parens->getSubExpr();
2299 }
2300
2301 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2302 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2303 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2304 } else
2305 DRE = dyn_cast<DeclRefExpr>(Arg);
2306
2307 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002308 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002309 diag::err_template_arg_not_object_or_func_form)
2310 << Arg->getSourceRange();
2311
2312 // Cannot refer to non-static data members
2313 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2314 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2315 << Field << Arg->getSourceRange();
2316
2317 // Cannot refer to non-static member functions
2318 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2319 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002320 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002321 diag::err_template_arg_method)
2322 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002324 // Functions must have external linkage.
2325 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002326 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002327 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002328 diag::err_template_arg_function_not_extern)
2329 << Func << Arg->getSourceRange();
2330 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2331 << true;
2332 return true;
2333 }
2334
2335 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002336 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002337 return Invalid;
2338 }
2339
2340 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002341 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002342 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002343 diag::err_template_arg_object_not_extern)
2344 << Var << Arg->getSourceRange();
2345 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2346 << true;
2347 return true;
2348 }
2349
2350 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002351 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002352 return Invalid;
2353 }
Mike Stump1eb44332009-09-09 15:08:12 +00002354
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002355 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002356 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002357 diag::err_template_arg_not_object_or_func)
2358 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002359 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002360 diag::note_template_arg_refers_here);
2361 return true;
2362}
2363
2364/// \brief Checks whether the given template argument is a pointer to
2365/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002366bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2367 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002368 bool Invalid = false;
2369
2370 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002371 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002372 Arg = Cast->getSubExpr();
2373
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002374 // C++0x allows nullptr, and there's no further checking to be done for that.
2375 if (Arg->getType()->isNullPtrType())
2376 return false;
2377
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002378 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002379 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002380 // A template-argument for a non-type, non-template
2381 // template-parameter shall be one of: [...]
2382 //
2383 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002384 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002385
2386 // Ignore (and complain about) any excess parentheses.
2387 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2388 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002389 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002390 diag::err_template_arg_extra_parens)
2391 << Arg->getSourceRange();
2392 Invalid = true;
2393 }
2394
2395 Arg = Parens->getSubExpr();
2396 }
2397
Douglas Gregorcaddba02009-11-12 18:38:13 +00002398 // A pointer-to-member constant written &Class::member.
2399 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002400 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2401 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2402 if (DRE && !DRE->getQualifier())
2403 DRE = 0;
2404 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002405 }
2406 // A constant of pointer-to-member type.
2407 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2408 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2409 if (VD->getType()->isMemberPointerType()) {
2410 if (isa<NonTypeTemplateParmDecl>(VD) ||
2411 (isa<VarDecl>(VD) &&
2412 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2413 if (Arg->isTypeDependent() || Arg->isValueDependent())
2414 Converted = TemplateArgument(Arg->Retain());
2415 else
2416 Converted = TemplateArgument(VD->getCanonicalDecl());
2417 return Invalid;
2418 }
2419 }
2420 }
2421
2422 DRE = 0;
2423 }
2424
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002425 if (!DRE)
2426 return Diag(Arg->getSourceRange().getBegin(),
2427 diag::err_template_arg_not_pointer_to_member_form)
2428 << Arg->getSourceRange();
2429
2430 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2431 assert((isa<FieldDecl>(DRE->getDecl()) ||
2432 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2433 "Only non-static member pointers can make it here");
2434
2435 // Okay: this is the address of a non-static member, and therefore
2436 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002437 if (Arg->isTypeDependent() || Arg->isValueDependent())
2438 Converted = TemplateArgument(Arg->Retain());
2439 else
2440 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002441 return Invalid;
2442 }
2443
2444 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002445 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002446 diag::err_template_arg_not_pointer_to_member_form)
2447 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002448 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002449 diag::note_template_arg_refers_here);
2450 return true;
2451}
2452
Douglas Gregorc15cb382009-02-09 23:23:08 +00002453/// \brief Check a template argument against its corresponding
2454/// non-type template parameter.
2455///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002456/// This routine implements the semantics of C++ [temp.arg.nontype].
2457/// It returns true if an error occurred, and false otherwise. \p
2458/// InstantiatedParamType is the type of the non-type template
2459/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002460///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002461/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002462bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002463 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002464 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002465 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2466
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002467 // If either the parameter has a dependent type or the argument is
2468 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002469 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002470 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2471 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002472 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002473 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002474 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002475
2476 // C++ [temp.arg.nontype]p5:
2477 // The following conversions are performed on each expression used
2478 // as a non-type template-argument. If a non-type
2479 // template-argument cannot be converted to the type of the
2480 // corresponding template-parameter then the program is
2481 // ill-formed.
2482 //
2483 // -- for a non-type template-parameter of integral or
2484 // enumeration type, integral promotions (4.5) and integral
2485 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002486 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002487 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002488 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002489 // C++ [temp.arg.nontype]p1:
2490 // A template-argument for a non-type, non-template
2491 // template-parameter shall be one of:
2492 //
2493 // -- an integral constant-expression of integral or enumeration
2494 // type; or
2495 // -- the name of a non-type template-parameter; or
2496 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002497 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002498 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002499 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002500 diag::err_template_arg_not_integral_or_enumeral)
2501 << ArgType << Arg->getSourceRange();
2502 Diag(Param->getLocation(), diag::note_template_param_here);
2503 return true;
2504 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002505 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002506 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2507 << ArgType << Arg->getSourceRange();
2508 return true;
2509 }
2510
2511 // FIXME: We need some way to more easily get the unqualified form
2512 // of the types without going all the way to the
2513 // canonical type.
2514 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2515 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2516 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2517 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2518
2519 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002520 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002521 // Okay: no conversion necessary
2522 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2523 !ParamType->isEnumeralType()) {
2524 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002525 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002526 } else {
2527 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002528 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002529 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002530 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002531 Diag(Param->getLocation(), diag::note_template_param_here);
2532 return true;
2533 }
2534
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002535 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002536 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002537 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002538
2539 if (!Arg->isValueDependent()) {
2540 // Check that an unsigned parameter does not receive a negative
2541 // value.
2542 if (IntegerType->isUnsignedIntegerType()
2543 && (Value.isSigned() && Value.isNegative())) {
2544 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2545 << Value.toString(10) << Param->getType()
2546 << Arg->getSourceRange();
2547 Diag(Param->getLocation(), diag::note_template_param_here);
2548 return true;
2549 }
2550
2551 // Check that we don't overflow the template parameter type.
2552 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Eli Friedman29f89f62009-12-23 18:44:58 +00002553 unsigned RequiredBits;
2554 if (IntegerType->isUnsignedIntegerType())
2555 RequiredBits = Value.getActiveBits();
2556 else if (Value.isUnsigned())
2557 RequiredBits = Value.getActiveBits() + 1;
2558 else
2559 RequiredBits = Value.getMinSignedBits();
2560 if (RequiredBits > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002561 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002562 diag::err_template_arg_too_large)
2563 << Value.toString(10) << Param->getType()
2564 << Arg->getSourceRange();
2565 Diag(Param->getLocation(), diag::note_template_param_here);
2566 return true;
2567 }
2568
2569 if (Value.getBitWidth() != AllowedBits)
2570 Value.extOrTrunc(AllowedBits);
2571 Value.setIsSigned(IntegerType->isSignedIntegerType());
2572 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002573
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002574 // Add the value of this argument to the list of converted
2575 // arguments. We use the bitwidth and signedness of the template
2576 // parameter.
2577 if (Arg->isValueDependent()) {
2578 // The argument is value-dependent. Create a new
2579 // TemplateArgument with the converted expression.
2580 Converted = TemplateArgument(Arg);
2581 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002582 }
2583
John McCall833ca992009-10-29 08:12:44 +00002584 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002585 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002586 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002587 return false;
2588 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002589
Douglas Gregorb86b0572009-02-11 01:18:59 +00002590 // Handle pointer-to-function, reference-to-function, and
2591 // pointer-to-member-function all in (roughly) the same way.
2592 if (// -- For a non-type template-parameter of type pointer to
2593 // function, only the function-to-pointer conversion (4.3) is
2594 // applied. If the template-argument represents a set of
2595 // overloaded functions (or a pointer to such), the matching
2596 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002597 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002598 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002599 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002600 // -- For a non-type template-parameter of type reference to
2601 // function, no conversions apply. If the template-argument
2602 // represents a set of overloaded functions, the matching
2603 // function is selected from the set (13.4).
2604 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002605 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002606 // -- For a non-type template-parameter of type pointer to
2607 // member function, no conversions apply. If the
2608 // template-argument represents a set of overloaded member
2609 // functions, the matching member function is selected from
2610 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002611 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002612 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002613 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002614 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002615 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002616 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002617 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002618 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2619 ParamType->isMemberPointerType())) {
2620 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002621 if (ParamType->isMemberPointerType())
2622 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2623 else
2624 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002625 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002626 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002627 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002628 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002629 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002630 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2631 return true;
2632
Anders Carlsson96ad5332009-10-21 17:16:23 +00002633 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002634 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002635 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002636 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002637 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002638 }
2639 }
2640
Mike Stump1eb44332009-09-09 15:08:12 +00002641 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002642 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002643 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002644 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002645 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002646 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002647 Diag(Param->getLocation(), diag::note_template_param_here);
2648 return true;
2649 }
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Douglas Gregorcaddba02009-11-12 18:38:13 +00002651 if (ParamType->isMemberPointerType())
2652 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002654 NamedDecl *Entity = 0;
2655 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2656 return true;
2657
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002658 if (Entity)
2659 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002660 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002661 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002662 }
2663
Chris Lattnerfe90de72009-02-20 21:37:53 +00002664 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002665 // -- for a non-type template-parameter of type pointer to
2666 // object, qualification conversions (4.4) and the
2667 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002668 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002669 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002670 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002671
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002672 if (ArgType->isNullPtrType()) {
2673 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002674 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002675 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002676 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002677 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002678 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002679
Douglas Gregorb86b0572009-02-11 01:18:59 +00002680 if (IsQualificationConversion(ArgType, ParamType)) {
2681 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002682 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002683 }
Mike Stump1eb44332009-09-09 15:08:12 +00002684
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002685 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002686 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002687 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002688 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002689 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002690 Diag(Param->getLocation(), diag::note_template_param_here);
2691 return true;
2692 }
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002694 NamedDecl *Entity = 0;
2695 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2696 return true;
2697
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002698 if (Entity)
2699 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002700 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002701 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002702 }
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Ted Kremenek6217b802009-07-29 21:53:49 +00002704 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002705 // -- For a non-type template-parameter of type reference to
2706 // object, no conversions apply. The type referred to by the
2707 // reference may be more cv-qualified than the (otherwise
2708 // identical) type of the template-argument. The
2709 // template-parameter is bound directly to the
2710 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002711 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002712 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002713
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002714 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002715 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002716 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002717 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002718 << Arg->getSourceRange();
2719 Diag(Param->getLocation(), diag::note_template_param_here);
2720 return true;
2721 }
2722
Mike Stump1eb44332009-09-09 15:08:12 +00002723 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002724 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2725 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Douglas Gregorb86b0572009-02-11 01:18:59 +00002727 if ((ParamQuals | ArgQuals) != ParamQuals) {
2728 Diag(Arg->getSourceRange().getBegin(),
2729 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002730 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002731 << Arg->getSourceRange();
2732 Diag(Param->getLocation(), diag::note_template_param_here);
2733 return true;
2734 }
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002736 NamedDecl *Entity = 0;
2737 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2738 return true;
2739
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002740 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002741 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002742 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002743 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002744
2745 // -- For a non-type template-parameter of type pointer to data
2746 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002747 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002748 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2749
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002750 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002751 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002752 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002753 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002754 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002755 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002756 } else {
2757 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002758 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002759 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002760 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002761 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002762 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002763 }
2764
Douglas Gregorcaddba02009-11-12 18:38:13 +00002765 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002766}
2767
2768/// \brief Check a template argument against its corresponding
2769/// template template parameter.
2770///
2771/// This routine implements the semantics of C++ [temp.arg.template].
2772/// It returns true if an error occurred, and false otherwise.
2773bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002774 const TemplateArgumentLoc &Arg) {
2775 TemplateName Name = Arg.getArgument().getAsTemplate();
2776 TemplateDecl *Template = Name.getAsTemplateDecl();
2777 if (!Template) {
2778 // Any dependent template name is fine.
2779 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2780 return false;
2781 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002782
2783 // C++ [temp.arg.template]p1:
2784 // A template-argument for a template template-parameter shall be
2785 // the name of a class template, expressed as id-expression. Only
2786 // primary class templates are considered when matching the
2787 // template template argument with the corresponding parameter;
2788 // partial specializations are not considered even if their
2789 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002790 //
2791 // Note that we also allow template template parameters here, which
2792 // will happen when we are dealing with, e.g., class template
2793 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002794 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002795 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002796 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002797 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002798 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002799 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002800 << Template;
2801 }
2802
2803 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2804 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002805 true,
2806 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002807 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002808}
2809
Douglas Gregorddc29e12009-02-06 22:42:48 +00002810/// \brief Determine whether the given template parameter lists are
2811/// equivalent.
2812///
Mike Stump1eb44332009-09-09 15:08:12 +00002813/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002814/// source code as part of a new template declaration.
2815///
2816/// \param Old The old template parameter list, typically found via
2817/// name lookup of the template declared with this template parameter
2818/// list.
2819///
2820/// \param Complain If true, this routine will produce a diagnostic if
2821/// the template parameter lists are not equivalent.
2822///
Douglas Gregorfb898e12009-11-12 16:20:59 +00002823/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00002824///
2825/// \param TemplateArgLoc If this source location is valid, then we
2826/// are actually checking the template parameter list of a template
2827/// argument (New) against the template parameter list of its
2828/// corresponding template template parameter (Old). We produce
2829/// slightly different diagnostics in this scenario.
2830///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002831/// \returns True if the template parameter lists are equal, false
2832/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002833bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002834Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2835 TemplateParameterList *Old,
2836 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002837 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002838 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002839 if (Old->size() != New->size()) {
2840 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002841 unsigned NextDiag = diag::err_template_param_list_different_arity;
2842 if (TemplateArgLoc.isValid()) {
2843 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2844 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002845 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002846 Diag(New->getTemplateLoc(), NextDiag)
2847 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00002848 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002849 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002850 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002851 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002852 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2853 }
2854
2855 return false;
2856 }
2857
2858 for (TemplateParameterList::iterator OldParm = Old->begin(),
2859 OldParmEnd = Old->end(), NewParm = New->begin();
2860 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2861 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002862 if (Complain) {
2863 unsigned NextDiag = diag::err_template_param_different_kind;
2864 if (TemplateArgLoc.isValid()) {
2865 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2866 NextDiag = diag::note_template_param_different_kind;
2867 }
2868 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002869 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002870 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002871 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00002872 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002873 return false;
2874 }
2875
2876 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2877 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002878 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00002879 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002880 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2881 // The types of non-type template parameters must agree.
2882 NonTypeTemplateParmDecl *NewNTTP
2883 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00002884
2885 // If we are matching a template template argument to a template
2886 // template parameter and one of the non-type template parameter types
2887 // is dependent, then we must wait until template instantiation time
2888 // to actually compare the arguments.
2889 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2890 (OldNTTP->getType()->isDependentType() ||
2891 NewNTTP->getType()->isDependentType()))
2892 continue;
2893
Douglas Gregorddc29e12009-02-06 22:42:48 +00002894 if (Context.getCanonicalType(OldNTTP->getType()) !=
2895 Context.getCanonicalType(NewNTTP->getType())) {
2896 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002897 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2898 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002899 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002900 diag::err_template_arg_template_params_mismatch);
2901 NextDiag = diag::note_template_nontype_parm_different_type;
2902 }
2903 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002904 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00002905 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00002906 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002907 diag::note_template_nontype_parm_prev_declaration)
2908 << OldNTTP->getType();
2909 }
2910 return false;
2911 }
2912 } else {
2913 // The template parameter lists of template template
2914 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00002915 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002916 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002917 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002918 = cast<TemplateTemplateParmDecl>(*OldParm);
2919 TemplateTemplateParmDecl *NewTTP
2920 = cast<TemplateTemplateParmDecl>(*NewParm);
2921 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2922 OldTTP->getTemplateParameters(),
2923 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002924 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00002925 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002926 return false;
2927 }
2928 }
2929
2930 return true;
2931}
2932
2933/// \brief Check whether a template can be declared within this scope.
2934///
2935/// If the template declaration is valid in this scope, returns
2936/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002937bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002938Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002939 // Find the nearest enclosing declaration scope.
2940 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2941 (S->getFlags() & Scope::TemplateParamScope) != 0)
2942 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Douglas Gregorddc29e12009-02-06 22:42:48 +00002944 // C++ [temp]p2:
2945 // A template-declaration can appear only as a namespace scope or
2946 // class scope declaration.
2947 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002948 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2949 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002950 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002951 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002952
Eli Friedman1503f772009-07-31 01:43:05 +00002953 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002954 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002955
2956 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2957 return false;
2958
Mike Stump1eb44332009-09-09 15:08:12 +00002959 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002960 diag::err_template_outside_namespace_or_class_scope)
2961 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002962}
Douglas Gregorcc636682009-02-17 23:15:12 +00002963
Douglas Gregord5cb8762009-10-07 00:13:32 +00002964/// \brief Determine what kind of template specialization the given declaration
2965/// is.
2966static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2967 if (!D)
2968 return TSK_Undeclared;
2969
Douglas Gregorf6b11852009-10-08 15:14:33 +00002970 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2971 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002972 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2973 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002974 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2975 return Var->getTemplateSpecializationKind();
2976
Douglas Gregord5cb8762009-10-07 00:13:32 +00002977 return TSK_Undeclared;
2978}
2979
Douglas Gregor9302da62009-10-14 23:50:59 +00002980/// \brief Check whether a specialization is well-formed in the current
2981/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00002982///
Douglas Gregor9302da62009-10-14 23:50:59 +00002983/// This routine determines whether a template specialization can be declared
2984/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00002985///
2986/// \param S the semantic analysis object for which this check is being
2987/// performed.
2988///
2989/// \param Specialized the entity being specialized or instantiated, which
2990/// may be a kind of template (class template, function template, etc.) or
2991/// a member of a class template (member function, static data member,
2992/// member class).
2993///
2994/// \param PrevDecl the previous declaration of this entity, if any.
2995///
2996/// \param Loc the location of the explicit specialization or instantiation of
2997/// this entity.
2998///
2999/// \param IsPartialSpecialization whether this is a partial specialization of
3000/// a class template.
3001///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003002/// \returns true if there was an error that we cannot recover from, false
3003/// otherwise.
3004static bool CheckTemplateSpecializationScope(Sema &S,
3005 NamedDecl *Specialized,
3006 NamedDecl *PrevDecl,
3007 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003008 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003009 // Keep these "kind" numbers in sync with the %select statements in the
3010 // various diagnostics emitted by this routine.
3011 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003012 bool isTemplateSpecialization = false;
3013 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003014 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003015 isTemplateSpecialization = true;
3016 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003017 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003018 isTemplateSpecialization = true;
3019 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003020 EntityKind = 3;
3021 else if (isa<VarDecl>(Specialized))
3022 EntityKind = 4;
3023 else if (isa<RecordDecl>(Specialized))
3024 EntityKind = 5;
3025 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003026 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3027 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003028 return true;
3029 }
3030
Douglas Gregor88b70942009-02-25 22:02:03 +00003031 // C++ [temp.expl.spec]p2:
3032 // An explicit specialization shall be declared in the namespace
3033 // of which the template is a member, or, for member templates, in
3034 // the namespace of which the enclosing class or enclosing class
3035 // template is a member. An explicit specialization of a member
3036 // function, member class or static data member of a class
3037 // template shall be declared in the namespace of which the class
3038 // template is a member. Such a declaration may also be a
3039 // definition. If the declaration is not a definition, the
3040 // specialization may be defined later in the name- space in which
3041 // the explicit specialization was declared, or in a namespace
3042 // that encloses the one in which the explicit specialization was
3043 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003044 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3045 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003046 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003047 return true;
3048 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003049
Douglas Gregor0a407472009-10-07 17:30:37 +00003050 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3051 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003052 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003053 return true;
3054 }
3055
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003056 // C++ [temp.class.spec]p6:
3057 // A class template partial specialization may be declared or redeclared
3058 // in any namespace scope in which its definition may be defined (14.5.1
3059 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003060 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003061 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003062 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003063 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003064 if ((!PrevDecl ||
3065 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3066 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3067 // There is no prior declaration of this entity, so this
3068 // specialization must be in the same context as the template
3069 // itself.
3070 if (!DC->Equals(SpecializedContext)) {
3071 if (isa<TranslationUnitDecl>(SpecializedContext))
3072 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3073 << EntityKind << Specialized;
3074 else if (isa<NamespaceDecl>(SpecializedContext))
3075 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3076 << EntityKind << Specialized
3077 << cast<NamedDecl>(SpecializedContext);
3078
3079 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3080 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003081 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003082 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003083
3084 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003085 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003086 // Note that HandleDeclarator() performs this check for explicit
3087 // specializations of function templates, static data members, and member
3088 // functions, so we skip the check here for those kinds of entities.
3089 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003090 // Should we refactor that check, so that it occurs later?
3091 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003092 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3093 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003094 if (isa<TranslationUnitDecl>(SpecializedContext))
3095 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3096 << EntityKind << Specialized;
3097 else if (isa<NamespaceDecl>(SpecializedContext))
3098 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3099 << EntityKind << Specialized
3100 << cast<NamedDecl>(SpecializedContext);
3101
Douglas Gregor9302da62009-10-14 23:50:59 +00003102 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003103 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003104
3105 // FIXME: check for specialization-after-instantiation errors and such.
3106
Douglas Gregor88b70942009-02-25 22:02:03 +00003107 return false;
3108}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003109
Douglas Gregore94866f2009-06-12 21:21:02 +00003110/// \brief Check the non-type template arguments of a class template
3111/// partial specialization according to C++ [temp.class.spec]p9.
3112///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003113/// \param TemplateParams the template parameters of the primary class
3114/// template.
3115///
3116/// \param TemplateArg the template arguments of the class template
3117/// partial specialization.
3118///
3119/// \param MirrorsPrimaryTemplate will be set true if the class
3120/// template partial specialization arguments are identical to the
3121/// implicit template arguments of the primary template. This is not
3122/// necessarily an error (C++0x), and it is left to the caller to diagnose
3123/// this condition when it is an error.
3124///
Douglas Gregore94866f2009-06-12 21:21:02 +00003125/// \returns true if there was an error, false otherwise.
3126bool Sema::CheckClassTemplatePartialSpecializationArgs(
3127 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003128 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003129 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003130 // FIXME: the interface to this function will have to change to
3131 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003132 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003133
Anders Carlssonfb250522009-06-23 01:26:57 +00003134 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Douglas Gregore94866f2009-06-12 21:21:02 +00003136 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003137 // Determine whether the template argument list of the partial
3138 // specialization is identical to the implicit argument list of
3139 // the primary template. The caller may need to diagnostic this as
3140 // an error per C++ [temp.class.spec]p9b3.
3141 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003142 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003143 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3144 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003145 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003146 MirrorsPrimaryTemplate = false;
3147 } else if (TemplateTemplateParmDecl *TTP
3148 = dyn_cast<TemplateTemplateParmDecl>(
3149 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003150 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003151 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003152 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003153 if (!ArgDecl ||
3154 ArgDecl->getIndex() != TTP->getIndex() ||
3155 ArgDecl->getDepth() != TTP->getDepth())
3156 MirrorsPrimaryTemplate = false;
3157 }
3158 }
3159
Mike Stump1eb44332009-09-09 15:08:12 +00003160 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003161 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003162 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003163 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003164 }
3165
Anders Carlsson6360be72009-06-13 18:20:51 +00003166 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003167 if (!ArgExpr) {
3168 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003169 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003170 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003171
3172 // C++ [temp.class.spec]p8:
3173 // A non-type argument is non-specialized if it is the name of a
3174 // non-type parameter. All other non-type arguments are
3175 // specialized.
3176 //
3177 // Below, we check the two conditions that only apply to
3178 // specialized non-type arguments, so skip any non-specialized
3179 // arguments.
3180 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003181 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003182 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003183 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003184 (Param->getIndex() != NTTP->getIndex() ||
3185 Param->getDepth() != NTTP->getDepth()))
3186 MirrorsPrimaryTemplate = false;
3187
Douglas Gregore94866f2009-06-12 21:21:02 +00003188 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003189 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003190
3191 // C++ [temp.class.spec]p9:
3192 // Within the argument list of a class template partial
3193 // specialization, the following restrictions apply:
3194 // -- A partially specialized non-type argument expression
3195 // shall not involve a template parameter of the partial
3196 // specialization except when the argument expression is a
3197 // simple identifier.
3198 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003199 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003200 diag::err_dependent_non_type_arg_in_partial_spec)
3201 << ArgExpr->getSourceRange();
3202 return true;
3203 }
3204
3205 // -- The type of a template parameter corresponding to a
3206 // specialized non-type argument shall not be dependent on a
3207 // parameter of the specialization.
3208 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003209 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003210 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3211 << Param->getType()
3212 << ArgExpr->getSourceRange();
3213 Diag(Param->getLocation(), diag::note_template_param_here);
3214 return true;
3215 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003216
3217 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003218 }
3219
3220 return false;
3221}
3222
Douglas Gregor212e81c2009-03-25 00:13:59 +00003223Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003224Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3225 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003226 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00003227 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003228 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003229 SourceLocation TemplateNameLoc,
3230 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003231 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003232 SourceLocation RAngleLoc,
3233 AttributeList *Attr,
3234 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003235 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003236
Douglas Gregorcc636682009-02-17 23:15:12 +00003237 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003238 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003239 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003240 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3241
3242 if (!ClassTemplate) {
3243 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3244 << (Name.getAsTemplateDecl() &&
3245 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3246 return true;
3247 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003248
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003249 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003250 bool isPartialSpecialization = false;
3251
Douglas Gregor88b70942009-02-25 22:02:03 +00003252 // Check the validity of the template headers that introduce this
3253 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003254 // FIXME: We probably shouldn't complain about these headers for
3255 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003256 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003257 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3258 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003259 TemplateParameterLists.size(),
3260 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003261 if (TemplateParams && TemplateParams->size() > 0) {
3262 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003263
Douglas Gregor05396e22009-08-25 17:23:04 +00003264 // C++ [temp.class.spec]p10:
3265 // The template parameter list of a specialization shall not
3266 // contain default template argument values.
3267 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3268 Decl *Param = TemplateParams->getParam(I);
3269 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3270 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003271 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003272 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003273 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003274 }
3275 } else if (NonTypeTemplateParmDecl *NTTP
3276 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3277 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003278 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003279 diag::err_default_arg_in_partial_spec)
3280 << DefArg->getSourceRange();
3281 NTTP->setDefaultArgument(0);
3282 DefArg->Destroy(Context);
3283 }
3284 } else {
3285 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003286 if (TTP->hasDefaultArgument()) {
3287 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003288 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003289 << TTP->getDefaultArgument().getSourceRange();
3290 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003291 }
3292 }
3293 }
Douglas Gregora735b202009-10-13 14:39:41 +00003294 } else if (TemplateParams) {
3295 if (TUK == TUK_Friend)
3296 Diag(KWLoc, diag::err_template_spec_friend)
3297 << CodeModificationHint::CreateRemoval(
3298 SourceRange(TemplateParams->getTemplateLoc(),
3299 TemplateParams->getRAngleLoc()))
3300 << SourceRange(LAngleLoc, RAngleLoc);
3301 else
3302 isExplicitSpecialization = true;
3303 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003304 Diag(KWLoc, diag::err_template_spec_needs_header)
3305 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003306 isExplicitSpecialization = true;
3307 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003308
Douglas Gregorcc636682009-02-17 23:15:12 +00003309 // Check that the specialization uses the same tag kind as the
3310 // original template.
3311 TagDecl::TagKind Kind;
3312 switch (TagSpec) {
3313 default: assert(0 && "Unknown tag type!");
3314 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3315 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3316 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3317 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003318 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003319 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003320 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003321 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003322 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003323 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003324 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003325 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003326 diag::note_previous_use);
3327 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3328 }
3329
Douglas Gregor40808ce2009-03-09 23:48:35 +00003330 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003331 TemplateArgumentListInfo TemplateArgs;
3332 TemplateArgs.setLAngleLoc(LAngleLoc);
3333 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003334 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003335
Douglas Gregorcc636682009-02-17 23:15:12 +00003336 // Check that the template argument list is well-formed for this
3337 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003338 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3339 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003340 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3341 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003342 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003343
Mike Stump1eb44332009-09-09 15:08:12 +00003344 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003345 ClassTemplate->getTemplateParameters()->size()) &&
3346 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003347
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003348 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003349 // corresponds to these arguments.
3350 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003351 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003352 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003353 if (CheckClassTemplatePartialSpecializationArgs(
3354 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003355 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003356 return true;
3357
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003358 if (MirrorsPrimaryTemplate) {
3359 // C++ [temp.class.spec]p9b3:
3360 //
Mike Stump1eb44332009-09-09 15:08:12 +00003361 // -- The argument list of the specialization shall not be identical
3362 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003363 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003364 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003365 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003366 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003367 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003368 ClassTemplate->getIdentifier(),
3369 TemplateNameLoc,
3370 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003371 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003372 AS_none);
3373 }
3374
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003375 // FIXME: Diagnose friend partial specializations
3376
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003377 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00003378 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003379 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003380 Converted.flatSize(),
3381 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003382 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003383 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003384 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003385 Converted.flatSize(),
3386 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003387 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003388 ClassTemplateSpecializationDecl *PrevDecl = 0;
3389
3390 if (isPartialSpecialization)
3391 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003392 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003393 InsertPos);
3394 else
3395 PrevDecl
3396 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003397
3398 ClassTemplateSpecializationDecl *Specialization = 0;
3399
Douglas Gregor88b70942009-02-25 22:02:03 +00003400 // Check whether we can declare a class template specialization in
3401 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003402 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003403 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003404 TemplateNameLoc,
3405 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003406 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003407
Douglas Gregorb88e8882009-07-30 17:40:51 +00003408 // The canonical type
3409 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003410 if (PrevDecl &&
3411 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3412 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003413 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003414 // arguments was referenced but not declared, or we're only
3415 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003416 // declaration node as our own, updating its source location to
3417 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003418 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003419 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003420 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003421 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003422 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003423 // Build the canonical type that describes the converted template
3424 // arguments of the class template partial specialization.
3425 CanonType = Context.getTemplateSpecializationType(
3426 TemplateName(ClassTemplate),
3427 Converted.getFlatArguments(),
3428 Converted.flatSize());
3429
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003430 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003431 ClassTemplatePartialSpecializationDecl *PrevPartial
3432 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003433 ClassTemplatePartialSpecializationDecl *Partial
3434 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003435 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003436 TemplateNameLoc,
3437 TemplateParams,
3438 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003439 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003440 TemplateArgs,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003441 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003442
3443 if (PrevPartial) {
3444 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3445 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3446 } else {
3447 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3448 }
3449 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003450
Douglas Gregored9c0f92009-10-29 00:04:11 +00003451 // If we are providing an explicit specialization of a member class
3452 // template specialization, make a note of that.
3453 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3454 PrevPartial->setMemberSpecialization();
3455
Douglas Gregor031a5882009-06-13 00:26:55 +00003456 // Check that all of the template parameters of the class template
3457 // partial specialization are deducible from the template
3458 // arguments. If not, this class template partial specialization
3459 // will never be used.
3460 llvm::SmallVector<bool, 8> DeducibleParams;
3461 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003462 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003463 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003464 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003465 unsigned NumNonDeducible = 0;
3466 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3467 if (!DeducibleParams[I])
3468 ++NumNonDeducible;
3469
3470 if (NumNonDeducible) {
3471 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3472 << (NumNonDeducible > 1)
3473 << SourceRange(TemplateNameLoc, RAngleLoc);
3474 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3475 if (!DeducibleParams[I]) {
3476 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3477 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003478 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003479 diag::note_partial_spec_unused_parameter)
3480 << Param->getDeclName();
3481 else
Mike Stump1eb44332009-09-09 15:08:12 +00003482 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003483 diag::note_partial_spec_unused_parameter)
3484 << std::string("<anonymous>");
3485 }
3486 }
3487 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003488 } else {
3489 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003490 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003491 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003492 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003493 ClassTemplate->getDeclContext(),
3494 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003495 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003496 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003497 PrevDecl);
3498
3499 if (PrevDecl) {
3500 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3501 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3502 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003503 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003504 InsertPos);
3505 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003506
3507 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003508 }
3509
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003510 // C++ [temp.expl.spec]p6:
3511 // If a template, a member template or the member of a class template is
3512 // explicitly specialized then that specialization shall be declared
3513 // before the first use of that specialization that would cause an implicit
3514 // instantiation to take place, in every translation unit in which such a
3515 // use occurs; no diagnostic is required.
3516 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3517 SourceRange Range(TemplateNameLoc, RAngleLoc);
3518 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3519 << Context.getTypeDeclType(Specialization) << Range;
3520
3521 Diag(PrevDecl->getPointOfInstantiation(),
3522 diag::note_instantiation_required_here)
3523 << (PrevDecl->getTemplateSpecializationKind()
3524 != TSK_ImplicitInstantiation);
3525 return true;
3526 }
3527
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003528 // If this is not a friend, note that this is an explicit specialization.
3529 if (TUK != TUK_Friend)
3530 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003531
3532 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003533 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003534 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003535 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003536 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003537 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003538 Diag(Def->getLocation(), diag::note_previous_definition);
3539 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003540 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003541 }
3542 }
3543
Douglas Gregorfc705b82009-02-26 22:19:44 +00003544 // Build the fully-sugared type for this class template
3545 // specialization as the user wrote in the specialization
3546 // itself. This means that we'll pretty-print the type retrieved
3547 // from the specialization's declaration the way that the user
3548 // actually wrote the specialization, rather than formatting the
3549 // name based on the "canonical" representation used to store the
3550 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003551 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00003552 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003553 if (TUK != TUK_Friend)
3554 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003555 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003556
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003557 // C++ [temp.expl.spec]p9:
3558 // A template explicit specialization is in the scope of the
3559 // namespace in which the template was defined.
3560 //
3561 // We actually implement this paragraph where we set the semantic
3562 // context (in the creation of the ClassTemplateSpecializationDecl),
3563 // but we also maintain the lexical context where the actual
3564 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003565 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Douglas Gregorcc636682009-02-17 23:15:12 +00003567 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003568 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003569 Specialization->startDefinition();
3570
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003571 if (TUK == TUK_Friend) {
3572 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3573 TemplateNameLoc,
3574 WrittenTy.getTypePtr(),
3575 /*FIXME:*/KWLoc);
3576 Friend->setAccess(AS_public);
3577 CurContext->addDecl(Friend);
3578 } else {
3579 // Add the specialization into its lexical context, so that it can
3580 // be seen when iterating through the list of declarations in that
3581 // context. However, specializations are not found by name lookup.
3582 CurContext->addDecl(Specialization);
3583 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003584 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003585}
Douglas Gregord57959a2009-03-27 23:10:48 +00003586
Mike Stump1eb44332009-09-09 15:08:12 +00003587Sema::DeclPtrTy
3588Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003589 MultiTemplateParamsArg TemplateParameterLists,
3590 Declarator &D) {
3591 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3592}
3593
Mike Stump1eb44332009-09-09 15:08:12 +00003594Sema::DeclPtrTy
3595Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003596 MultiTemplateParamsArg TemplateParameterLists,
3597 Declarator &D) {
3598 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3599 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3600 "Not a function declarator!");
3601 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003602
Douglas Gregor52591bf2009-06-24 00:54:41 +00003603 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003604 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003605 }
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Douglas Gregor52591bf2009-06-24 00:54:41 +00003607 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003608
3609 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003610 move(TemplateParameterLists),
3611 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003612 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003613 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003614 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003615 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003616 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3617 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003618 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003619}
3620
Douglas Gregor454885e2009-10-15 15:54:05 +00003621/// \brief Diagnose cases where we have an explicit template specialization
3622/// before/after an explicit template instantiation, producing diagnostics
3623/// for those cases where they are required and determining whether the
3624/// new specialization/instantiation will have any effect.
3625///
Douglas Gregor454885e2009-10-15 15:54:05 +00003626/// \param NewLoc the location of the new explicit specialization or
3627/// instantiation.
3628///
3629/// \param NewTSK the kind of the new explicit specialization or instantiation.
3630///
3631/// \param PrevDecl the previous declaration of the entity.
3632///
3633/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3634///
3635/// \param PrevPointOfInstantiation if valid, indicates where the previus
3636/// declaration was instantiated (either implicitly or explicitly).
3637///
3638/// \param SuppressNew will be set to true to indicate that the new
3639/// specialization or instantiation has no effect and should be ignored.
3640///
3641/// \returns true if there was an error that should prevent the introduction of
3642/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003643bool
3644Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3645 TemplateSpecializationKind NewTSK,
3646 NamedDecl *PrevDecl,
3647 TemplateSpecializationKind PrevTSK,
3648 SourceLocation PrevPointOfInstantiation,
3649 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003650 SuppressNew = false;
3651
3652 switch (NewTSK) {
3653 case TSK_Undeclared:
3654 case TSK_ImplicitInstantiation:
3655 assert(false && "Don't check implicit instantiations here");
3656 return false;
3657
3658 case TSK_ExplicitSpecialization:
3659 switch (PrevTSK) {
3660 case TSK_Undeclared:
3661 case TSK_ExplicitSpecialization:
3662 // Okay, we're just specializing something that is either already
3663 // explicitly specialized or has merely been mentioned without any
3664 // instantiation.
3665 return false;
3666
3667 case TSK_ImplicitInstantiation:
3668 if (PrevPointOfInstantiation.isInvalid()) {
3669 // The declaration itself has not actually been instantiated, so it is
3670 // still okay to specialize it.
3671 return false;
3672 }
3673 // Fall through
3674
3675 case TSK_ExplicitInstantiationDeclaration:
3676 case TSK_ExplicitInstantiationDefinition:
3677 assert((PrevTSK == TSK_ImplicitInstantiation ||
3678 PrevPointOfInstantiation.isValid()) &&
3679 "Explicit instantiation without point of instantiation?");
3680
3681 // C++ [temp.expl.spec]p6:
3682 // If a template, a member template or the member of a class template
3683 // is explicitly specialized then that specialization shall be declared
3684 // before the first use of that specialization that would cause an
3685 // implicit instantiation to take place, in every translation unit in
3686 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003687 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003688 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003689 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003690 << (PrevTSK != TSK_ImplicitInstantiation);
3691
3692 return true;
3693 }
3694 break;
3695
3696 case TSK_ExplicitInstantiationDeclaration:
3697 switch (PrevTSK) {
3698 case TSK_ExplicitInstantiationDeclaration:
3699 // This explicit instantiation declaration is redundant (that's okay).
3700 SuppressNew = true;
3701 return false;
3702
3703 case TSK_Undeclared:
3704 case TSK_ImplicitInstantiation:
3705 // We're explicitly instantiating something that may have already been
3706 // implicitly instantiated; that's fine.
3707 return false;
3708
3709 case TSK_ExplicitSpecialization:
3710 // C++0x [temp.explicit]p4:
3711 // For a given set of template parameters, if an explicit instantiation
3712 // of a template appears after a declaration of an explicit
3713 // specialization for that template, the explicit instantiation has no
3714 // effect.
3715 return false;
3716
3717 case TSK_ExplicitInstantiationDefinition:
3718 // C++0x [temp.explicit]p10:
3719 // If an entity is the subject of both an explicit instantiation
3720 // declaration and an explicit instantiation definition in the same
3721 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003722 Diag(NewLoc,
3723 diag::err_explicit_instantiation_declaration_after_definition);
3724 Diag(PrevPointOfInstantiation,
3725 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003726 assert(PrevPointOfInstantiation.isValid() &&
3727 "Explicit instantiation without point of instantiation?");
3728 SuppressNew = true;
3729 return false;
3730 }
3731 break;
3732
3733 case TSK_ExplicitInstantiationDefinition:
3734 switch (PrevTSK) {
3735 case TSK_Undeclared:
3736 case TSK_ImplicitInstantiation:
3737 // We're explicitly instantiating something that may have already been
3738 // implicitly instantiated; that's fine.
3739 return false;
3740
3741 case TSK_ExplicitSpecialization:
3742 // C++ DR 259, C++0x [temp.explicit]p4:
3743 // For a given set of template parameters, if an explicit
3744 // instantiation of a template appears after a declaration of
3745 // an explicit specialization for that template, the explicit
3746 // instantiation has no effect.
3747 //
3748 // In C++98/03 mode, we only give an extension warning here, because it
3749 // is not not harmful to try to explicitly instantiate something that
3750 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003751 if (!getLangOptions().CPlusPlus0x) {
3752 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003753 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003754 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003755 diag::note_previous_template_specialization);
3756 }
3757 SuppressNew = true;
3758 return false;
3759
3760 case TSK_ExplicitInstantiationDeclaration:
3761 // We're explicity instantiating a definition for something for which we
3762 // were previously asked to suppress instantiations. That's fine.
3763 return false;
3764
3765 case TSK_ExplicitInstantiationDefinition:
3766 // C++0x [temp.spec]p5:
3767 // For a given template and a given set of template-arguments,
3768 // - an explicit instantiation definition shall appear at most once
3769 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003770 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003771 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003772 Diag(PrevPointOfInstantiation,
3773 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003774 SuppressNew = true;
3775 return false;
3776 }
3777 break;
3778 }
3779
3780 assert(false && "Missing specialization/instantiation case?");
3781
3782 return false;
3783}
3784
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003785/// \brief Perform semantic analysis for the given function template
3786/// specialization.
3787///
3788/// This routine performs all of the semantic analysis required for an
3789/// explicit function template specialization. On successful completion,
3790/// the function declaration \p FD will become a function template
3791/// specialization.
3792///
3793/// \param FD the function declaration, which will be updated to become a
3794/// function template specialization.
3795///
3796/// \param HasExplicitTemplateArgs whether any template arguments were
3797/// explicitly provided.
3798///
3799/// \param LAngleLoc the location of the left angle bracket ('<'), if
3800/// template arguments were explicitly provided.
3801///
3802/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3803/// if any.
3804///
3805/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3806/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3807/// true as in, e.g., \c void sort<>(char*, char*);
3808///
3809/// \param RAngleLoc the location of the right angle bracket ('>'), if
3810/// template arguments were explicitly provided.
3811///
3812/// \param PrevDecl the set of declarations that
3813bool
3814Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00003815 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00003816 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003817 // The set of function template specializations that could match this
3818 // explicit function template specialization.
3819 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3820 CandidateSet Candidates;
3821
3822 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00003823 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3824 I != E; ++I) {
3825 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3826 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003827 // Only consider templates found within the same semantic lookup scope as
3828 // FD.
3829 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3830 continue;
3831
3832 // C++ [temp.expl.spec]p11:
3833 // A trailing template-argument can be left unspecified in the
3834 // template-id naming an explicit function template specialization
3835 // provided it can be deduced from the function argument type.
3836 // Perform template argument deduction to determine whether we may be
3837 // specializing this template.
3838 // FIXME: It is somewhat wasteful to build
3839 TemplateDeductionInfo Info(Context);
3840 FunctionDecl *Specialization = 0;
3841 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00003842 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003843 FD->getType(),
3844 Specialization,
3845 Info)) {
3846 // FIXME: Template argument deduction failed; record why it failed, so
3847 // that we can provide nifty diagnostics.
3848 (void)TDK;
3849 continue;
3850 }
3851
3852 // Record this candidate.
3853 Candidates.push_back(Specialization);
3854 }
3855 }
3856
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003857 // Find the most specialized function template.
3858 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3859 Candidates.size(),
3860 TPOC_Other,
3861 FD->getLocation(),
3862 PartialDiagnostic(diag::err_function_template_spec_no_match)
3863 << FD->getDeclName(),
3864 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00003865 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003866 PartialDiagnostic(diag::note_function_template_spec_matched));
3867 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003868 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003869
3870 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003871 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003872
Douglas Gregord5cb8762009-10-07 00:13:32 +00003873 // Check the scope of this explicit specialization.
3874 if (CheckTemplateSpecializationScope(*this,
3875 Specialization->getPrimaryTemplate(),
3876 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003877 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003878 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003879
3880 // C++ [temp.expl.spec]p6:
3881 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003882 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003883 // before the first use of that specialization that would cause an implicit
3884 // instantiation to take place, in every translation unit in which such a
3885 // use occurs; no diagnostic is required.
3886 FunctionTemplateSpecializationInfo *SpecInfo
3887 = Specialization->getTemplateSpecializationInfo();
3888 assert(SpecInfo && "Function template specialization info missing?");
3889 if (SpecInfo->getPointOfInstantiation().isValid()) {
3890 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3891 << FD;
3892 Diag(SpecInfo->getPointOfInstantiation(),
3893 diag::note_instantiation_required_here)
3894 << (Specialization->getTemplateSpecializationKind()
3895 != TSK_ImplicitInstantiation);
3896 return true;
3897 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003898
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003899 // Mark the prior declaration as an explicit specialization, so that later
3900 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003901 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003902
3903 // Turn the given function declaration into a function template
3904 // specialization, with the template arguments from the previous
3905 // specialization.
3906 FD->setFunctionTemplateSpecialization(Context,
3907 Specialization->getPrimaryTemplate(),
3908 new (Context) TemplateArgumentList(
3909 *Specialization->getTemplateSpecializationArgs()),
3910 /*InsertPos=*/0,
3911 TSK_ExplicitSpecialization);
3912
3913 // The "previous declaration" for this function template specialization is
3914 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00003915 Previous.clear();
3916 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003917 return false;
3918}
3919
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003920/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003921/// specialization.
3922///
3923/// This routine performs all of the semantic analysis required for an
3924/// explicit member function specialization. On successful completion,
3925/// the function declaration \p FD will become a member function
3926/// specialization.
3927///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003928/// \param Member the member declaration, which will be updated to become a
3929/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003930///
John McCall68263142009-11-18 22:49:29 +00003931/// \param Previous the set of declarations, one of which may be specialized
3932/// by this function specialization; the set will be modified to contain the
3933/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003934bool
John McCall68263142009-11-18 22:49:29 +00003935Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003936 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3937
3938 // Try to find the member we are instantiating.
3939 NamedDecl *Instantiation = 0;
3940 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003941 MemberSpecializationInfo *MSInfo = 0;
3942
John McCall68263142009-11-18 22:49:29 +00003943 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003944 // Nowhere to look anyway.
3945 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003946 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3947 I != E; ++I) {
3948 NamedDecl *D = (*I)->getUnderlyingDecl();
3949 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003950 if (Context.hasSameType(Function->getType(), Method->getType())) {
3951 Instantiation = Method;
3952 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003953 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003954 break;
3955 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003956 }
3957 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003958 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003959 VarDecl *PrevVar;
3960 if (Previous.isSingleResult() &&
3961 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003962 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00003963 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003964 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003965 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003966 }
3967 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003968 CXXRecordDecl *PrevRecord;
3969 if (Previous.isSingleResult() &&
3970 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3971 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003972 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003973 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003974 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003975 }
3976
3977 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003978 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003979 // specializations are always out-of-line, the caller will complain about
3980 // this mismatch later.
3981 return false;
3982 }
3983
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003984 // Make sure that this is a specialization of a member.
3985 if (!InstantiatedFrom) {
3986 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3987 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003988 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3989 return true;
3990 }
3991
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003992 // C++ [temp.expl.spec]p6:
3993 // If a template, a member template or the member of a class template is
3994 // explicitly specialized then that spe- cialization shall be declared
3995 // before the first use of that specialization that would cause an implicit
3996 // instantiation to take place, in every translation unit in which such a
3997 // use occurs; no diagnostic is required.
3998 assert(MSInfo && "Member specialization info missing?");
3999 if (MSInfo->getPointOfInstantiation().isValid()) {
4000 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
4001 << Member;
4002 Diag(MSInfo->getPointOfInstantiation(),
4003 diag::note_instantiation_required_here)
4004 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
4005 return true;
4006 }
4007
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004008 // Check the scope of this explicit specialization.
4009 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004010 InstantiatedFrom,
4011 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004012 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004013 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004014
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004015 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004016 // the original declaration to note that it is an explicit specialization
4017 // (if it was previously an implicit instantiation). This latter step
4018 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004019 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004020 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4021 if (InstantiationFunction->getTemplateSpecializationKind() ==
4022 TSK_ImplicitInstantiation) {
4023 InstantiationFunction->setTemplateSpecializationKind(
4024 TSK_ExplicitSpecialization);
4025 InstantiationFunction->setLocation(Member->getLocation());
4026 }
4027
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004028 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4029 cast<CXXMethodDecl>(InstantiatedFrom),
4030 TSK_ExplicitSpecialization);
4031 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004032 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4033 if (InstantiationVar->getTemplateSpecializationKind() ==
4034 TSK_ImplicitInstantiation) {
4035 InstantiationVar->setTemplateSpecializationKind(
4036 TSK_ExplicitSpecialization);
4037 InstantiationVar->setLocation(Member->getLocation());
4038 }
4039
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004040 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4041 cast<VarDecl>(InstantiatedFrom),
4042 TSK_ExplicitSpecialization);
4043 } else {
4044 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004045 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4046 if (InstantiationClass->getTemplateSpecializationKind() ==
4047 TSK_ImplicitInstantiation) {
4048 InstantiationClass->setTemplateSpecializationKind(
4049 TSK_ExplicitSpecialization);
4050 InstantiationClass->setLocation(Member->getLocation());
4051 }
4052
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004053 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004054 cast<CXXRecordDecl>(InstantiatedFrom),
4055 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004056 }
4057
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004058 // Save the caller the trouble of having to figure out which declaration
4059 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004060 Previous.clear();
4061 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004062 return false;
4063}
4064
Douglas Gregor558c0322009-10-14 23:41:34 +00004065/// \brief Check the scope of an explicit instantiation.
4066static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4067 SourceLocation InstLoc,
4068 bool WasQualifiedName) {
4069 DeclContext *ExpectedContext
4070 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4071 DeclContext *CurContext = S.CurContext->getLookupContext();
4072
4073 // C++0x [temp.explicit]p2:
4074 // An explicit instantiation shall appear in an enclosing namespace of its
4075 // template.
4076 //
4077 // This is DR275, which we do not retroactively apply to C++98/03.
4078 if (S.getLangOptions().CPlusPlus0x &&
4079 !CurContext->Encloses(ExpectedContext)) {
4080 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4081 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4082 << D << NS;
4083 else
4084 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4085 << D;
4086 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4087 return;
4088 }
4089
4090 // C++0x [temp.explicit]p2:
4091 // If the name declared in the explicit instantiation is an unqualified
4092 // name, the explicit instantiation shall appear in the namespace where
4093 // its template is declared or, if that namespace is inline (7.3.1), any
4094 // namespace from its enclosing namespace set.
4095 if (WasQualifiedName)
4096 return;
4097
4098 if (CurContext->Equals(ExpectedContext))
4099 return;
4100
4101 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4102 << D << ExpectedContext;
4103 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4104}
4105
4106/// \brief Determine whether the given scope specifier has a template-id in it.
4107static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4108 if (!SS.isSet())
4109 return false;
4110
4111 // C++0x [temp.explicit]p2:
4112 // If the explicit instantiation is for a member function, a member class
4113 // or a static data member of a class template specialization, the name of
4114 // the class template specialization in the qualified-id for the member
4115 // name shall be a simple-template-id.
4116 //
4117 // C++98 has the same restriction, just worded differently.
4118 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4119 NNS; NNS = NNS->getPrefix())
4120 if (Type *T = NNS->getAsType())
4121 if (isa<TemplateSpecializationType>(T))
4122 return true;
4123
4124 return false;
4125}
4126
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004127// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00004128// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004129Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004130Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004131 SourceLocation ExternLoc,
4132 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004133 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004134 SourceLocation KWLoc,
4135 const CXXScopeSpec &SS,
4136 TemplateTy TemplateD,
4137 SourceLocation TemplateNameLoc,
4138 SourceLocation LAngleLoc,
4139 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004140 SourceLocation RAngleLoc,
4141 AttributeList *Attr) {
4142 // Find the class template we're specializing
4143 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004144 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004145 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4146
4147 // Check that the specialization uses the same tag kind as the
4148 // original template.
4149 TagDecl::TagKind Kind;
4150 switch (TagSpec) {
4151 default: assert(0 && "Unknown tag type!");
4152 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4153 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4154 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4155 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004156 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004157 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004158 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004159 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004160 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00004161 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004162 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004163 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004164 diag::note_previous_use);
4165 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4166 }
4167
Douglas Gregor558c0322009-10-14 23:41:34 +00004168 // C++0x [temp.explicit]p2:
4169 // There are two forms of explicit instantiation: an explicit instantiation
4170 // definition and an explicit instantiation declaration. An explicit
4171 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004172 TemplateSpecializationKind TSK
4173 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4174 : TSK_ExplicitInstantiationDeclaration;
4175
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004176 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004177 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004178 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004179
4180 // Check that the template argument list is well-formed for this
4181 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004182 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4183 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004184 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4185 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004186 return true;
4187
Mike Stump1eb44332009-09-09 15:08:12 +00004188 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004189 ClassTemplate->getTemplateParameters()->size()) &&
4190 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004191
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004192 // Find the class template specialization declaration that
4193 // corresponds to these arguments.
4194 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004195 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004196 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004197 Converted.flatSize(),
4198 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004199 void *InsertPos = 0;
4200 ClassTemplateSpecializationDecl *PrevDecl
4201 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4202
Douglas Gregord5cb8762009-10-07 00:13:32 +00004203 // C++0x [temp.explicit]p2:
4204 // [...] An explicit instantiation shall appear in an enclosing
4205 // namespace of its template. [...]
4206 //
4207 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004208 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4209 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004210
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004211 ClassTemplateSpecializationDecl *Specialization = 0;
4212
Douglas Gregord78f5982009-11-25 06:01:46 +00004213 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004214 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004215 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004216 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004217 PrevDecl,
4218 PrevDecl->getSpecializationKind(),
4219 PrevDecl->getPointOfInstantiation(),
4220 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004221 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004222
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004223 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004224 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004225
Douglas Gregor52604ab2009-09-11 21:19:12 +00004226 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4227 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4228 // Since the only prior class template specialization with these
4229 // arguments was referenced but not declared, reuse that
4230 // declaration node as our own, updating its source location to
4231 // reflect our new declaration.
4232 Specialization = PrevDecl;
4233 Specialization->setLocation(TemplateNameLoc);
4234 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004235 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004236 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004237 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004238
4239 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004240 // Create a new class template specialization declaration node for
4241 // this explicit specialization.
4242 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00004243 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004244 ClassTemplate->getDeclContext(),
4245 TemplateNameLoc,
4246 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004247 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004248
Douglas Gregor52604ab2009-09-11 21:19:12 +00004249 if (PrevDecl) {
4250 // Remove the previous declaration from the folding set, since we want
4251 // to introduce a new declaration.
4252 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4253 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4254 }
4255
4256 // Insert the new specialization.
4257 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004258 }
4259
4260 // Build the fully-sugared type for this explicit instantiation as
4261 // the user wrote in the explicit instantiation itself. This means
4262 // that we'll pretty-print the type retrieved from the
4263 // specialization's declaration the way that the user actually wrote
4264 // the explicit instantiation, rather than formatting the name based
4265 // on the "canonical" representation used to store the template
4266 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004267 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00004268 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004269 Context.getTypeDeclType(Specialization));
4270 Specialization->setTypeAsWritten(WrittenTy);
4271 TemplateArgsIn.release();
4272
Douglas Gregord78f5982009-11-25 06:01:46 +00004273 if (!ReusedDecl) {
4274 // Add the explicit instantiation into its lexical context. However,
4275 // since explicit instantiations are never found by name lookup, we
4276 // just put it into the declaration context directly.
4277 Specialization->setLexicalDeclContext(CurContext);
4278 CurContext->addDecl(Specialization);
4279 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004280
4281 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004282 // A definition of a class template or class member template
4283 // shall be in scope at the point of the explicit instantiation of
4284 // the class template or class member template.
4285 //
4286 // This check comes when we actually try to perform the
4287 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004288 ClassTemplateSpecializationDecl *Def
4289 = cast_or_null<ClassTemplateSpecializationDecl>(
4290 Specialization->getDefinition(Context));
4291 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004292 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004293
4294 // Instantiate the members of this class template specialization.
4295 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4296 Specialization->getDefinition(Context));
4297 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004298 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004299
4300 return DeclPtrTy::make(Specialization);
4301}
4302
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004303// Explicit instantiation of a member class of a class template.
4304Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004305Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004306 SourceLocation ExternLoc,
4307 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004308 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004309 SourceLocation KWLoc,
4310 const CXXScopeSpec &SS,
4311 IdentifierInfo *Name,
4312 SourceLocation NameLoc,
4313 AttributeList *Attr) {
4314
Douglas Gregor402abb52009-05-28 23:31:59 +00004315 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004316 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004317 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004318 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004319 MultiTemplateParamsArg(*this, 0, 0),
4320 Owned, IsDependent);
4321 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4322
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004323 if (!TagD)
4324 return true;
4325
4326 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4327 if (Tag->isEnum()) {
4328 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4329 << Context.getTypeDeclType(Tag);
4330 return true;
4331 }
4332
Douglas Gregord0c87372009-05-27 17:30:49 +00004333 if (Tag->isInvalidDecl())
4334 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004335
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004336 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4337 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4338 if (!Pattern) {
4339 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4340 << Context.getTypeDeclType(Record);
4341 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4342 return true;
4343 }
4344
Douglas Gregor558c0322009-10-14 23:41:34 +00004345 // C++0x [temp.explicit]p2:
4346 // If the explicit instantiation is for a class or member class, the
4347 // elaborated-type-specifier in the declaration shall include a
4348 // simple-template-id.
4349 //
4350 // C++98 has the same restriction, just worded differently.
4351 if (!ScopeSpecifierHasTemplateId(SS))
4352 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4353 << Record << SS.getRange();
4354
4355 // C++0x [temp.explicit]p2:
4356 // There are two forms of explicit instantiation: an explicit instantiation
4357 // definition and an explicit instantiation declaration. An explicit
4358 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004359 TemplateSpecializationKind TSK
4360 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4361 : TSK_ExplicitInstantiationDeclaration;
4362
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004363 // C++0x [temp.explicit]p2:
4364 // [...] An explicit instantiation shall appear in an enclosing
4365 // namespace of its template. [...]
4366 //
4367 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004368 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004369
4370 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004371 CXXRecordDecl *PrevDecl
4372 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4373 if (!PrevDecl && Record->getDefinition(Context))
4374 PrevDecl = Record;
4375 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004376 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4377 bool SuppressNew = false;
4378 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004379 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004380 PrevDecl,
4381 MSInfo->getTemplateSpecializationKind(),
4382 MSInfo->getPointOfInstantiation(),
4383 SuppressNew))
4384 return true;
4385 if (SuppressNew)
4386 return TagD;
4387 }
4388
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004389 CXXRecordDecl *RecordDef
4390 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4391 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004392 // C++ [temp.explicit]p3:
4393 // A definition of a member class of a class template shall be in scope
4394 // at the point of an explicit instantiation of the member class.
4395 CXXRecordDecl *Def
4396 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4397 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004398 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4399 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004400 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4401 << Pattern;
4402 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004403 } else {
4404 if (InstantiateClass(NameLoc, Record, Def,
4405 getTemplateInstantiationArgs(Record),
4406 TSK))
4407 return true;
4408
4409 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4410 if (!RecordDef)
4411 return true;
4412 }
4413 }
4414
4415 // Instantiate all of the members of the class.
4416 InstantiateClassMembers(NameLoc, RecordDef,
4417 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004418
Mike Stump390b4cc2009-05-16 07:39:55 +00004419 // FIXME: We don't have any representation for explicit instantiations of
4420 // member classes. Such a representation is not needed for compilation, but it
4421 // should be available for clients that want to see all of the declarations in
4422 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004423 return TagD;
4424}
4425
Douglas Gregord5a423b2009-09-25 18:43:00 +00004426Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4427 SourceLocation ExternLoc,
4428 SourceLocation TemplateLoc,
4429 Declarator &D) {
4430 // Explicit instantiations always require a name.
4431 DeclarationName Name = GetNameForDeclarator(D);
4432 if (!Name) {
4433 if (!D.isInvalidType())
4434 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4435 diag::err_explicit_instantiation_requires_name)
4436 << D.getDeclSpec().getSourceRange()
4437 << D.getSourceRange();
4438
4439 return true;
4440 }
4441
4442 // The scope passed in may not be a decl scope. Zip up the scope tree until
4443 // we find one that is.
4444 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4445 (S->getFlags() & Scope::TemplateParamScope) != 0)
4446 S = S->getParent();
4447
4448 // Determine the type of the declaration.
4449 QualType R = GetTypeForDeclarator(D, S, 0);
4450 if (R.isNull())
4451 return true;
4452
4453 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4454 // Cannot explicitly instantiate a typedef.
4455 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4456 << Name;
4457 return true;
4458 }
4459
Douglas Gregor663b5a02009-10-14 20:14:33 +00004460 // C++0x [temp.explicit]p1:
4461 // [...] An explicit instantiation of a function template shall not use the
4462 // inline or constexpr specifiers.
4463 // Presumably, this also applies to member functions of class templates as
4464 // well.
4465 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4466 Diag(D.getDeclSpec().getInlineSpecLoc(),
4467 diag::err_explicit_instantiation_inline)
Chris Lattner29d9c1a2009-12-06 17:36:05 +00004468 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004469
4470 // FIXME: check for constexpr specifier.
4471
Douglas Gregor558c0322009-10-14 23:41:34 +00004472 // C++0x [temp.explicit]p2:
4473 // There are two forms of explicit instantiation: an explicit instantiation
4474 // definition and an explicit instantiation declaration. An explicit
4475 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004476 TemplateSpecializationKind TSK
4477 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4478 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004479
John McCalla24dc2e2009-11-17 02:14:36 +00004480 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4481 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004482
4483 if (!R->isFunctionType()) {
4484 // C++ [temp.explicit]p1:
4485 // A [...] static data member of a class template can be explicitly
4486 // instantiated from the member definition associated with its class
4487 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004488 if (Previous.isAmbiguous())
4489 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004490
John McCall1bcee0a2009-12-02 08:25:40 +00004491 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004492 if (!Prev || !Prev->isStaticDataMember()) {
4493 // We expect to see a data data member here.
4494 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4495 << Name;
4496 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4497 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004498 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004499 return true;
4500 }
4501
4502 if (!Prev->getInstantiatedFromStaticDataMember()) {
4503 // FIXME: Check for explicit specialization?
4504 Diag(D.getIdentifierLoc(),
4505 diag::err_explicit_instantiation_data_member_not_instantiated)
4506 << Prev;
4507 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4508 // FIXME: Can we provide a note showing where this was declared?
4509 return true;
4510 }
4511
Douglas Gregor558c0322009-10-14 23:41:34 +00004512 // C++0x [temp.explicit]p2:
4513 // If the explicit instantiation is for a member function, a member class
4514 // or a static data member of a class template specialization, the name of
4515 // the class template specialization in the qualified-id for the member
4516 // name shall be a simple-template-id.
4517 //
4518 // C++98 has the same restriction, just worded differently.
4519 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4520 Diag(D.getIdentifierLoc(),
4521 diag::err_explicit_instantiation_without_qualified_id)
4522 << Prev << D.getCXXScopeSpec().getRange();
4523
4524 // Check the scope of this explicit instantiation.
4525 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4526
Douglas Gregor454885e2009-10-15 15:54:05 +00004527 // Verify that it is okay to explicitly instantiate here.
4528 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4529 assert(MSInfo && "Missing static data member specialization info?");
4530 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004531 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004532 MSInfo->getTemplateSpecializationKind(),
4533 MSInfo->getPointOfInstantiation(),
4534 SuppressNew))
4535 return true;
4536 if (SuppressNew)
4537 return DeclPtrTy();
4538
Douglas Gregord5a423b2009-09-25 18:43:00 +00004539 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004540 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004541 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004542 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4543 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004544
4545 // FIXME: Create an ExplicitInstantiation node?
4546 return DeclPtrTy();
4547 }
4548
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004549 // If the declarator is a template-id, translate the parser's template
4550 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004551 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004552 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004553 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4554 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00004555 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4556 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00004557 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4558 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004559 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00004560 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00004561 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004562 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004563 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004564
Douglas Gregord5a423b2009-09-25 18:43:00 +00004565 // C++ [temp.explicit]p1:
4566 // A [...] function [...] can be explicitly instantiated from its template.
4567 // A member function [...] of a class template can be explicitly
4568 // instantiated from the member definition associated with its class
4569 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004570 llvm::SmallVector<FunctionDecl *, 8> Matches;
4571 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4572 P != PEnd; ++P) {
4573 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004574 if (!HasExplicitTemplateArgs) {
4575 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4576 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4577 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00004578
Douglas Gregordb422df2009-09-25 21:45:23 +00004579 Matches.push_back(Method);
Douglas Gregor48026d22010-01-11 18:40:55 +00004580 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4581 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00004582 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004583 }
4584 }
4585
4586 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4587 if (!FunTmpl)
4588 continue;
4589
4590 TemplateDeductionInfo Info(Context);
4591 FunctionDecl *Specialization = 0;
4592 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00004593 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00004594 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004595 R, Specialization, Info)) {
4596 // FIXME: Keep track of almost-matches?
4597 (void)TDK;
4598 continue;
4599 }
4600
4601 Matches.push_back(Specialization);
4602 }
4603
4604 // Find the most specialized function template specialization.
4605 FunctionDecl *Specialization
4606 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4607 D.getIdentifierLoc(),
4608 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4609 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4610 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4611
4612 if (!Specialization)
4613 return true;
4614
Douglas Gregor0a897e32009-10-15 17:21:20 +00004615 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004616 Diag(D.getIdentifierLoc(),
4617 diag::err_explicit_instantiation_member_function_not_instantiated)
4618 << Specialization
4619 << (Specialization->getTemplateSpecializationKind() ==
4620 TSK_ExplicitSpecialization);
4621 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4622 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004623 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004624
Douglas Gregor0a897e32009-10-15 17:21:20 +00004625 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004626 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4627 PrevDecl = Specialization;
4628
Douglas Gregor0a897e32009-10-15 17:21:20 +00004629 if (PrevDecl) {
4630 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004631 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004632 PrevDecl,
4633 PrevDecl->getTemplateSpecializationKind(),
4634 PrevDecl->getPointOfInstantiation(),
4635 SuppressNew))
4636 return true;
4637
4638 // FIXME: We may still want to build some representation of this
4639 // explicit specialization.
4640 if (SuppressNew)
4641 return DeclPtrTy();
4642 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00004643
4644 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00004645
4646 if (TSK == TSK_ExplicitInstantiationDefinition)
4647 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4648 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00004649
Douglas Gregor558c0322009-10-14 23:41:34 +00004650 // C++0x [temp.explicit]p2:
4651 // If the explicit instantiation is for a member function, a member class
4652 // or a static data member of a class template specialization, the name of
4653 // the class template specialization in the qualified-id for the member
4654 // name shall be a simple-template-id.
4655 //
4656 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004657 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004658 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004659 D.getCXXScopeSpec().isSet() &&
4660 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4661 Diag(D.getIdentifierLoc(),
4662 diag::err_explicit_instantiation_without_qualified_id)
4663 << Specialization << D.getCXXScopeSpec().getRange();
4664
4665 CheckExplicitInstantiationScope(*this,
4666 FunTmpl? (NamedDecl *)FunTmpl
4667 : Specialization->getInstantiatedFromMemberFunction(),
4668 D.getIdentifierLoc(),
4669 D.getCXXScopeSpec().isSet());
4670
Douglas Gregord5a423b2009-09-25 18:43:00 +00004671 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4672 return DeclPtrTy();
4673}
4674
Douglas Gregord57959a2009-03-27 23:10:48 +00004675Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004676Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4677 const CXXScopeSpec &SS, IdentifierInfo *Name,
4678 SourceLocation TagLoc, SourceLocation NameLoc) {
4679 // This has to hold, because SS is expected to be defined.
4680 assert(Name && "Expected a name in a dependent tag");
4681
4682 NestedNameSpecifier *NNS
4683 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4684 if (!NNS)
4685 return true;
4686
4687 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4688 if (T.isNull())
4689 return true;
4690
4691 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4692 QualType ElabType = Context.getElaboratedType(T, TagKind);
4693
4694 return ElabType.getAsOpaquePtr();
4695}
4696
4697Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004698Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4699 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004700 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004701 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4702 if (!NNS)
4703 return true;
4704
4705 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004706 if (T.isNull())
4707 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004708 return T.getAsOpaquePtr();
4709}
4710
Douglas Gregor17343172009-04-01 00:28:59 +00004711Sema::TypeResult
4712Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4713 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004714 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004715 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004716 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004717 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004718 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004719 assert(TemplateId && "Expected a template specialization type");
4720
Douglas Gregor6946baf2009-09-02 13:05:45 +00004721 if (computeDeclContext(SS, false)) {
4722 // If we can compute a declaration context, then the "typename"
4723 // keyword was superfluous. Just build a QualifiedNameType to keep
4724 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004725
Douglas Gregor6946baf2009-09-02 13:05:45 +00004726 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4727 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4728 }
Mike Stump1eb44332009-09-09 15:08:12 +00004729
Douglas Gregor6946baf2009-09-02 13:05:45 +00004730 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004731}
4732
Douglas Gregord57959a2009-03-27 23:10:48 +00004733/// \brief Build the type that describes a C++ typename specifier,
4734/// e.g., "typename T::type".
4735QualType
4736Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4737 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004738 CXXRecordDecl *CurrentInstantiation = 0;
4739 if (NNS->isDependent()) {
4740 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004741
Douglas Gregor42af25f2009-05-11 19:58:34 +00004742 // If the nested-name-specifier does not refer to the current
4743 // instantiation, then build a typename type.
4744 if (!CurrentInstantiation)
4745 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004746
Douglas Gregorde18d122009-09-02 13:12:51 +00004747 // The nested-name-specifier refers to the current instantiation, so the
4748 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004749 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004750 // extraneous "typename" keywords, and we retroactively apply this DR to
4751 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004752 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004753
Douglas Gregor42af25f2009-05-11 19:58:34 +00004754 DeclContext *Ctx = 0;
4755
4756 if (CurrentInstantiation)
4757 Ctx = CurrentInstantiation;
4758 else {
4759 CXXScopeSpec SS;
4760 SS.setScopeRep(NNS);
4761 SS.setRange(Range);
4762 if (RequireCompleteDeclContext(SS))
4763 return QualType();
4764
4765 Ctx = computeDeclContext(SS);
4766 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004767 assert(Ctx && "No declaration context?");
4768
4769 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00004770 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4771 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00004772 unsigned DiagID = 0;
4773 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004774 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004775 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004776 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004777 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00004778
4779 case LookupResult::NotFoundInCurrentInstantiation:
4780 // Okay, it's a member of an unknown instantiation.
4781 return Context.getTypenameType(NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00004782
4783 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004784 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004785 // We found a type. Build a QualifiedNameType, since the
4786 // typename-specifier was just sugar. FIXME: Tell
4787 // QualifiedNameType that it has a "typename" prefix.
4788 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4789 }
4790
4791 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004792 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004793 break;
4794
John McCall7ba107a2009-11-18 02:36:19 +00004795 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004796 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00004797 return QualType();
4798
Douglas Gregord57959a2009-03-27 23:10:48 +00004799 case LookupResult::FoundOverloaded:
4800 DiagID = diag::err_typename_nested_not_type;
4801 Referenced = *Result.begin();
4802 break;
4803
John McCall6e247262009-10-10 05:48:19 +00004804 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004805 return QualType();
4806 }
4807
4808 // If we get here, it's because name lookup did not find a
4809 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004810 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004811 if (Referenced)
4812 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4813 << Name;
4814 return QualType();
4815}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004816
4817namespace {
4818 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00004819 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00004820 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004821 SourceLocation Loc;
4822 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004823
Douglas Gregor4a959d82009-08-06 16:20:37 +00004824 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004825 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004826 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004827 DeclarationName Entity)
4828 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004829 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004830
4831 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004832 /// transformed.
4833 ///
4834 /// For the purposes of type reconstruction, a type has already been
4835 /// transformed if it is NULL or if it is not dependent.
4836 bool AlreadyTransformed(QualType T) {
4837 return T.isNull() || !T->isDependentType();
4838 }
Mike Stump1eb44332009-09-09 15:08:12 +00004839
4840 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004841 /// rebuilt.
4842 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Douglas Gregor4a959d82009-08-06 16:20:37 +00004844 /// \brief Returns the name of the entity whose type is being rebuilt.
4845 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004847 /// \brief Sets the "base" location and entity when that
4848 /// information is known based on another transformation.
4849 void setBase(SourceLocation Loc, DeclarationName Entity) {
4850 this->Loc = Loc;
4851 this->Entity = Entity;
4852 }
4853
Douglas Gregor4a959d82009-08-06 16:20:37 +00004854 /// \brief Transforms an expression by returning the expression itself
4855 /// (an identity function).
4856 ///
4857 /// FIXME: This is completely unsafe; we will need to actually clone the
4858 /// expressions.
4859 Sema::OwningExprResult TransformExpr(Expr *E) {
4860 return getSema().Owned(E);
4861 }
Mike Stump1eb44332009-09-09 15:08:12 +00004862
Douglas Gregor4a959d82009-08-06 16:20:37 +00004863 /// \brief Transforms a typename type by determining whether the type now
4864 /// refers to a member of the current instantiation, and then
4865 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004866 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004867 };
4868}
4869
Mike Stump1eb44332009-09-09 15:08:12 +00004870QualType
John McCalla2becad2009-10-21 00:40:46 +00004871CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4872 TypenameTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00004873 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004874
Douglas Gregor4a959d82009-08-06 16:20:37 +00004875 NestedNameSpecifier *NNS
4876 = TransformNestedNameSpecifier(T->getQualifier(),
4877 /*FIXME:*/SourceRange(getBaseLocation()));
4878 if (!NNS)
4879 return QualType();
4880
4881 // If the nested-name-specifier did not change, and we cannot compute the
4882 // context corresponding to the nested-name-specifier, then this
4883 // typename type will not change; exit early.
4884 CXXScopeSpec SS;
4885 SS.setRange(SourceRange(getBaseLocation()));
4886 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004887
4888 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004889 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004890 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004891
4892 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004893 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004894 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004895 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004896 = TransformType(QualType(TemplateId, 0));
4897 if (NewTemplateId.isNull())
4898 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004899
Douglas Gregor4a959d82009-08-06 16:20:37 +00004900 if (NNS == T->getQualifier() &&
4901 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004902 Result = QualType(T, 0);
4903 else
4904 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4905 } else
4906 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4907 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004908
John McCall833ca992009-10-29 08:12:44 +00004909 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4910 NewTL.setNameLoc(TL.getNameLoc());
4911 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004912}
4913
4914/// \brief Rebuilds a type within the context of the current instantiation.
4915///
Mike Stump1eb44332009-09-09 15:08:12 +00004916/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004917/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004918/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004919/// partial specialization thereof). This routine will rebuild that type now
4920/// that we have entered the declarator's scope, which may produce different
4921/// canonical types, e.g.,
4922///
4923/// \code
4924/// template<typename T>
4925/// struct X {
4926/// typedef T* pointer;
4927/// pointer data();
4928/// };
4929///
4930/// template<typename T>
4931/// typename X<T>::pointer X<T>::data() { ... }
4932/// \endcode
4933///
4934/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4935/// since we do not know that we can look into X<T> when we parsed the type.
4936/// This function will rebuild the type, performing the lookup of "pointer"
4937/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4938/// as the canonical type of T*, allowing the return types of the out-of-line
4939/// definition and the declaration to match.
4940QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4941 DeclarationName Name) {
4942 if (T.isNull() || !T->isDependentType())
4943 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004944
Douglas Gregor4a959d82009-08-06 16:20:37 +00004945 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4946 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004947}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004948
4949/// \brief Produces a formatted string that describes the binding of
4950/// template parameters to template arguments.
4951std::string
4952Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4953 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004954 // FIXME: For variadic templates, we'll need to get the structured list.
4955 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4956 Args.flat_size());
4957}
4958
4959std::string
4960Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4961 const TemplateArgument *Args,
4962 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004963 std::string Result;
4964
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004965 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004966 return Result;
4967
4968 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004969 if (I >= NumArgs)
4970 break;
4971
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004972 if (I == 0)
4973 Result += "[with ";
4974 else
4975 Result += ", ";
4976
4977 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4978 Result += Id->getName();
4979 } else {
4980 Result += '$';
4981 Result += llvm::utostr(I);
4982 }
4983
4984 Result += " = ";
4985
4986 switch (Args[I].getKind()) {
4987 case TemplateArgument::Null:
4988 Result += "<no value>";
4989 break;
4990
4991 case TemplateArgument::Type: {
4992 std::string TypeStr;
4993 Args[I].getAsType().getAsStringInternal(TypeStr,
4994 Context.PrintingPolicy);
4995 Result += TypeStr;
4996 break;
4997 }
4998
4999 case TemplateArgument::Declaration: {
5000 bool Unnamed = true;
5001 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5002 if (ND->getDeclName()) {
5003 Unnamed = false;
5004 Result += ND->getNameAsString();
5005 }
5006 }
5007
5008 if (Unnamed) {
5009 Result += "<anonymous>";
5010 }
5011 break;
5012 }
5013
Douglas Gregor788cd062009-11-11 01:00:40 +00005014 case TemplateArgument::Template: {
5015 std::string Str;
5016 llvm::raw_string_ostream OS(Str);
5017 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5018 Result += OS.str();
5019 break;
5020 }
5021
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005022 case TemplateArgument::Integral: {
5023 Result += Args[I].getAsIntegral()->toString(10);
5024 break;
5025 }
5026
5027 case TemplateArgument::Expression: {
5028 assert(false && "No expressions in deduced template arguments!");
5029 Result += "<expression>";
5030 break;
5031 }
5032
5033 case TemplateArgument::Pack:
5034 // FIXME: Format template argument packs
5035 Result += "<template argument pack>";
5036 break;
5037 }
5038 }
5039
5040 Result += ']';
5041 return Result;
5042}