blob: c98f88f86aab9d5a35dad98f288d04e0de4b85d5 [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
John McCall7a9813c2010-01-22 00:28:27 +0000452 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
453 Loc, 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
John McCall7a9813c2010-01-22 00:28:27 +0000575 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
576 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000577 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000578 if (Invalid)
579 Param->setInvalidDecl();
580
581 if (D.getIdentifier()) {
582 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000583 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000584 IdResolver.AddDecl(Param);
585 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000586 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000587}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000588
Douglas Gregord684b002009-02-10 19:49:53 +0000589/// \brief Adds a default argument to the given non-type template
590/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000591void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000592 SourceLocation EqualLoc,
593 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000594 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000595 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000596 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Douglas Gregord684b002009-02-10 19:49:53 +0000598 // C++ [temp.param]p14:
599 // A template-parameter shall not be used in its own default argument.
600 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Douglas Gregord684b002009-02-10 19:49:53 +0000602 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000603 TemplateArgument Converted;
604 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
605 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000606 TemplateParm->setInvalidDecl();
607 return;
608 }
609
Anders Carlssone9146f22009-05-01 19:49:17 +0000610 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000611}
612
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000613
614/// ActOnTemplateTemplateParameter - Called when a C++ template template
615/// parameter (e.g. T in template <template <typename> class T> class array)
616/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000617Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
618 SourceLocation TmpLoc,
619 TemplateParamsTy *Params,
620 IdentifierInfo *Name,
621 SourceLocation NameLoc,
622 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000623 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000624 assert(S->isTemplateParamScope() &&
625 "Template template parameter not in template parameter scope!");
626
627 // Construct the parameter object.
628 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000629 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
630 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000631 (TemplateParameterList*)Params);
632
633 // Make sure the parameter is valid.
634 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
635 // do anything yet. However, if the template parameter list or (eventual)
636 // default value is ever invalidated, that will propagate here.
637 bool Invalid = false;
638 if (Invalid) {
639 Param->setInvalidDecl();
640 }
641
642 // If the tt-param has a name, then link the identifier into the scope
643 // and lookup mechanisms.
644 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000645 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000646 IdResolver.AddDecl(Param);
647 }
648
Chris Lattnerb28317a2009-03-28 19:18:32 +0000649 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000650}
651
Douglas Gregord684b002009-02-10 19:49:53 +0000652/// \brief Adds a default argument to the given template template
653/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000654void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000655 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000656 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000657 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000658 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000659
Douglas Gregord684b002009-02-10 19:49:53 +0000660 // C++ [temp.param]p14:
661 // A template-parameter shall not be used in its own default argument.
662 // FIXME: Implement this check! Needs a recursive walk over the types.
663
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000664 // Check only that we have a template template argument. We don't want to
665 // try to check well-formedness now, because our template template parameter
666 // might have dependent types in its template parameters, which we wouldn't
667 // be able to match now.
668 //
669 // If none of the template template parameter's template arguments mention
670 // other template parameters, we could actually perform more checking here.
671 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000672 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000673 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
674 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
675 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000676 return;
677 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000678
Douglas Gregor788cd062009-11-11 01:00:40 +0000679 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000680}
681
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000682/// ActOnTemplateParameterList - Builds a TemplateParameterList that
683/// contains the template parameters in Params/NumParams.
684Sema::TemplateParamsTy *
685Sema::ActOnTemplateParameterList(unsigned Depth,
686 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000687 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000688 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000689 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000690 SourceLocation RAngleLoc) {
691 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000692 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000693
Douglas Gregorddc29e12009-02-06 22:42:48 +0000694 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000695 (NamedDecl**)Params, NumParams,
696 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000697}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000698
Douglas Gregor212e81c2009-03-25 00:13:59 +0000699Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000700Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000701 SourceLocation KWLoc, const CXXScopeSpec &SS,
702 IdentifierInfo *Name, SourceLocation NameLoc,
703 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000704 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000705 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000706 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000707 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000708 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000709 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000710
711 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000712 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000713 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000714
John McCall05b23ea2009-09-14 21:59:20 +0000715 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
716 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000717
718 // There is no such thing as an unnamed class template.
719 if (!Name) {
720 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000721 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000722 }
723
724 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000725 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000726 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000727 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000728 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000729 if (RequireCompleteDeclContext(SS))
730 return true;
731
Douglas Gregor05396e22009-08-25 17:23:04 +0000732 SemanticContext = computeDeclContext(SS, true);
733 if (!SemanticContext) {
734 // FIXME: Produce a reasonable diagnostic here
735 return true;
736 }
Mike Stump1eb44332009-09-09 15:08:12 +0000737
John McCalla24dc2e2009-11-17 02:14:36 +0000738 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000739 } else {
740 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000741 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000742 }
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Douglas Gregorddc29e12009-02-06 22:42:48 +0000744 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
745 NamedDecl *PrevDecl = 0;
746 if (Previous.begin() != Previous.end())
747 PrevDecl = *Previous.begin();
748
Douglas Gregorddc29e12009-02-06 22:42:48 +0000749 // If there is a previous declaration with the same name, check
750 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000751 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000752 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000753
754 // We may have found the injected-class-name of a class template,
755 // class template partial specialization, or class template specialization.
756 // In these cases, grab the template that is being defined or specialized.
757 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
758 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
759 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
760 PrevClassTemplate
761 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
762 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
763 PrevClassTemplate
764 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
765 ->getSpecializedTemplate();
766 }
767 }
768
John McCall65c49462009-12-18 11:25:59 +0000769 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000770 // C++ [namespace.memdef]p3:
771 // [...] When looking for a prior declaration of a class or a function
772 // declared as a friend, and when the name of the friend class or
773 // function is neither a qualified name nor a template-id, scopes outside
774 // the innermost enclosing namespace scope are not considered.
775 DeclContext *OutermostContext = CurContext;
776 while (!OutermostContext->isFileContext())
777 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000778
779 if (PrevDecl &&
780 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
781 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCalle129d442009-12-17 23:21:11 +0000782 SemanticContext = PrevDecl->getDeclContext();
783 } else {
784 // Declarations in outer scopes don't matter. However, the outermost
785 // context we computed is the semantic context for our new
786 // declaration.
787 PrevDecl = PrevClassTemplate = 0;
788 SemanticContext = OutermostContext;
789 }
790
791 if (CurContext->isDependentContext()) {
792 // If this is a dependent context, we don't want to link the friend
793 // class template to the template in scope, because that would perform
794 // checking of the template parameter lists that can't be performed
795 // until the outer context is instantiated.
796 PrevDecl = PrevClassTemplate = 0;
797 }
798 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
799 PrevDecl = PrevClassTemplate = 0;
800
Douglas Gregorddc29e12009-02-06 22:42:48 +0000801 if (PrevClassTemplate) {
802 // Ensure that the template parameter lists are compatible.
803 if (!TemplateParameterListsAreEqual(TemplateParams,
804 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000805 /*Complain=*/true,
806 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000807 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000808
809 // C++ [temp.class]p4:
810 // In a redeclaration, partial specialization, explicit
811 // specialization or explicit instantiation of a class template,
812 // the class-key shall agree in kind with the original class
813 // template declaration (7.1.5.3).
814 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000815 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000816 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000817 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000818 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000819 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000820 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000821 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000822 }
823
Douglas Gregorddc29e12009-02-06 22:42:48 +0000824 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000825 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000826 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000827 Diag(NameLoc, diag::err_redefinition) << Name;
828 Diag(Def->getLocation(), diag::note_previous_definition);
829 // FIXME: Would it make sense to try to "forget" the previous
830 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000831 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000832 }
833 }
834 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
835 // Maybe we will complain about the shadowed template parameter.
836 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
837 // Just pretend that we didn't see the previous declaration.
838 PrevDecl = 0;
839 } else if (PrevDecl) {
840 // C++ [temp]p5:
841 // A class template shall not have the same name as any other
842 // template, class, function, object, enumeration, enumerator,
843 // namespace, or type in the same scope (3.3), except as specified
844 // in (14.5.4).
845 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
846 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000847 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000848 }
849
Douglas Gregord684b002009-02-10 19:49:53 +0000850 // Check the template parameter list of this declaration, possibly
851 // merging in the template parameter list from the previous class
852 // template declaration.
853 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000854 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
855 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000856 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Douglas Gregor7da97d02009-05-10 22:57:19 +0000858 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000859 // declaration!
860
Mike Stump1eb44332009-09-09 15:08:12 +0000861 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000862 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000863 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000864 PrevClassTemplate->getTemplatedDecl() : 0,
865 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000866
867 ClassTemplateDecl *NewTemplate
868 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
869 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000870 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000871 NewClass->setDescribedClassTemplate(NewTemplate);
872
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000873 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000874 QualType T =
875 Context.getTypeDeclType(NewClass,
876 PrevClassTemplate?
877 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000878 assert(T->isDependentType() && "Class template type is not dependent?");
879 (void)T;
880
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000881 // If we are providing an explicit specialization of a member that is a
882 // class template, make a note of that.
883 if (PrevClassTemplate &&
884 PrevClassTemplate->getInstantiatedFromMemberTemplate())
885 PrevClassTemplate->setMemberSpecialization();
886
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000887 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000888 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000889 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Douglas Gregorddc29e12009-02-06 22:42:48 +0000891 // Set the lexical context of these templates
892 NewClass->setLexicalDeclContext(CurContext);
893 NewTemplate->setLexicalDeclContext(CurContext);
894
John McCall0f434ec2009-07-31 02:45:11 +0000895 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000896 NewClass->startDefinition();
897
898 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000899 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000900
John McCall05b23ea2009-09-14 21:59:20 +0000901 if (TUK != TUK_Friend)
902 PushOnScopeChains(NewTemplate, S);
903 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000904 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000905 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000906 NewClass->setAccess(PrevClassTemplate->getAccess());
907 }
John McCall05b23ea2009-09-14 21:59:20 +0000908
Douglas Gregord85bea22009-09-26 06:47:28 +0000909 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
910 PrevClassTemplate != NULL);
911
John McCall05b23ea2009-09-14 21:59:20 +0000912 // Friend templates are visible in fairly strange ways.
913 if (!CurContext->isDependentContext()) {
914 DeclContext *DC = SemanticContext->getLookupContext();
915 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
916 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
917 PushOnScopeChains(NewTemplate, EnclosingScope,
918 /* AddToContext = */ false);
919 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000920
921 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
922 NewClass->getLocation(),
923 NewTemplate,
924 /*FIXME:*/NewClass->getLocation());
925 Friend->setAccess(AS_public);
926 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000927 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000928
Douglas Gregord684b002009-02-10 19:49:53 +0000929 if (Invalid) {
930 NewTemplate->setInvalidDecl();
931 NewClass->setInvalidDecl();
932 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000933 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000934}
935
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000936/// \brief Diagnose the presence of a default template argument on a
937/// template parameter, which is ill-formed in certain contexts.
938///
939/// \returns true if the default template argument should be dropped.
940static bool DiagnoseDefaultTemplateArgument(Sema &S,
941 Sema::TemplateParamListContext TPC,
942 SourceLocation ParamLoc,
943 SourceRange DefArgRange) {
944 switch (TPC) {
945 case Sema::TPC_ClassTemplate:
946 return false;
947
948 case Sema::TPC_FunctionTemplate:
949 // C++ [temp.param]p9:
950 // A default template-argument shall not be specified in a
951 // function template declaration or a function template
952 // definition [...]
953 // (This sentence is not in C++0x, per DR226).
954 if (!S.getLangOptions().CPlusPlus0x)
955 S.Diag(ParamLoc,
956 diag::err_template_parameter_default_in_function_template)
957 << DefArgRange;
958 return false;
959
960 case Sema::TPC_ClassTemplateMember:
961 // C++0x [temp.param]p9:
962 // A default template-argument shall not be specified in the
963 // template-parameter-lists of the definition of a member of a
964 // class template that appears outside of the member's class.
965 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
966 << DefArgRange;
967 return true;
968
969 case Sema::TPC_FriendFunctionTemplate:
970 // C++ [temp.param]p9:
971 // A default template-argument shall not be specified in a
972 // friend template declaration.
973 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
974 << DefArgRange;
975 return true;
976
977 // FIXME: C++0x [temp.param]p9 allows default template-arguments
978 // for friend function templates if there is only a single
979 // declaration (and it is a definition). Strange!
980 }
981
982 return false;
983}
984
Douglas Gregord684b002009-02-10 19:49:53 +0000985/// \brief Checks the validity of a template parameter list, possibly
986/// considering the template parameter list from a previous
987/// declaration.
988///
989/// If an "old" template parameter list is provided, it must be
990/// equivalent (per TemplateParameterListsAreEqual) to the "new"
991/// template parameter list.
992///
993/// \param NewParams Template parameter list for a new template
994/// declaration. This template parameter list will be updated with any
995/// default arguments that are carried through from the previous
996/// template parameter list.
997///
998/// \param OldParams If provided, template parameter list from a
999/// previous declaration of the same template. Default template
1000/// arguments will be merged from the old template parameter list to
1001/// the new template parameter list.
1002///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001003/// \param TPC Describes the context in which we are checking the given
1004/// template parameter list.
1005///
Douglas Gregord684b002009-02-10 19:49:53 +00001006/// \returns true if an error occurred, false otherwise.
1007bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001008 TemplateParameterList *OldParams,
1009 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001010 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Douglas Gregord684b002009-02-10 19:49:53 +00001012 // C++ [temp.param]p10:
1013 // The set of default template-arguments available for use with a
1014 // template declaration or definition is obtained by merging the
1015 // default arguments from the definition (if in scope) and all
1016 // declarations in scope in the same way default function
1017 // arguments are (8.3.6).
1018 bool SawDefaultArgument = false;
1019 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001020
Anders Carlsson49d25572009-06-12 23:20:15 +00001021 bool SawParameterPack = false;
1022 SourceLocation ParameterPackLoc;
1023
Mike Stump1a35fde2009-02-11 23:03:27 +00001024 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001025 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001026 if (OldParams)
1027 OldParam = OldParams->begin();
1028
1029 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1030 NewParamEnd = NewParams->end();
1031 NewParam != NewParamEnd; ++NewParam) {
1032 // Variables used to diagnose redundant default arguments
1033 bool RedundantDefaultArg = false;
1034 SourceLocation OldDefaultLoc;
1035 SourceLocation NewDefaultLoc;
1036
1037 // Variables used to diagnose missing default arguments
1038 bool MissingDefaultArg = false;
1039
Anders Carlsson49d25572009-06-12 23:20:15 +00001040 // C++0x [temp.param]p11:
1041 // If a template parameter of a class template is a template parameter pack,
1042 // it must be the last template parameter.
1043 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001044 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001045 diag::err_template_param_pack_must_be_last_template_parameter);
1046 Invalid = true;
1047 }
1048
Douglas Gregord684b002009-02-10 19:49:53 +00001049 if (TemplateTypeParmDecl *NewTypeParm
1050 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001051 // Check the presence of a default argument here.
1052 if (NewTypeParm->hasDefaultArgument() &&
1053 DiagnoseDefaultTemplateArgument(*this, TPC,
1054 NewTypeParm->getLocation(),
1055 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1056 .getFullSourceRange()))
1057 NewTypeParm->removeDefaultArgument();
1058
1059 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001060 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001061 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Anders Carlsson49d25572009-06-12 23:20:15 +00001063 if (NewTypeParm->isParameterPack()) {
1064 assert(!NewTypeParm->hasDefaultArgument() &&
1065 "Parameter packs can't have a default argument!");
1066 SawParameterPack = true;
1067 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001068 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001069 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001070 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1071 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1072 SawDefaultArgument = true;
1073 RedundantDefaultArg = true;
1074 PreviousDefaultArgLoc = NewDefaultLoc;
1075 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1076 // Merge the default argument from the old declaration to the
1077 // new declaration.
1078 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001079 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001080 true);
1081 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1082 } else if (NewTypeParm->hasDefaultArgument()) {
1083 SawDefaultArgument = true;
1084 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1085 } else if (SawDefaultArgument)
1086 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001087 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001088 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001089 // Check the presence of a default argument here.
1090 if (NewNonTypeParm->hasDefaultArgument() &&
1091 DiagnoseDefaultTemplateArgument(*this, TPC,
1092 NewNonTypeParm->getLocation(),
1093 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1094 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1095 NewNonTypeParm->setDefaultArgument(0);
1096 }
1097
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001098 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001099 NonTypeTemplateParmDecl *OldNonTypeParm
1100 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001101 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001102 NewNonTypeParm->hasDefaultArgument()) {
1103 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1104 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1105 SawDefaultArgument = true;
1106 RedundantDefaultArg = true;
1107 PreviousDefaultArgLoc = NewDefaultLoc;
1108 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1109 // Merge the default argument from the old declaration to the
1110 // new declaration.
1111 SawDefaultArgument = true;
1112 // FIXME: We need to create a new kind of "default argument"
1113 // expression that points to a previous template template
1114 // parameter.
1115 NewNonTypeParm->setDefaultArgument(
1116 OldNonTypeParm->getDefaultArgument());
1117 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1118 } else if (NewNonTypeParm->hasDefaultArgument()) {
1119 SawDefaultArgument = true;
1120 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1121 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001122 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001123 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001124 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001125 TemplateTemplateParmDecl *NewTemplateParm
1126 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001127 if (NewTemplateParm->hasDefaultArgument() &&
1128 DiagnoseDefaultTemplateArgument(*this, TPC,
1129 NewTemplateParm->getLocation(),
1130 NewTemplateParm->getDefaultArgument().getSourceRange()))
1131 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1132
1133 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001134 TemplateTemplateParmDecl *OldTemplateParm
1135 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001136 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001137 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001138 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1139 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001140 SawDefaultArgument = true;
1141 RedundantDefaultArg = true;
1142 PreviousDefaultArgLoc = NewDefaultLoc;
1143 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1144 // Merge the default argument from the old declaration to the
1145 // new declaration.
1146 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001147 // FIXME: We need to create a new kind of "default argument" expression
1148 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001149 NewTemplateParm->setDefaultArgument(
1150 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001151 PreviousDefaultArgLoc
1152 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001153 } else if (NewTemplateParm->hasDefaultArgument()) {
1154 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001155 PreviousDefaultArgLoc
1156 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001157 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001158 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001159 }
1160
1161 if (RedundantDefaultArg) {
1162 // C++ [temp.param]p12:
1163 // A template-parameter shall not be given default arguments
1164 // by two different declarations in the same scope.
1165 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1166 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1167 Invalid = true;
1168 } else if (MissingDefaultArg) {
1169 // C++ [temp.param]p11:
1170 // If a template-parameter has a default template-argument,
1171 // all subsequent template-parameters shall have a default
1172 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001173 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001174 diag::err_template_param_default_arg_missing);
1175 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1176 Invalid = true;
1177 }
1178
1179 // If we have an old template parameter list that we're merging
1180 // in, move on to the next parameter.
1181 if (OldParams)
1182 ++OldParam;
1183 }
1184
1185 return Invalid;
1186}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001187
Mike Stump1eb44332009-09-09 15:08:12 +00001188/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001189/// specifier, returning the template parameter list that applies to the
1190/// name.
1191///
1192/// \param DeclStartLoc the start of the declaration that has a scope
1193/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001194///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001195/// \param SS the scope specifier that will be matched to the given template
1196/// parameter lists. This scope specifier precedes a qualified name that is
1197/// being declared.
1198///
1199/// \param ParamLists the template parameter lists, from the outermost to the
1200/// innermost template parameter lists.
1201///
1202/// \param NumParamLists the number of template parameter lists in ParamLists.
1203///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001204/// \param IsExplicitSpecialization will be set true if the entity being
1205/// declared is an explicit specialization, false otherwise.
1206///
Mike Stump1eb44332009-09-09 15:08:12 +00001207/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001208/// name that is preceded by the scope specifier @p SS. This template
1209/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001210/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001211/// template specialization), or may be NULL (if we were's declaring isn't
1212/// itself a template).
1213TemplateParameterList *
1214Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1215 const CXXScopeSpec &SS,
1216 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001217 unsigned NumParamLists,
1218 bool &IsExplicitSpecialization) {
1219 IsExplicitSpecialization = false;
1220
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001221 // Find the template-ids that occur within the nested-name-specifier. These
1222 // template-ids will match up with the template parameter lists.
1223 llvm::SmallVector<const TemplateSpecializationType *, 4>
1224 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001225 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1226 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001227 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1228 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001229 const Type *T = NNS->getAsType();
1230 if (!T) break;
1231
1232 // C++0x [temp.expl.spec]p17:
1233 // A member or a member template may be nested within many
1234 // enclosing class templates. In an explicit specialization for
1235 // such a member, the member declaration shall be preceded by a
1236 // template<> for each enclosing class template that is
1237 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001238 //
1239 // Following the existing practice of GNU and EDG, we allow a typedef of a
1240 // template specialization type.
1241 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1242 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001243
Mike Stump1eb44332009-09-09 15:08:12 +00001244 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001245 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001246 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1247 if (!Template)
1248 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Ted Kremenek6217b802009-07-29 21:53:49 +00001250 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001251 ClassTemplateSpecializationDecl *SpecDecl
1252 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1253 // If the nested name specifier refers to an explicit specialization,
1254 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001255 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1256 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001257 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001258 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001259 }
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001261 TemplateIdsInSpecifier.push_back(SpecType);
1262 }
1263 }
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001265 // Reverse the list of template-ids in the scope specifier, so that we can
1266 // more easily match up the template-ids and the template parameter lists.
1267 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001269 SourceLocation FirstTemplateLoc = DeclStartLoc;
1270 if (NumParamLists)
1271 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001273 // Match the template-ids found in the specifier to the template parameter
1274 // lists.
1275 unsigned Idx = 0;
1276 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1277 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001278 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1279 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001280 if (Idx >= NumParamLists) {
1281 // We have a template-id without a corresponding template parameter
1282 // list.
1283 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001284 // FIXME: the location information here isn't great.
1285 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001286 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001287 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001288 << SS.getRange();
1289 } else {
1290 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1291 << SS.getRange()
1292 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1293 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001294 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001295 }
1296 return 0;
1297 }
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001299 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001300 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001301 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001302 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1303
Mike Stump1eb44332009-09-09 15:08:12 +00001304 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001305 = dyn_cast<ClassTemplateDecl>(Template)) {
1306 TemplateParameterList *ExpectedTemplateParams = 0;
1307 // Is this template-id naming the primary template?
1308 if (Context.hasSameType(TemplateId,
1309 ClassTemplate->getInjectedClassNameType(Context)))
1310 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1311 // ... or a partial specialization?
1312 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1313 = ClassTemplate->findPartialSpecialization(TemplateId))
1314 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1315
1316 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001317 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001318 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001319 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001320 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001321
1322 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001323 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001324 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001325 diag::err_template_param_list_matches_nontemplate)
1326 << TemplateId
1327 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001328 else
1329 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001330 }
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001332 // If there were at least as many template-ids as there were template
1333 // parameter lists, then there are no template parameter lists remaining for
1334 // the declaration itself.
1335 if (Idx >= NumParamLists)
1336 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001338 // If there were too many template parameter lists, complain about that now.
1339 if (Idx != NumParamLists - 1) {
1340 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001341 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001342 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001343 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1344 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001345 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1346 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001347
1348 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1349 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1350 diag::note_explicit_template_spec_does_not_need_header)
1351 << ExplicitSpecializationsInSpecifier.back();
1352 ExplicitSpecializationsInSpecifier.pop_back();
1353 }
1354
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001355 ++Idx;
1356 }
1357 }
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001359 // Return the last template parameter list, which corresponds to the
1360 // entity being declared.
1361 return ParamLists[NumParamLists - 1];
1362}
1363
Douglas Gregor7532dc62009-03-30 22:58:21 +00001364QualType Sema::CheckTemplateIdType(TemplateName Name,
1365 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001366 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001367 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001368 if (!Template) {
1369 // The template name does not resolve to a template, so we just
1370 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001371 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001372 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001373
Douglas Gregor40808ce2009-03-09 23:48:35 +00001374 // Check that the template argument list is well-formed for this
1375 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001376 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001377 TemplateArgs.size());
1378 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001379 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001380 return QualType();
1381
Mike Stump1eb44332009-09-09 15:08:12 +00001382 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001383 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001384 "Converted template argument list is too short!");
1385
1386 QualType CanonType;
1387
Douglas Gregorcaddba02009-11-12 18:38:13 +00001388 if (Name.isDependent() ||
1389 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001390 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001391 // This class template specialization is a dependent
1392 // type. Therefore, its canonical type is another class template
1393 // specialization type that contains all of the converted
1394 // arguments in canonical form. This ensures that, e.g., A<T> and
1395 // A<T, T> have identical types when A is declared as:
1396 //
1397 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001398 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001399 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001400 Converted.getFlatArguments(),
1401 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Douglas Gregor1275ae02009-07-28 23:00:59 +00001403 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001404 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001405 // In the future, we need to teach getTemplateSpecializationType to only
1406 // build the canonical type and return that to us.
1407 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001408 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001409 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001410 // Find the class template specialization declaration that
1411 // corresponds to these arguments.
1412 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001413 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001414 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001415 Converted.flatSize(),
1416 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001417 void *InsertPos = 0;
1418 ClassTemplateSpecializationDecl *Decl
1419 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1420 if (!Decl) {
1421 // This is the first time we have referenced this class template
1422 // specialization. Create the canonical declaration and add it to
1423 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001424 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001425 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001426 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001427 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001428 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001429 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1430 Decl->setLexicalDeclContext(CurContext);
1431 }
1432
1433 CanonType = Context.getTypeDeclType(Decl);
1434 }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Douglas Gregor40808ce2009-03-09 23:48:35 +00001436 // Build the fully-sugared type for this class template
1437 // specialization, which refers back to the class template
1438 // specialization we created or found.
John McCalld5532b62009-11-23 01:53:49 +00001439 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001440}
1441
Douglas Gregorcc636682009-02-17 23:15:12 +00001442Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001443Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001444 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001445 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001446 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001447 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001448
Douglas Gregor40808ce2009-03-09 23:48:35 +00001449 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001450 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001451 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001452
John McCalld5532b62009-11-23 01:53:49 +00001453 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001454 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001455
1456 if (Result.isNull())
1457 return true;
1458
John McCalla93c9342009-12-07 02:54:59 +00001459 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001460 TemplateSpecializationTypeLoc TL
1461 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1462 TL.setTemplateNameLoc(TemplateLoc);
1463 TL.setLAngleLoc(LAngleLoc);
1464 TL.setRAngleLoc(RAngleLoc);
1465 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1466 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1467
1468 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001469}
John McCallf1bbbb42009-09-04 01:14:41 +00001470
John McCall6b2becf2009-09-08 17:47:29 +00001471Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1472 TagUseKind TUK,
1473 DeclSpec::TST TagSpec,
1474 SourceLocation TagLoc) {
1475 if (TypeResult.isInvalid())
1476 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001477
John McCall833ca992009-10-29 08:12:44 +00001478 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001479 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001480 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001481
John McCall6b2becf2009-09-08 17:47:29 +00001482 // Verify the tag specifier.
1483 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001484
John McCall6b2becf2009-09-08 17:47:29 +00001485 if (const RecordType *RT = Type->getAs<RecordType>()) {
1486 RecordDecl *D = RT->getDecl();
1487
1488 IdentifierInfo *Id = D->getIdentifier();
1489 assert(Id && "templated class must have an identifier");
1490
1491 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1492 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001493 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001494 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1495 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001496 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001497 }
1498 }
1499
John McCall6b2becf2009-09-08 17:47:29 +00001500 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1501
1502 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001503}
1504
John McCallf7a1a742009-11-24 19:00:30 +00001505Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1506 LookupResult &R,
1507 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001508 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001509 // FIXME: Can we do any checking at this point? I guess we could check the
1510 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001511 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001512 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001513
1514 // These should be filtered out by our callers.
1515 assert(!R.empty() && "empty lookup results when building templateid");
1516 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1517
1518 NestedNameSpecifier *Qualifier = 0;
1519 SourceRange QualifierRange;
1520 if (SS.isSet()) {
1521 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1522 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001523 }
John McCallc373d482010-01-27 01:50:18 +00001524
1525 // We don't want lookup warnings at this point.
1526 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001527
John McCallf7a1a742009-11-24 19:00:30 +00001528 bool Dependent
1529 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1530 &TemplateArgs);
1531 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001532 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001533 Qualifier, QualifierRange,
1534 R.getLookupName(), R.getNameLoc(),
1535 RequiresADL, TemplateArgs);
John McCallc373d482010-01-27 01:50:18 +00001536 ULE->addDecls(R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001537
1538 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001539}
1540
John McCallf7a1a742009-11-24 19:00:30 +00001541// We actually only call this from template instantiation.
1542Sema::OwningExprResult
1543Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1544 DeclarationName Name,
1545 SourceLocation NameLoc,
1546 const TemplateArgumentListInfo &TemplateArgs) {
1547 DeclContext *DC;
1548 if (!(DC = computeDeclContext(SS, false)) ||
1549 DC->isDependentContext() ||
1550 RequireCompleteDeclContext(SS))
1551 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
John McCallf7a1a742009-11-24 19:00:30 +00001553 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1554 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
John McCallf7a1a742009-11-24 19:00:30 +00001556 if (R.isAmbiguous())
1557 return ExprError();
1558
1559 if (R.empty()) {
1560 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1561 << Name << SS.getRange();
1562 return ExprError();
1563 }
1564
1565 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1566 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1567 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1568 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1569 return ExprError();
1570 }
1571
1572 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001573}
1574
Douglas Gregorc45c2322009-03-31 00:43:58 +00001575/// \brief Form a dependent template name.
1576///
1577/// This action forms a dependent template name given the template
1578/// name and its (presumably dependent) scope specifier. For
1579/// example, given "MetaFun::template apply", the scope specifier \p
1580/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1581/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001582Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001583Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001584 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001585 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001586 TypeTy *ObjectType,
1587 bool EnteringContext) {
Douglas Gregor0707bc52010-01-19 16:01:07 +00001588 DeclContext *LookupCtx = 0;
1589 if (SS.isSet())
1590 LookupCtx = computeDeclContext(SS, EnteringContext);
1591 if (!LookupCtx && ObjectType)
1592 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1593 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001594 // C++0x [temp.names]p5:
1595 // If a name prefixed by the keyword template is not the name of
1596 // a template, the program is ill-formed. [Note: the keyword
1597 // template may not be applied to non-template members of class
1598 // templates. -end note ] [ Note: as is the case with the
1599 // typename prefix, the template prefix is allowed in cases
1600 // where it is not strictly necessary; i.e., when the
1601 // nested-name-specifier or the expression on the left of the ->
1602 // or . is not dependent on a template-parameter, or the use
1603 // does not appear in the scope of a template. -end note]
1604 //
1605 // Note: C++03 was more strict here, because it banned the use of
1606 // the "template" keyword prior to a template-name that was not a
1607 // dependent name. C++ DR468 relaxed this requirement (the
1608 // "template" keyword is now permitted). We follow the C++0x
1609 // rules, even in C++03 mode, retroactively applying the DR.
1610 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001611 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001612 EnteringContext, Template);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001613 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1614 isa<CXXRecordDecl>(LookupCtx) &&
1615 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001616 // This is a dependent template.
1617 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001618 Diag(Name.getSourceRange().getBegin(),
1619 diag::err_template_kw_refers_to_non_template)
1620 << GetNameFromUnqualifiedId(Name)
1621 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001622 return TemplateTy();
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001623 } else {
1624 // We found something; return it.
1625 return Template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001626 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001627 }
1628
Mike Stump1eb44332009-09-09 15:08:12 +00001629 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001630 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001631
1632 switch (Name.getKind()) {
1633 case UnqualifiedId::IK_Identifier:
1634 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1635 Name.Identifier));
1636
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001637 case UnqualifiedId::IK_OperatorFunctionId:
1638 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1639 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001640
1641 case UnqualifiedId::IK_LiteralOperatorId:
1642 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1643
Douglas Gregor014e88d2009-11-03 23:16:33 +00001644 default:
1645 break;
1646 }
1647
1648 Diag(Name.getSourceRange().getBegin(),
1649 diag::err_template_kw_refers_to_non_template)
1650 << GetNameFromUnqualifiedId(Name)
1651 << Name.getSourceRange();
1652 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001653}
1654
Mike Stump1eb44332009-09-09 15:08:12 +00001655bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001656 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001657 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001658 const TemplateArgument &Arg = AL.getArgument();
1659
Anders Carlsson436b1562009-06-13 00:33:33 +00001660 // Check template type parameter.
1661 if (Arg.getKind() != TemplateArgument::Type) {
1662 // C++ [temp.arg.type]p1:
1663 // A template-argument for a template-parameter which is a
1664 // type shall be a type-id.
1665
1666 // We have a template type parameter but the template argument
1667 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001668 SourceRange SR = AL.getSourceRange();
1669 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001670 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Anders Carlsson436b1562009-06-13 00:33:33 +00001672 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001673 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001674
John McCalla93c9342009-12-07 02:54:59 +00001675 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001676 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Anders Carlsson436b1562009-06-13 00:33:33 +00001678 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001679 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001680 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001681 return false;
1682}
1683
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001684/// \brief Substitute template arguments into the default template argument for
1685/// the given template type parameter.
1686///
1687/// \param SemaRef the semantic analysis object for which we are performing
1688/// the substitution.
1689///
1690/// \param Template the template that we are synthesizing template arguments
1691/// for.
1692///
1693/// \param TemplateLoc the location of the template name that started the
1694/// template-id we are checking.
1695///
1696/// \param RAngleLoc the location of the right angle bracket ('>') that
1697/// terminates the template-id.
1698///
1699/// \param Param the template template parameter whose default we are
1700/// substituting into.
1701///
1702/// \param Converted the list of template arguments provided for template
1703/// parameters that precede \p Param in the template parameter list.
1704///
1705/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001706static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001707SubstDefaultTemplateArgument(Sema &SemaRef,
1708 TemplateDecl *Template,
1709 SourceLocation TemplateLoc,
1710 SourceLocation RAngleLoc,
1711 TemplateTypeParmDecl *Param,
1712 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001713 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001714
1715 // If the argument type is dependent, instantiate it now based
1716 // on the previously-computed template arguments.
1717 if (ArgType->getType()->isDependentType()) {
1718 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1719 /*TakeArgs=*/false);
1720
1721 MultiLevelTemplateArgumentList AllTemplateArgs
1722 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1723
1724 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1725 Template, Converted.getFlatArguments(),
1726 Converted.flatSize(),
1727 SourceRange(TemplateLoc, RAngleLoc));
1728
1729 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1730 Param->getDefaultArgumentLoc(),
1731 Param->getDeclName());
1732 }
1733
1734 return ArgType;
1735}
1736
1737/// \brief Substitute template arguments into the default template argument for
1738/// the given non-type template parameter.
1739///
1740/// \param SemaRef the semantic analysis object for which we are performing
1741/// the substitution.
1742///
1743/// \param Template the template that we are synthesizing template arguments
1744/// for.
1745///
1746/// \param TemplateLoc the location of the template name that started the
1747/// template-id we are checking.
1748///
1749/// \param RAngleLoc the location of the right angle bracket ('>') that
1750/// terminates the template-id.
1751///
Douglas Gregor788cd062009-11-11 01:00:40 +00001752/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001753/// substituting into.
1754///
1755/// \param Converted the list of template arguments provided for template
1756/// parameters that precede \p Param in the template parameter list.
1757///
1758/// \returns the substituted template argument, or NULL if an error occurred.
1759static Sema::OwningExprResult
1760SubstDefaultTemplateArgument(Sema &SemaRef,
1761 TemplateDecl *Template,
1762 SourceLocation TemplateLoc,
1763 SourceLocation RAngleLoc,
1764 NonTypeTemplateParmDecl *Param,
1765 TemplateArgumentListBuilder &Converted) {
1766 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1767 /*TakeArgs=*/false);
1768
1769 MultiLevelTemplateArgumentList AllTemplateArgs
1770 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1771
1772 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1773 Template, Converted.getFlatArguments(),
1774 Converted.flatSize(),
1775 SourceRange(TemplateLoc, RAngleLoc));
1776
1777 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1778}
1779
Douglas Gregor788cd062009-11-11 01:00:40 +00001780/// \brief Substitute template arguments into the default template argument for
1781/// the given template template parameter.
1782///
1783/// \param SemaRef the semantic analysis object for which we are performing
1784/// the substitution.
1785///
1786/// \param Template the template that we are synthesizing template arguments
1787/// for.
1788///
1789/// \param TemplateLoc the location of the template name that started the
1790/// template-id we are checking.
1791///
1792/// \param RAngleLoc the location of the right angle bracket ('>') that
1793/// terminates the template-id.
1794///
1795/// \param Param the template template parameter whose default we are
1796/// substituting into.
1797///
1798/// \param Converted the list of template arguments provided for template
1799/// parameters that precede \p Param in the template parameter list.
1800///
1801/// \returns the substituted template argument, or NULL if an error occurred.
1802static TemplateName
1803SubstDefaultTemplateArgument(Sema &SemaRef,
1804 TemplateDecl *Template,
1805 SourceLocation TemplateLoc,
1806 SourceLocation RAngleLoc,
1807 TemplateTemplateParmDecl *Param,
1808 TemplateArgumentListBuilder &Converted) {
1809 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1810 /*TakeArgs=*/false);
1811
1812 MultiLevelTemplateArgumentList AllTemplateArgs
1813 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1814
1815 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1816 Template, Converted.getFlatArguments(),
1817 Converted.flatSize(),
1818 SourceRange(TemplateLoc, RAngleLoc));
1819
1820 return SemaRef.SubstTemplateName(
1821 Param->getDefaultArgument().getArgument().getAsTemplate(),
1822 Param->getDefaultArgument().getTemplateNameLoc(),
1823 AllTemplateArgs);
1824}
1825
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001826/// \brief If the given template parameter has a default template
1827/// argument, substitute into that default template argument and
1828/// return the corresponding template argument.
1829TemplateArgumentLoc
1830Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1831 SourceLocation TemplateLoc,
1832 SourceLocation RAngleLoc,
1833 Decl *Param,
1834 TemplateArgumentListBuilder &Converted) {
1835 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1836 if (!TypeParm->hasDefaultArgument())
1837 return TemplateArgumentLoc();
1838
John McCalla93c9342009-12-07 02:54:59 +00001839 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001840 TemplateLoc,
1841 RAngleLoc,
1842 TypeParm,
1843 Converted);
1844 if (DI)
1845 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1846
1847 return TemplateArgumentLoc();
1848 }
1849
1850 if (NonTypeTemplateParmDecl *NonTypeParm
1851 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1852 if (!NonTypeParm->hasDefaultArgument())
1853 return TemplateArgumentLoc();
1854
1855 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1856 TemplateLoc,
1857 RAngleLoc,
1858 NonTypeParm,
1859 Converted);
1860 if (Arg.isInvalid())
1861 return TemplateArgumentLoc();
1862
1863 Expr *ArgE = Arg.takeAs<Expr>();
1864 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1865 }
1866
1867 TemplateTemplateParmDecl *TempTempParm
1868 = cast<TemplateTemplateParmDecl>(Param);
1869 if (!TempTempParm->hasDefaultArgument())
1870 return TemplateArgumentLoc();
1871
1872 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1873 TemplateLoc,
1874 RAngleLoc,
1875 TempTempParm,
1876 Converted);
1877 if (TName.isNull())
1878 return TemplateArgumentLoc();
1879
1880 return TemplateArgumentLoc(TemplateArgument(TName),
1881 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1882 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1883}
1884
Douglas Gregore7526412009-11-11 19:31:23 +00001885/// \brief Check that the given template argument corresponds to the given
1886/// template parameter.
1887bool Sema::CheckTemplateArgument(NamedDecl *Param,
1888 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001889 TemplateDecl *Template,
1890 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001891 SourceLocation RAngleLoc,
1892 TemplateArgumentListBuilder &Converted) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001893 // Check template type parameters.
1894 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001895 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001896
Douglas Gregord9e15302009-11-11 19:41:09 +00001897 // Check non-type template parameters.
1898 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001899 // Do substitution on the type of the non-type template parameter
1900 // with the template arguments we've seen thus far.
1901 QualType NTTPType = NTTP->getType();
1902 if (NTTPType->isDependentType()) {
1903 // Do substitution on the type of the non-type template parameter.
1904 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1905 NTTP, Converted.getFlatArguments(),
1906 Converted.flatSize(),
1907 SourceRange(TemplateLoc, RAngleLoc));
1908
1909 TemplateArgumentList TemplateArgs(Context, Converted,
1910 /*TakeArgs=*/false);
1911 NTTPType = SubstType(NTTPType,
1912 MultiLevelTemplateArgumentList(TemplateArgs),
1913 NTTP->getLocation(),
1914 NTTP->getDeclName());
1915 // If that worked, check the non-type template parameter type
1916 // for validity.
1917 if (!NTTPType.isNull())
1918 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1919 NTTP->getLocation());
1920 if (NTTPType.isNull())
1921 return true;
1922 }
1923
1924 switch (Arg.getArgument().getKind()) {
1925 case TemplateArgument::Null:
1926 assert(false && "Should never see a NULL template argument here");
1927 return true;
1928
1929 case TemplateArgument::Expression: {
1930 Expr *E = Arg.getArgument().getAsExpr();
1931 TemplateArgument Result;
1932 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1933 return true;
1934
1935 Converted.Append(Result);
1936 break;
1937 }
1938
1939 case TemplateArgument::Declaration:
1940 case TemplateArgument::Integral:
1941 // We've already checked this template argument, so just copy
1942 // it to the list of converted arguments.
1943 Converted.Append(Arg.getArgument());
1944 break;
1945
1946 case TemplateArgument::Template:
1947 // We were given a template template argument. It may not be ill-formed;
1948 // see below.
1949 if (DependentTemplateName *DTN
1950 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1951 // We have a template argument such as \c T::template X, which we
1952 // parsed as a template template argument. However, since we now
1953 // know that we need a non-type template argument, convert this
1954 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00001955 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1956 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00001957 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00001958 DTN->getIdentifier(),
1959 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00001960
1961 TemplateArgument Result;
1962 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1963 return true;
1964
1965 Converted.Append(Result);
1966 break;
1967 }
1968
1969 // We have a template argument that actually does refer to a class
1970 // template, template alias, or template template parameter, and
1971 // therefore cannot be a non-type template argument.
1972 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1973 << Arg.getSourceRange();
1974
1975 Diag(Param->getLocation(), diag::note_template_param_here);
1976 return true;
1977
1978 case TemplateArgument::Type: {
1979 // We have a non-type template parameter but the template
1980 // argument is a type.
1981
1982 // C++ [temp.arg]p2:
1983 // In a template-argument, an ambiguity between a type-id and
1984 // an expression is resolved to a type-id, regardless of the
1985 // form of the corresponding template-parameter.
1986 //
1987 // We warn specifically about this case, since it can be rather
1988 // confusing for users.
1989 QualType T = Arg.getArgument().getAsType();
1990 SourceRange SR = Arg.getSourceRange();
1991 if (T->isFunctionType())
1992 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1993 else
1994 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1995 Diag(Param->getLocation(), diag::note_template_param_here);
1996 return true;
1997 }
1998
1999 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002000 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002001 break;
2002 }
2003
2004 return false;
2005 }
2006
2007
2008 // Check template template parameters.
2009 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2010
2011 // Substitute into the template parameter list of the template
2012 // template parameter, since previously-supplied template arguments
2013 // may appear within the template template parameter.
2014 {
2015 // Set up a template instantiation context.
2016 LocalInstantiationScope Scope(*this);
2017 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2018 TempParm, Converted.getFlatArguments(),
2019 Converted.flatSize(),
2020 SourceRange(TemplateLoc, RAngleLoc));
2021
2022 TemplateArgumentList TemplateArgs(Context, Converted,
2023 /*TakeArgs=*/false);
2024 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2025 SubstDecl(TempParm, CurContext,
2026 MultiLevelTemplateArgumentList(TemplateArgs)));
2027 if (!TempParm)
2028 return true;
2029
2030 // FIXME: TempParam is leaked.
2031 }
2032
2033 switch (Arg.getArgument().getKind()) {
2034 case TemplateArgument::Null:
2035 assert(false && "Should never see a NULL template argument here");
2036 return true;
2037
2038 case TemplateArgument::Template:
2039 if (CheckTemplateArgument(TempParm, Arg))
2040 return true;
2041
2042 Converted.Append(Arg.getArgument());
2043 break;
2044
2045 case TemplateArgument::Expression:
2046 case TemplateArgument::Type:
2047 // We have a template template parameter but the template
2048 // argument does not refer to a template.
2049 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2050 return true;
2051
2052 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002053 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002054 "Declaration argument with template template parameter");
2055 break;
2056 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002057 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002058 "Integral argument with template template parameter");
2059 break;
2060
2061 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002062 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002063 break;
2064 }
2065
2066 return false;
2067}
2068
Douglas Gregorc15cb382009-02-09 23:23:08 +00002069/// \brief Check that the given template argument list is well-formed
2070/// for specializing the given template.
2071bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2072 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002073 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002074 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002075 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002076 TemplateParameterList *Params = Template->getTemplateParameters();
2077 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002078 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002079 bool Invalid = false;
2080
John McCalld5532b62009-11-23 01:53:49 +00002081 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2082
Mike Stump1eb44332009-09-09 15:08:12 +00002083 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002084 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002086 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002087 (NumArgs < Params->getMinRequiredArguments() &&
2088 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002089 // FIXME: point at either the first arg beyond what we can handle,
2090 // or the '>', depending on whether we have too many or too few
2091 // arguments.
2092 SourceRange Range;
2093 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002094 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002095 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2096 << (NumArgs > NumParams)
2097 << (isa<ClassTemplateDecl>(Template)? 0 :
2098 isa<FunctionTemplateDecl>(Template)? 1 :
2099 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2100 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002101 Diag(Template->getLocation(), diag::note_template_decl_here)
2102 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002103 Invalid = true;
2104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
2106 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002107 // [...] The type and form of each template-argument specified in
2108 // a template-id shall match the type and form specified for the
2109 // corresponding parameter declared by the template in its
2110 // template-parameter-list.
2111 unsigned ArgIdx = 0;
2112 for (TemplateParameterList::iterator Param = Params->begin(),
2113 ParamEnd = Params->end();
2114 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002115 if (ArgIdx > NumArgs && PartialTemplateArgs)
2116 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Douglas Gregord9e15302009-11-11 19:41:09 +00002118 // If we have a template parameter pack, check every remaining template
2119 // argument against that template parameter pack.
2120 if ((*Param)->isTemplateParameterPack()) {
2121 Converted.BeginPack();
2122 for (; ArgIdx < NumArgs; ++ArgIdx) {
2123 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2124 TemplateLoc, RAngleLoc, Converted)) {
2125 Invalid = true;
2126 break;
2127 }
2128 }
2129 Converted.EndPack();
2130 continue;
2131 }
2132
Douglas Gregorf35f8282009-11-11 21:54:23 +00002133 if (ArgIdx < NumArgs) {
2134 // Check the template argument we were given.
2135 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2136 TemplateLoc, RAngleLoc, Converted))
2137 return true;
2138
2139 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002140 }
Douglas Gregore7526412009-11-11 19:31:23 +00002141
Douglas Gregorf35f8282009-11-11 21:54:23 +00002142 // We have a default template argument that we will use.
2143 TemplateArgumentLoc Arg;
2144
2145 // Retrieve the default template argument from the template
2146 // parameter. For each kind of template parameter, we substitute the
2147 // template arguments provided thus far and any "outer" template arguments
2148 // (when the template parameter was part of a nested template) into
2149 // the default argument.
2150 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2151 if (!TTP->hasDefaultArgument()) {
2152 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2153 break;
2154 }
2155
John McCalla93c9342009-12-07 02:54:59 +00002156 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002157 Template,
2158 TemplateLoc,
2159 RAngleLoc,
2160 TTP,
2161 Converted);
2162 if (!ArgType)
2163 return true;
2164
2165 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2166 ArgType);
2167 } else if (NonTypeTemplateParmDecl *NTTP
2168 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2169 if (!NTTP->hasDefaultArgument()) {
2170 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2171 break;
2172 }
2173
2174 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2175 TemplateLoc,
2176 RAngleLoc,
2177 NTTP,
2178 Converted);
2179 if (E.isInvalid())
2180 return true;
2181
2182 Expr *Ex = E.takeAs<Expr>();
2183 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2184 } else {
2185 TemplateTemplateParmDecl *TempParm
2186 = cast<TemplateTemplateParmDecl>(*Param);
2187
2188 if (!TempParm->hasDefaultArgument()) {
2189 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2190 break;
2191 }
2192
2193 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2194 TemplateLoc,
2195 RAngleLoc,
2196 TempParm,
2197 Converted);
2198 if (Name.isNull())
2199 return true;
2200
2201 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2202 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2203 TempParm->getDefaultArgument().getTemplateNameLoc());
2204 }
2205
2206 // Introduce an instantiation record that describes where we are using
2207 // the default template argument.
2208 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2209 Converted.getFlatArguments(),
2210 Converted.flatSize(),
2211 SourceRange(TemplateLoc, RAngleLoc));
2212
2213 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002214 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002215 RAngleLoc, Converted))
2216 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002217 }
2218
2219 return Invalid;
2220}
2221
2222/// \brief Check a template argument against its corresponding
2223/// template type parameter.
2224///
2225/// This routine implements the semantics of C++ [temp.arg.type]. It
2226/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002227bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002228 TypeSourceInfo *ArgInfo) {
2229 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002230 QualType Arg = ArgInfo->getType();
2231
Douglas Gregorc15cb382009-02-09 23:23:08 +00002232 // C++ [temp.arg.type]p2:
2233 // A local type, a type with no linkage, an unnamed type or a type
2234 // compounded from any of these types shall not be used as a
2235 // template-argument for a template type-parameter.
2236 //
2237 // FIXME: Perform the recursive and no-linkage type checks.
2238 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002239 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002240 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002241 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002242 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002243 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2244 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2245 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2246 << QualType(Tag, 0) << SR;
2247 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002248 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002249 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2250 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002251 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2252 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002253 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2254 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2255 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002256 }
2257
2258 return false;
2259}
2260
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002261/// \brief Checks whether the given template argument is the address
2262/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002263bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2264 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002265 bool Invalid = false;
2266
2267 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002268 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002269 Arg = Cast->getSubExpr();
2270
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002271 // C++0x allows nullptr, and there's no further checking to be done for that.
2272 if (Arg->getType()->isNullPtrType())
2273 return false;
2274
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002275 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002276 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002277 // A template-argument for a non-type, non-template
2278 // template-parameter shall be one of: [...]
2279 //
2280 // -- the address of an object or function with external
2281 // linkage, including function templates and function
2282 // template-ids but excluding non-static class members,
2283 // expressed as & id-expression where the & is optional if
2284 // the name refers to a function or array, or if the
2285 // corresponding template-parameter is a reference; or
2286 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002288 // Ignore (and complain about) any excess parentheses.
2289 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2290 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002291 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002292 diag::err_template_arg_extra_parens)
2293 << Arg->getSourceRange();
2294 Invalid = true;
2295 }
2296
2297 Arg = Parens->getSubExpr();
2298 }
2299
2300 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2301 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2302 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2303 } else
2304 DRE = dyn_cast<DeclRefExpr>(Arg);
2305
Chandler Carruth038cc392010-01-31 10:01:20 +00002306 if (!DRE)
2307 return Diag(Arg->getSourceRange().getBegin(),
2308 diag::err_template_arg_not_decl_ref)
2309 << Arg->getSourceRange();
2310
2311 // Stop checking the precise nature of the argument if it is value dependent,
2312 // it should be checked when instantiated.
2313 if (Arg->isValueDependent())
2314 return false;
2315
2316 if (!isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002317 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002318 diag::err_template_arg_not_object_or_func_form)
2319 << Arg->getSourceRange();
2320
2321 // Cannot refer to non-static data members
2322 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2323 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2324 << Field << Arg->getSourceRange();
2325
2326 // Cannot refer to non-static member functions
2327 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2328 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002329 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002330 diag::err_template_arg_method)
2331 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002332
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002333 // Functions must have external linkage.
2334 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002335 if (!isExternalLinkage(Func->getLinkage())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002336 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002337 diag::err_template_arg_function_not_extern)
2338 << Func << Arg->getSourceRange();
2339 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2340 << true;
2341 return true;
2342 }
2343
2344 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002345 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002346 return Invalid;
2347 }
2348
2349 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002350 if (!isExternalLinkage(Var->getLinkage())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002351 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002352 diag::err_template_arg_object_not_extern)
2353 << Var << Arg->getSourceRange();
2354 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2355 << true;
2356 return true;
2357 }
2358
2359 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002360 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002361 return Invalid;
2362 }
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002364 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002365 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002366 diag::err_template_arg_not_object_or_func)
2367 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002368 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002369 diag::note_template_arg_refers_here);
2370 return true;
2371}
2372
2373/// \brief Checks whether the given template argument is a pointer to
2374/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002375bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2376 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002377 bool Invalid = false;
2378
2379 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002380 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002381 Arg = Cast->getSubExpr();
2382
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002383 // C++0x allows nullptr, and there's no further checking to be done for that.
2384 if (Arg->getType()->isNullPtrType())
2385 return false;
2386
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002387 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002388 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002389 // A template-argument for a non-type, non-template
2390 // template-parameter shall be one of: [...]
2391 //
2392 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002393 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002394
2395 // Ignore (and complain about) any excess parentheses.
2396 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2397 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002398 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002399 diag::err_template_arg_extra_parens)
2400 << Arg->getSourceRange();
2401 Invalid = true;
2402 }
2403
2404 Arg = Parens->getSubExpr();
2405 }
2406
Douglas Gregorcaddba02009-11-12 18:38:13 +00002407 // A pointer-to-member constant written &Class::member.
2408 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002409 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2410 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2411 if (DRE && !DRE->getQualifier())
2412 DRE = 0;
2413 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002414 }
2415 // A constant of pointer-to-member type.
2416 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2417 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2418 if (VD->getType()->isMemberPointerType()) {
2419 if (isa<NonTypeTemplateParmDecl>(VD) ||
2420 (isa<VarDecl>(VD) &&
2421 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2422 if (Arg->isTypeDependent() || Arg->isValueDependent())
2423 Converted = TemplateArgument(Arg->Retain());
2424 else
2425 Converted = TemplateArgument(VD->getCanonicalDecl());
2426 return Invalid;
2427 }
2428 }
2429 }
2430
2431 DRE = 0;
2432 }
2433
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002434 if (!DRE)
2435 return Diag(Arg->getSourceRange().getBegin(),
2436 diag::err_template_arg_not_pointer_to_member_form)
2437 << Arg->getSourceRange();
2438
2439 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2440 assert((isa<FieldDecl>(DRE->getDecl()) ||
2441 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2442 "Only non-static member pointers can make it here");
2443
2444 // Okay: this is the address of a non-static member, and therefore
2445 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002446 if (Arg->isTypeDependent() || Arg->isValueDependent())
2447 Converted = TemplateArgument(Arg->Retain());
2448 else
2449 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002450 return Invalid;
2451 }
2452
2453 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002454 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002455 diag::err_template_arg_not_pointer_to_member_form)
2456 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002457 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002458 diag::note_template_arg_refers_here);
2459 return true;
2460}
2461
Douglas Gregorc15cb382009-02-09 23:23:08 +00002462/// \brief Check a template argument against its corresponding
2463/// non-type template parameter.
2464///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002465/// This routine implements the semantics of C++ [temp.arg.nontype].
2466/// It returns true if an error occurred, and false otherwise. \p
2467/// InstantiatedParamType is the type of the non-type template
2468/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002469///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002470/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002471bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002472 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002473 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002474 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2475
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002476 // If either the parameter has a dependent type or the argument is
2477 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002478 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002479 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2480 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002481 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002482 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002483 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002484
2485 // C++ [temp.arg.nontype]p5:
2486 // The following conversions are performed on each expression used
2487 // as a non-type template-argument. If a non-type
2488 // template-argument cannot be converted to the type of the
2489 // corresponding template-parameter then the program is
2490 // ill-formed.
2491 //
2492 // -- for a non-type template-parameter of integral or
2493 // enumeration type, integral promotions (4.5) and integral
2494 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002495 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002496 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002497 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002498 // C++ [temp.arg.nontype]p1:
2499 // A template-argument for a non-type, non-template
2500 // template-parameter shall be one of:
2501 //
2502 // -- an integral constant-expression of integral or enumeration
2503 // type; or
2504 // -- the name of a non-type template-parameter; or
2505 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002506 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002507 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002508 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002509 diag::err_template_arg_not_integral_or_enumeral)
2510 << ArgType << Arg->getSourceRange();
2511 Diag(Param->getLocation(), diag::note_template_param_here);
2512 return true;
2513 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002514 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002515 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2516 << ArgType << Arg->getSourceRange();
2517 return true;
2518 }
2519
2520 // FIXME: We need some way to more easily get the unqualified form
2521 // of the types without going all the way to the
2522 // canonical type.
2523 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2524 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2525 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2526 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2527
2528 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002529 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002530 // Okay: no conversion necessary
2531 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2532 !ParamType->isEnumeralType()) {
2533 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002534 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002535 } else {
2536 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002537 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002538 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002539 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002540 Diag(Param->getLocation(), diag::note_template_param_here);
2541 return true;
2542 }
2543
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002544 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002545 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002546 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002547
2548 if (!Arg->isValueDependent()) {
2549 // Check that an unsigned parameter does not receive a negative
2550 // value.
2551 if (IntegerType->isUnsignedIntegerType()
2552 && (Value.isSigned() && Value.isNegative())) {
2553 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2554 << Value.toString(10) << Param->getType()
2555 << Arg->getSourceRange();
2556 Diag(Param->getLocation(), diag::note_template_param_here);
2557 return true;
2558 }
2559
2560 // Check that we don't overflow the template parameter type.
2561 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Eli Friedman29f89f62009-12-23 18:44:58 +00002562 unsigned RequiredBits;
2563 if (IntegerType->isUnsignedIntegerType())
2564 RequiredBits = Value.getActiveBits();
2565 else if (Value.isUnsigned())
2566 RequiredBits = Value.getActiveBits() + 1;
2567 else
2568 RequiredBits = Value.getMinSignedBits();
2569 if (RequiredBits > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002570 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002571 diag::err_template_arg_too_large)
2572 << Value.toString(10) << Param->getType()
2573 << Arg->getSourceRange();
2574 Diag(Param->getLocation(), diag::note_template_param_here);
2575 return true;
2576 }
2577
2578 if (Value.getBitWidth() != AllowedBits)
2579 Value.extOrTrunc(AllowedBits);
2580 Value.setIsSigned(IntegerType->isSignedIntegerType());
2581 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002582
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002583 // Add the value of this argument to the list of converted
2584 // arguments. We use the bitwidth and signedness of the template
2585 // parameter.
2586 if (Arg->isValueDependent()) {
2587 // The argument is value-dependent. Create a new
2588 // TemplateArgument with the converted expression.
2589 Converted = TemplateArgument(Arg);
2590 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002591 }
2592
John McCall833ca992009-10-29 08:12:44 +00002593 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002594 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002595 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002596 return false;
2597 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002598
Douglas Gregorb86b0572009-02-11 01:18:59 +00002599 // Handle pointer-to-function, reference-to-function, and
2600 // pointer-to-member-function all in (roughly) the same way.
2601 if (// -- For a non-type template-parameter of type pointer to
2602 // function, only the function-to-pointer conversion (4.3) is
2603 // applied. If the template-argument represents a set of
2604 // overloaded functions (or a pointer to such), the matching
2605 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002606 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002607 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002608 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002609 // -- For a non-type template-parameter of type reference to
2610 // function, no conversions apply. If the template-argument
2611 // represents a set of overloaded functions, the matching
2612 // function is selected from the set (13.4).
2613 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002614 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002615 // -- For a non-type template-parameter of type pointer to
2616 // member function, no conversions apply. If the
2617 // template-argument represents a set of overloaded member
2618 // functions, the matching member function is selected from
2619 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002620 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002621 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002622 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002623 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002624 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002625 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002626 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002627 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2628 ParamType->isMemberPointerType())) {
2629 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002630 if (ParamType->isMemberPointerType())
2631 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2632 else
2633 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002634 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002635 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002636 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002637 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002638 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002639 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2640 return true;
2641
Anders Carlsson96ad5332009-10-21 17:16:23 +00002642 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002643 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002644 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002645 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002646 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002647 }
2648 }
2649
Mike Stump1eb44332009-09-09 15:08:12 +00002650 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002651 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002652 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002653 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002654 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002655 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002656 Diag(Param->getLocation(), diag::note_template_param_here);
2657 return true;
2658 }
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Douglas Gregorcaddba02009-11-12 18:38:13 +00002660 if (ParamType->isMemberPointerType())
2661 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002663 NamedDecl *Entity = 0;
2664 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2665 return true;
2666
Chandler Carruth038cc392010-01-31 10:01:20 +00002667 if (Arg->isValueDependent()) {
2668 Converted = TemplateArgument(Arg);
2669 } else {
2670 if (Entity)
2671 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2672 Converted = TemplateArgument(Entity);
2673 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002674 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002675 }
2676
Chris Lattnerfe90de72009-02-20 21:37:53 +00002677 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002678 // -- for a non-type template-parameter of type pointer to
2679 // object, qualification conversions (4.4) and the
2680 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002681 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002682 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002683 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002684
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002685 if (ArgType->isNullPtrType()) {
2686 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002687 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002688 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002689 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002690 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002691 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002692
Douglas Gregorb86b0572009-02-11 01:18:59 +00002693 if (IsQualificationConversion(ArgType, ParamType)) {
2694 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002695 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002696 }
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002698 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002699 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002700 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002701 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002702 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002703 Diag(Param->getLocation(), diag::note_template_param_here);
2704 return true;
2705 }
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002707 NamedDecl *Entity = 0;
2708 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2709 return true;
2710
Chandler Carruth038cc392010-01-31 10:01:20 +00002711 if (Arg->isValueDependent()) {
2712 Converted = TemplateArgument(Arg);
2713 } else {
2714 if (Entity)
2715 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2716 Converted = TemplateArgument(Entity);
2717 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002718 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002719 }
Mike Stump1eb44332009-09-09 15:08:12 +00002720
Ted Kremenek6217b802009-07-29 21:53:49 +00002721 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002722 // -- For a non-type template-parameter of type reference to
2723 // object, no conversions apply. The type referred to by the
2724 // reference may be more cv-qualified than the (otherwise
2725 // identical) type of the template-argument. The
2726 // template-parameter is bound directly to the
2727 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002728 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002729 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002730
Chandler Carruth5147fa62010-02-03 09:37:33 +00002731 QualType ReferredType = ParamRefType->getPointeeType();
2732 if (!Context.hasSameUnqualifiedType(ReferredType, ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002733 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002734 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002735 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002736 << Arg->getSourceRange();
2737 Diag(Param->getLocation(), diag::note_template_param_here);
2738 return true;
2739 }
2740
Mike Stump1eb44332009-09-09 15:08:12 +00002741 unsigned ParamQuals
Chandler Carruth5147fa62010-02-03 09:37:33 +00002742 = Context.getCanonicalType(ReferredType).getCVRQualifiers();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002743 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Douglas Gregorb86b0572009-02-11 01:18:59 +00002745 if ((ParamQuals | ArgQuals) != ParamQuals) {
2746 Diag(Arg->getSourceRange().getBegin(),
2747 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002748 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002749 << Arg->getSourceRange();
2750 Diag(Param->getLocation(), diag::note_template_param_here);
2751 return true;
2752 }
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002754 NamedDecl *Entity = 0;
2755 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2756 return true;
2757
Chandler Carruth038cc392010-01-31 10:01:20 +00002758 if (Arg->isValueDependent()) {
2759 Converted = TemplateArgument(Arg);
2760 } else {
2761 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
2762 Converted = TemplateArgument(Entity);
2763 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002764 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002765 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002766
2767 // -- For a non-type template-parameter of type pointer to data
2768 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002769 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002770 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2771
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002772 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002773 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002774 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002775 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002776 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002777 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002778 } else {
2779 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002780 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002781 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002782 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002783 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002784 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002785 }
2786
Douglas Gregorcaddba02009-11-12 18:38:13 +00002787 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002788}
2789
2790/// \brief Check a template argument against its corresponding
2791/// template template parameter.
2792///
2793/// This routine implements the semantics of C++ [temp.arg.template].
2794/// It returns true if an error occurred, and false otherwise.
2795bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002796 const TemplateArgumentLoc &Arg) {
2797 TemplateName Name = Arg.getArgument().getAsTemplate();
2798 TemplateDecl *Template = Name.getAsTemplateDecl();
2799 if (!Template) {
2800 // Any dependent template name is fine.
2801 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2802 return false;
2803 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002804
2805 // C++ [temp.arg.template]p1:
2806 // A template-argument for a template template-parameter shall be
2807 // the name of a class template, expressed as id-expression. Only
2808 // primary class templates are considered when matching the
2809 // template template argument with the corresponding parameter;
2810 // partial specializations are not considered even if their
2811 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002812 //
2813 // Note that we also allow template template parameters here, which
2814 // will happen when we are dealing with, e.g., class template
2815 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002816 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002817 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002818 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002819 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002820 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002821 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002822 << Template;
2823 }
2824
2825 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2826 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002827 true,
2828 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002829 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002830}
2831
Douglas Gregorddc29e12009-02-06 22:42:48 +00002832/// \brief Determine whether the given template parameter lists are
2833/// equivalent.
2834///
Mike Stump1eb44332009-09-09 15:08:12 +00002835/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002836/// source code as part of a new template declaration.
2837///
2838/// \param Old The old template parameter list, typically found via
2839/// name lookup of the template declared with this template parameter
2840/// list.
2841///
2842/// \param Complain If true, this routine will produce a diagnostic if
2843/// the template parameter lists are not equivalent.
2844///
Douglas Gregorfb898e12009-11-12 16:20:59 +00002845/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00002846///
2847/// \param TemplateArgLoc If this source location is valid, then we
2848/// are actually checking the template parameter list of a template
2849/// argument (New) against the template parameter list of its
2850/// corresponding template template parameter (Old). We produce
2851/// slightly different diagnostics in this scenario.
2852///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002853/// \returns True if the template parameter lists are equal, false
2854/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002855bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002856Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2857 TemplateParameterList *Old,
2858 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002859 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002860 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002861 if (Old->size() != New->size()) {
2862 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002863 unsigned NextDiag = diag::err_template_param_list_different_arity;
2864 if (TemplateArgLoc.isValid()) {
2865 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2866 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002867 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002868 Diag(New->getTemplateLoc(), NextDiag)
2869 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00002870 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002871 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002872 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002873 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002874 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2875 }
2876
2877 return false;
2878 }
2879
2880 for (TemplateParameterList::iterator OldParm = Old->begin(),
2881 OldParmEnd = Old->end(), NewParm = New->begin();
2882 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2883 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002884 if (Complain) {
2885 unsigned NextDiag = diag::err_template_param_different_kind;
2886 if (TemplateArgLoc.isValid()) {
2887 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2888 NextDiag = diag::note_template_param_different_kind;
2889 }
2890 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002891 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002892 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002893 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00002894 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002895 return false;
2896 }
2897
2898 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2899 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002900 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00002901 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002902 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2903 // The types of non-type template parameters must agree.
2904 NonTypeTemplateParmDecl *NewNTTP
2905 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00002906
2907 // If we are matching a template template argument to a template
2908 // template parameter and one of the non-type template parameter types
2909 // is dependent, then we must wait until template instantiation time
2910 // to actually compare the arguments.
2911 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2912 (OldNTTP->getType()->isDependentType() ||
2913 NewNTTP->getType()->isDependentType()))
2914 continue;
2915
Douglas Gregorddc29e12009-02-06 22:42:48 +00002916 if (Context.getCanonicalType(OldNTTP->getType()) !=
2917 Context.getCanonicalType(NewNTTP->getType())) {
2918 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002919 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2920 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002921 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002922 diag::err_template_arg_template_params_mismatch);
2923 NextDiag = diag::note_template_nontype_parm_different_type;
2924 }
2925 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002926 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00002927 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00002928 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002929 diag::note_template_nontype_parm_prev_declaration)
2930 << OldNTTP->getType();
2931 }
2932 return false;
2933 }
2934 } else {
2935 // The template parameter lists of template template
2936 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00002937 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002938 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002939 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002940 = cast<TemplateTemplateParmDecl>(*OldParm);
2941 TemplateTemplateParmDecl *NewTTP
2942 = cast<TemplateTemplateParmDecl>(*NewParm);
2943 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2944 OldTTP->getTemplateParameters(),
2945 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002946 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00002947 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002948 return false;
2949 }
2950 }
2951
2952 return true;
2953}
2954
2955/// \brief Check whether a template can be declared within this scope.
2956///
2957/// If the template declaration is valid in this scope, returns
2958/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002959bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002960Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002961 // Find the nearest enclosing declaration scope.
2962 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2963 (S->getFlags() & Scope::TemplateParamScope) != 0)
2964 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Douglas Gregorddc29e12009-02-06 22:42:48 +00002966 // C++ [temp]p2:
2967 // A template-declaration can appear only as a namespace scope or
2968 // class scope declaration.
2969 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002970 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2971 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002972 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002973 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002974
Eli Friedman1503f772009-07-31 01:43:05 +00002975 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002976 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002977
2978 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2979 return false;
2980
Mike Stump1eb44332009-09-09 15:08:12 +00002981 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00002982 diag::err_template_outside_namespace_or_class_scope)
2983 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002984}
Douglas Gregorcc636682009-02-17 23:15:12 +00002985
Douglas Gregord5cb8762009-10-07 00:13:32 +00002986/// \brief Determine what kind of template specialization the given declaration
2987/// is.
2988static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2989 if (!D)
2990 return TSK_Undeclared;
2991
Douglas Gregorf6b11852009-10-08 15:14:33 +00002992 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2993 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00002994 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2995 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002996 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2997 return Var->getTemplateSpecializationKind();
2998
Douglas Gregord5cb8762009-10-07 00:13:32 +00002999 return TSK_Undeclared;
3000}
3001
Douglas Gregor9302da62009-10-14 23:50:59 +00003002/// \brief Check whether a specialization is well-formed in the current
3003/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003004///
Douglas Gregor9302da62009-10-14 23:50:59 +00003005/// This routine determines whether a template specialization can be declared
3006/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003007///
3008/// \param S the semantic analysis object for which this check is being
3009/// performed.
3010///
3011/// \param Specialized the entity being specialized or instantiated, which
3012/// may be a kind of template (class template, function template, etc.) or
3013/// a member of a class template (member function, static data member,
3014/// member class).
3015///
3016/// \param PrevDecl the previous declaration of this entity, if any.
3017///
3018/// \param Loc the location of the explicit specialization or instantiation of
3019/// this entity.
3020///
3021/// \param IsPartialSpecialization whether this is a partial specialization of
3022/// a class template.
3023///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003024/// \returns true if there was an error that we cannot recover from, false
3025/// otherwise.
3026static bool CheckTemplateSpecializationScope(Sema &S,
3027 NamedDecl *Specialized,
3028 NamedDecl *PrevDecl,
3029 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003030 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003031 // Keep these "kind" numbers in sync with the %select statements in the
3032 // various diagnostics emitted by this routine.
3033 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003034 bool isTemplateSpecialization = false;
3035 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003036 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003037 isTemplateSpecialization = true;
3038 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003039 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003040 isTemplateSpecialization = true;
3041 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003042 EntityKind = 3;
3043 else if (isa<VarDecl>(Specialized))
3044 EntityKind = 4;
3045 else if (isa<RecordDecl>(Specialized))
3046 EntityKind = 5;
3047 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003048 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3049 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003050 return true;
3051 }
3052
Douglas Gregor88b70942009-02-25 22:02:03 +00003053 // C++ [temp.expl.spec]p2:
3054 // An explicit specialization shall be declared in the namespace
3055 // of which the template is a member, or, for member templates, in
3056 // the namespace of which the enclosing class or enclosing class
3057 // template is a member. An explicit specialization of a member
3058 // function, member class or static data member of a class
3059 // template shall be declared in the namespace of which the class
3060 // template is a member. Such a declaration may also be a
3061 // definition. If the declaration is not a definition, the
3062 // specialization may be defined later in the name- space in which
3063 // the explicit specialization was declared, or in a namespace
3064 // that encloses the one in which the explicit specialization was
3065 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003066 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3067 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003068 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003069 return true;
3070 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003071
Douglas Gregor0a407472009-10-07 17:30:37 +00003072 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3073 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003074 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003075 return true;
3076 }
3077
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003078 // C++ [temp.class.spec]p6:
3079 // A class template partial specialization may be declared or redeclared
3080 // in any namespace scope in which its definition may be defined (14.5.1
3081 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003082 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003083 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003084 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003085 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003086 if ((!PrevDecl ||
3087 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3088 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3089 // There is no prior declaration of this entity, so this
3090 // specialization must be in the same context as the template
3091 // itself.
3092 if (!DC->Equals(SpecializedContext)) {
3093 if (isa<TranslationUnitDecl>(SpecializedContext))
3094 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3095 << EntityKind << Specialized;
3096 else if (isa<NamespaceDecl>(SpecializedContext))
3097 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3098 << EntityKind << Specialized
3099 << cast<NamedDecl>(SpecializedContext);
3100
3101 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3102 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003103 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003104 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003105
3106 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003107 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003108 // Note that HandleDeclarator() performs this check for explicit
3109 // specializations of function templates, static data members, and member
3110 // functions, so we skip the check here for those kinds of entities.
3111 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003112 // Should we refactor that check, so that it occurs later?
3113 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003114 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3115 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003116 if (isa<TranslationUnitDecl>(SpecializedContext))
3117 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3118 << EntityKind << Specialized;
3119 else if (isa<NamespaceDecl>(SpecializedContext))
3120 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3121 << EntityKind << Specialized
3122 << cast<NamedDecl>(SpecializedContext);
3123
Douglas Gregor9302da62009-10-14 23:50:59 +00003124 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003125 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003126
3127 // FIXME: check for specialization-after-instantiation errors and such.
3128
Douglas Gregor88b70942009-02-25 22:02:03 +00003129 return false;
3130}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003131
Douglas Gregore94866f2009-06-12 21:21:02 +00003132/// \brief Check the non-type template arguments of a class template
3133/// partial specialization according to C++ [temp.class.spec]p9.
3134///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003135/// \param TemplateParams the template parameters of the primary class
3136/// template.
3137///
3138/// \param TemplateArg the template arguments of the class template
3139/// partial specialization.
3140///
3141/// \param MirrorsPrimaryTemplate will be set true if the class
3142/// template partial specialization arguments are identical to the
3143/// implicit template arguments of the primary template. This is not
3144/// necessarily an error (C++0x), and it is left to the caller to diagnose
3145/// this condition when it is an error.
3146///
Douglas Gregore94866f2009-06-12 21:21:02 +00003147/// \returns true if there was an error, false otherwise.
3148bool Sema::CheckClassTemplatePartialSpecializationArgs(
3149 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003150 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003151 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003152 // FIXME: the interface to this function will have to change to
3153 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003154 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003155
Anders Carlssonfb250522009-06-23 01:26:57 +00003156 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003157
Douglas Gregore94866f2009-06-12 21:21:02 +00003158 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003159 // Determine whether the template argument list of the partial
3160 // specialization is identical to the implicit argument list of
3161 // the primary template. The caller may need to diagnostic this as
3162 // an error per C++ [temp.class.spec]p9b3.
3163 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003164 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003165 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3166 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003167 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003168 MirrorsPrimaryTemplate = false;
3169 } else if (TemplateTemplateParmDecl *TTP
3170 = dyn_cast<TemplateTemplateParmDecl>(
3171 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003172 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003173 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003174 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003175 if (!ArgDecl ||
3176 ArgDecl->getIndex() != TTP->getIndex() ||
3177 ArgDecl->getDepth() != TTP->getDepth())
3178 MirrorsPrimaryTemplate = false;
3179 }
3180 }
3181
Mike Stump1eb44332009-09-09 15:08:12 +00003182 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003183 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003184 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003185 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003186 }
3187
Anders Carlsson6360be72009-06-13 18:20:51 +00003188 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003189 if (!ArgExpr) {
3190 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003191 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003192 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003193
3194 // C++ [temp.class.spec]p8:
3195 // A non-type argument is non-specialized if it is the name of a
3196 // non-type parameter. All other non-type arguments are
3197 // specialized.
3198 //
3199 // Below, we check the two conditions that only apply to
3200 // specialized non-type arguments, so skip any non-specialized
3201 // arguments.
3202 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003203 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003204 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003205 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003206 (Param->getIndex() != NTTP->getIndex() ||
3207 Param->getDepth() != NTTP->getDepth()))
3208 MirrorsPrimaryTemplate = false;
3209
Douglas Gregore94866f2009-06-12 21:21:02 +00003210 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003211 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003212
3213 // C++ [temp.class.spec]p9:
3214 // Within the argument list of a class template partial
3215 // specialization, the following restrictions apply:
3216 // -- A partially specialized non-type argument expression
3217 // shall not involve a template parameter of the partial
3218 // specialization except when the argument expression is a
3219 // simple identifier.
3220 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003221 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003222 diag::err_dependent_non_type_arg_in_partial_spec)
3223 << ArgExpr->getSourceRange();
3224 return true;
3225 }
3226
3227 // -- The type of a template parameter corresponding to a
3228 // specialized non-type argument shall not be dependent on a
3229 // parameter of the specialization.
3230 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003231 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003232 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3233 << Param->getType()
3234 << ArgExpr->getSourceRange();
3235 Diag(Param->getLocation(), diag::note_template_param_here);
3236 return true;
3237 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003238
3239 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003240 }
3241
3242 return false;
3243}
3244
Douglas Gregor212e81c2009-03-25 00:13:59 +00003245Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003246Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3247 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003248 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00003249 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003250 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003251 SourceLocation TemplateNameLoc,
3252 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003253 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003254 SourceLocation RAngleLoc,
3255 AttributeList *Attr,
3256 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003257 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003258
Douglas Gregorcc636682009-02-17 23:15:12 +00003259 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003260 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003261 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003262 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3263
3264 if (!ClassTemplate) {
3265 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3266 << (Name.getAsTemplateDecl() &&
3267 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3268 return true;
3269 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003270
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003271 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003272 bool isPartialSpecialization = false;
3273
Douglas Gregor88b70942009-02-25 22:02:03 +00003274 // Check the validity of the template headers that introduce this
3275 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003276 // FIXME: We probably shouldn't complain about these headers for
3277 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003278 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003279 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3280 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003281 TemplateParameterLists.size(),
3282 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003283 if (TemplateParams && TemplateParams->size() > 0) {
3284 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003285
Douglas Gregor05396e22009-08-25 17:23:04 +00003286 // C++ [temp.class.spec]p10:
3287 // The template parameter list of a specialization shall not
3288 // contain default template argument values.
3289 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3290 Decl *Param = TemplateParams->getParam(I);
3291 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3292 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003293 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003294 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003295 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003296 }
3297 } else if (NonTypeTemplateParmDecl *NTTP
3298 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3299 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003300 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003301 diag::err_default_arg_in_partial_spec)
3302 << DefArg->getSourceRange();
3303 NTTP->setDefaultArgument(0);
3304 DefArg->Destroy(Context);
3305 }
3306 } else {
3307 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003308 if (TTP->hasDefaultArgument()) {
3309 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003310 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003311 << TTP->getDefaultArgument().getSourceRange();
3312 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003313 }
3314 }
3315 }
Douglas Gregora735b202009-10-13 14:39:41 +00003316 } else if (TemplateParams) {
3317 if (TUK == TUK_Friend)
3318 Diag(KWLoc, diag::err_template_spec_friend)
3319 << CodeModificationHint::CreateRemoval(
3320 SourceRange(TemplateParams->getTemplateLoc(),
3321 TemplateParams->getRAngleLoc()))
3322 << SourceRange(LAngleLoc, RAngleLoc);
3323 else
3324 isExplicitSpecialization = true;
3325 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003326 Diag(KWLoc, diag::err_template_spec_needs_header)
3327 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003328 isExplicitSpecialization = true;
3329 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003330
Douglas Gregorcc636682009-02-17 23:15:12 +00003331 // Check that the specialization uses the same tag kind as the
3332 // original template.
3333 TagDecl::TagKind Kind;
3334 switch (TagSpec) {
3335 default: assert(0 && "Unknown tag type!");
3336 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3337 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3338 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3339 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003340 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003341 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003342 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003343 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003344 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003345 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003346 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003347 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003348 diag::note_previous_use);
3349 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3350 }
3351
Douglas Gregor40808ce2009-03-09 23:48:35 +00003352 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003353 TemplateArgumentListInfo TemplateArgs;
3354 TemplateArgs.setLAngleLoc(LAngleLoc);
3355 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003356 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003357
Douglas Gregorcc636682009-02-17 23:15:12 +00003358 // Check that the template argument list is well-formed for this
3359 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003360 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3361 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003362 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3363 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003364 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003365
Mike Stump1eb44332009-09-09 15:08:12 +00003366 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003367 ClassTemplate->getTemplateParameters()->size()) &&
3368 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003370 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003371 // corresponds to these arguments.
3372 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003373 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003374 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003375 if (CheckClassTemplatePartialSpecializationArgs(
3376 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003377 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003378 return true;
3379
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003380 if (MirrorsPrimaryTemplate) {
3381 // C++ [temp.class.spec]p9b3:
3382 //
Mike Stump1eb44332009-09-09 15:08:12 +00003383 // -- The argument list of the specialization shall not be identical
3384 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003385 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003386 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003387 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003388 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003389 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003390 ClassTemplate->getIdentifier(),
3391 TemplateNameLoc,
3392 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003393 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003394 AS_none);
3395 }
3396
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003397 // FIXME: Diagnose friend partial specializations
3398
Douglas Gregorde090962010-02-09 00:37:32 +00003399 if (!Name.isDependent() &&
3400 !TemplateSpecializationType::anyDependentTemplateArguments(
3401 TemplateArgs.getArgumentArray(),
3402 TemplateArgs.size())) {
3403 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3404 << ClassTemplate->getDeclName();
3405 isPartialSpecialization = false;
3406 } else {
3407 // FIXME: Template parameter list matters, too
3408 ClassTemplatePartialSpecializationDecl::Profile(ID,
3409 Converted.getFlatArguments(),
3410 Converted.flatSize(),
3411 Context);
3412 }
3413 }
3414
3415 if (!isPartialSpecialization)
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003416 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003417 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003418 Converted.flatSize(),
3419 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003420 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003421 ClassTemplateSpecializationDecl *PrevDecl = 0;
3422
3423 if (isPartialSpecialization)
3424 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003425 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003426 InsertPos);
3427 else
3428 PrevDecl
3429 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003430
3431 ClassTemplateSpecializationDecl *Specialization = 0;
3432
Douglas Gregor88b70942009-02-25 22:02:03 +00003433 // Check whether we can declare a class template specialization in
3434 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003435 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003436 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003437 TemplateNameLoc,
3438 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003439 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003440
Douglas Gregorb88e8882009-07-30 17:40:51 +00003441 // The canonical type
3442 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003443 if (PrevDecl &&
3444 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003445 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003446 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003447 // arguments was referenced but not declared, or we're only
3448 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003449 // declaration node as our own, updating its source location to
3450 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003451 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003452 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003453 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003454 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003455 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003456 // Build the canonical type that describes the converted template
3457 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003458 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3459 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003460 Converted.getFlatArguments(),
3461 Converted.flatSize());
3462
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003463 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003464 ClassTemplatePartialSpecializationDecl *PrevPartial
3465 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003466 ClassTemplatePartialSpecializationDecl *Partial
3467 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003468 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003469 TemplateNameLoc,
3470 TemplateParams,
3471 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003472 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003473 TemplateArgs,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003474 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003475
3476 if (PrevPartial) {
3477 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3478 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3479 } else {
3480 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3481 }
3482 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003483
Douglas Gregored9c0f92009-10-29 00:04:11 +00003484 // If we are providing an explicit specialization of a member class
3485 // template specialization, make a note of that.
3486 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3487 PrevPartial->setMemberSpecialization();
3488
Douglas Gregor031a5882009-06-13 00:26:55 +00003489 // Check that all of the template parameters of the class template
3490 // partial specialization are deducible from the template
3491 // arguments. If not, this class template partial specialization
3492 // will never be used.
3493 llvm::SmallVector<bool, 8> DeducibleParams;
3494 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003495 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003496 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003497 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003498 unsigned NumNonDeducible = 0;
3499 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3500 if (!DeducibleParams[I])
3501 ++NumNonDeducible;
3502
3503 if (NumNonDeducible) {
3504 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3505 << (NumNonDeducible > 1)
3506 << SourceRange(TemplateNameLoc, RAngleLoc);
3507 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3508 if (!DeducibleParams[I]) {
3509 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3510 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003511 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003512 diag::note_partial_spec_unused_parameter)
3513 << Param->getDeclName();
3514 else
Mike Stump1eb44332009-09-09 15:08:12 +00003515 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003516 diag::note_partial_spec_unused_parameter)
3517 << std::string("<anonymous>");
3518 }
3519 }
3520 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003521 } else {
3522 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003523 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003524 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003525 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003526 ClassTemplate->getDeclContext(),
3527 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003528 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003529 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003530 PrevDecl);
3531
3532 if (PrevDecl) {
3533 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3534 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3535 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003536 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003537 InsertPos);
3538 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003539
3540 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003541 }
3542
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003543 // C++ [temp.expl.spec]p6:
3544 // If a template, a member template or the member of a class template is
3545 // explicitly specialized then that specialization shall be declared
3546 // before the first use of that specialization that would cause an implicit
3547 // instantiation to take place, in every translation unit in which such a
3548 // use occurs; no diagnostic is required.
3549 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3550 SourceRange Range(TemplateNameLoc, RAngleLoc);
3551 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3552 << Context.getTypeDeclType(Specialization) << Range;
3553
3554 Diag(PrevDecl->getPointOfInstantiation(),
3555 diag::note_instantiation_required_here)
3556 << (PrevDecl->getTemplateSpecializationKind()
3557 != TSK_ImplicitInstantiation);
3558 return true;
3559 }
3560
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003561 // If this is not a friend, note that this is an explicit specialization.
3562 if (TUK != TUK_Friend)
3563 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003564
3565 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003566 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003567 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003568 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003569 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003570 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003571 Diag(Def->getLocation(), diag::note_previous_definition);
3572 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003573 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003574 }
3575 }
3576
Douglas Gregorfc705b82009-02-26 22:19:44 +00003577 // Build the fully-sugared type for this class template
3578 // specialization as the user wrote in the specialization
3579 // itself. This means that we'll pretty-print the type retrieved
3580 // from the specialization's declaration the way that the user
3581 // actually wrote the specialization, rather than formatting the
3582 // name based on the "canonical" representation used to store the
3583 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003584 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00003585 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003586 if (TUK != TUK_Friend)
3587 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003588 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003589
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003590 // C++ [temp.expl.spec]p9:
3591 // A template explicit specialization is in the scope of the
3592 // namespace in which the template was defined.
3593 //
3594 // We actually implement this paragraph where we set the semantic
3595 // context (in the creation of the ClassTemplateSpecializationDecl),
3596 // but we also maintain the lexical context where the actual
3597 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003598 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003599
Douglas Gregorcc636682009-02-17 23:15:12 +00003600 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003601 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003602 Specialization->startDefinition();
3603
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003604 if (TUK == TUK_Friend) {
3605 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3606 TemplateNameLoc,
3607 WrittenTy.getTypePtr(),
3608 /*FIXME:*/KWLoc);
3609 Friend->setAccess(AS_public);
3610 CurContext->addDecl(Friend);
3611 } else {
3612 // Add the specialization into its lexical context, so that it can
3613 // be seen when iterating through the list of declarations in that
3614 // context. However, specializations are not found by name lookup.
3615 CurContext->addDecl(Specialization);
3616 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003617 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003618}
Douglas Gregord57959a2009-03-27 23:10:48 +00003619
Mike Stump1eb44332009-09-09 15:08:12 +00003620Sema::DeclPtrTy
3621Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003622 MultiTemplateParamsArg TemplateParameterLists,
3623 Declarator &D) {
3624 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3625}
3626
Mike Stump1eb44332009-09-09 15:08:12 +00003627Sema::DeclPtrTy
3628Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003629 MultiTemplateParamsArg TemplateParameterLists,
3630 Declarator &D) {
3631 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3632 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3633 "Not a function declarator!");
3634 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003635
Douglas Gregor52591bf2009-06-24 00:54:41 +00003636 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003637 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003638 }
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Douglas Gregor52591bf2009-06-24 00:54:41 +00003640 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003641
3642 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003643 move(TemplateParameterLists),
3644 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003645 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003646 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003647 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003648 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003649 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3650 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003651 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003652}
3653
John McCall75042392010-02-11 01:33:53 +00003654/// \brief Strips various properties off an implicit instantiation
3655/// that has just been explicitly specialized.
3656static void StripImplicitInstantiation(NamedDecl *D) {
3657 D->invalidateAttrs();
3658
3659 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3660 FD->setInlineSpecified(false);
3661 }
3662}
3663
Douglas Gregor454885e2009-10-15 15:54:05 +00003664/// \brief Diagnose cases where we have an explicit template specialization
3665/// before/after an explicit template instantiation, producing diagnostics
3666/// for those cases where they are required and determining whether the
3667/// new specialization/instantiation will have any effect.
3668///
Douglas Gregor454885e2009-10-15 15:54:05 +00003669/// \param NewLoc the location of the new explicit specialization or
3670/// instantiation.
3671///
3672/// \param NewTSK the kind of the new explicit specialization or instantiation.
3673///
3674/// \param PrevDecl the previous declaration of the entity.
3675///
3676/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3677///
3678/// \param PrevPointOfInstantiation if valid, indicates where the previus
3679/// declaration was instantiated (either implicitly or explicitly).
3680///
3681/// \param SuppressNew will be set to true to indicate that the new
3682/// specialization or instantiation has no effect and should be ignored.
3683///
3684/// \returns true if there was an error that should prevent the introduction of
3685/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003686bool
3687Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3688 TemplateSpecializationKind NewTSK,
3689 NamedDecl *PrevDecl,
3690 TemplateSpecializationKind PrevTSK,
3691 SourceLocation PrevPointOfInstantiation,
3692 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003693 SuppressNew = false;
3694
3695 switch (NewTSK) {
3696 case TSK_Undeclared:
3697 case TSK_ImplicitInstantiation:
3698 assert(false && "Don't check implicit instantiations here");
3699 return false;
3700
3701 case TSK_ExplicitSpecialization:
3702 switch (PrevTSK) {
3703 case TSK_Undeclared:
3704 case TSK_ExplicitSpecialization:
3705 // Okay, we're just specializing something that is either already
3706 // explicitly specialized or has merely been mentioned without any
3707 // instantiation.
3708 return false;
3709
3710 case TSK_ImplicitInstantiation:
3711 if (PrevPointOfInstantiation.isInvalid()) {
3712 // The declaration itself has not actually been instantiated, so it is
3713 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00003714 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00003715 return false;
3716 }
3717 // Fall through
3718
3719 case TSK_ExplicitInstantiationDeclaration:
3720 case TSK_ExplicitInstantiationDefinition:
3721 assert((PrevTSK == TSK_ImplicitInstantiation ||
3722 PrevPointOfInstantiation.isValid()) &&
3723 "Explicit instantiation without point of instantiation?");
3724
3725 // C++ [temp.expl.spec]p6:
3726 // If a template, a member template or the member of a class template
3727 // is explicitly specialized then that specialization shall be declared
3728 // before the first use of that specialization that would cause an
3729 // implicit instantiation to take place, in every translation unit in
3730 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003731 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003732 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003733 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003734 << (PrevTSK != TSK_ImplicitInstantiation);
3735
3736 return true;
3737 }
3738 break;
3739
3740 case TSK_ExplicitInstantiationDeclaration:
3741 switch (PrevTSK) {
3742 case TSK_ExplicitInstantiationDeclaration:
3743 // This explicit instantiation declaration is redundant (that's okay).
3744 SuppressNew = true;
3745 return false;
3746
3747 case TSK_Undeclared:
3748 case TSK_ImplicitInstantiation:
3749 // We're explicitly instantiating something that may have already been
3750 // implicitly instantiated; that's fine.
3751 return false;
3752
3753 case TSK_ExplicitSpecialization:
3754 // C++0x [temp.explicit]p4:
3755 // For a given set of template parameters, if an explicit instantiation
3756 // of a template appears after a declaration of an explicit
3757 // specialization for that template, the explicit instantiation has no
3758 // effect.
3759 return false;
3760
3761 case TSK_ExplicitInstantiationDefinition:
3762 // C++0x [temp.explicit]p10:
3763 // If an entity is the subject of both an explicit instantiation
3764 // declaration and an explicit instantiation definition in the same
3765 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003766 Diag(NewLoc,
3767 diag::err_explicit_instantiation_declaration_after_definition);
3768 Diag(PrevPointOfInstantiation,
3769 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003770 assert(PrevPointOfInstantiation.isValid() &&
3771 "Explicit instantiation without point of instantiation?");
3772 SuppressNew = true;
3773 return false;
3774 }
3775 break;
3776
3777 case TSK_ExplicitInstantiationDefinition:
3778 switch (PrevTSK) {
3779 case TSK_Undeclared:
3780 case TSK_ImplicitInstantiation:
3781 // We're explicitly instantiating something that may have already been
3782 // implicitly instantiated; that's fine.
3783 return false;
3784
3785 case TSK_ExplicitSpecialization:
3786 // C++ DR 259, C++0x [temp.explicit]p4:
3787 // For a given set of template parameters, if an explicit
3788 // instantiation of a template appears after a declaration of
3789 // an explicit specialization for that template, the explicit
3790 // instantiation has no effect.
3791 //
3792 // In C++98/03 mode, we only give an extension warning here, because it
3793 // is not not harmful to try to explicitly instantiate something that
3794 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003795 if (!getLangOptions().CPlusPlus0x) {
3796 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003797 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003798 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003799 diag::note_previous_template_specialization);
3800 }
3801 SuppressNew = true;
3802 return false;
3803
3804 case TSK_ExplicitInstantiationDeclaration:
3805 // We're explicity instantiating a definition for something for which we
3806 // were previously asked to suppress instantiations. That's fine.
3807 return false;
3808
3809 case TSK_ExplicitInstantiationDefinition:
3810 // C++0x [temp.spec]p5:
3811 // For a given template and a given set of template-arguments,
3812 // - an explicit instantiation definition shall appear at most once
3813 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003814 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003815 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003816 Diag(PrevPointOfInstantiation,
3817 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003818 SuppressNew = true;
3819 return false;
3820 }
3821 break;
3822 }
3823
3824 assert(false && "Missing specialization/instantiation case?");
3825
3826 return false;
3827}
3828
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003829/// \brief Perform semantic analysis for the given function template
3830/// specialization.
3831///
3832/// This routine performs all of the semantic analysis required for an
3833/// explicit function template specialization. On successful completion,
3834/// the function declaration \p FD will become a function template
3835/// specialization.
3836///
3837/// \param FD the function declaration, which will be updated to become a
3838/// function template specialization.
3839///
3840/// \param HasExplicitTemplateArgs whether any template arguments were
3841/// explicitly provided.
3842///
3843/// \param LAngleLoc the location of the left angle bracket ('<'), if
3844/// template arguments were explicitly provided.
3845///
3846/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3847/// if any.
3848///
3849/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3850/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3851/// true as in, e.g., \c void sort<>(char*, char*);
3852///
3853/// \param RAngleLoc the location of the right angle bracket ('>'), if
3854/// template arguments were explicitly provided.
3855///
3856/// \param PrevDecl the set of declarations that
3857bool
3858Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00003859 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00003860 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003861 // The set of function template specializations that could match this
3862 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00003863 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003864
3865 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00003866 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3867 I != E; ++I) {
3868 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3869 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003870 // Only consider templates found within the same semantic lookup scope as
3871 // FD.
3872 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3873 continue;
3874
3875 // C++ [temp.expl.spec]p11:
3876 // A trailing template-argument can be left unspecified in the
3877 // template-id naming an explicit function template specialization
3878 // provided it can be deduced from the function argument type.
3879 // Perform template argument deduction to determine whether we may be
3880 // specializing this template.
3881 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00003882 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003883 FunctionDecl *Specialization = 0;
3884 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00003885 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003886 FD->getType(),
3887 Specialization,
3888 Info)) {
3889 // FIXME: Template argument deduction failed; record why it failed, so
3890 // that we can provide nifty diagnostics.
3891 (void)TDK;
3892 continue;
3893 }
3894
3895 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00003896 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003897 }
3898 }
3899
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003900 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00003901 UnresolvedSetIterator Result
3902 = getMostSpecialized(Candidates.begin(), Candidates.end(),
3903 TPOC_Other, FD->getLocation(),
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003904 PartialDiagnostic(diag::err_function_template_spec_no_match)
3905 << FD->getDeclName(),
3906 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00003907 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003908 PartialDiagnostic(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00003909 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003910 return true;
John McCallc373d482010-01-27 01:50:18 +00003911
3912 // Ignore access information; it doesn't figure into redeclaration checking.
3913 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003914
3915 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003916 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003917
Douglas Gregord5cb8762009-10-07 00:13:32 +00003918 // Check the scope of this explicit specialization.
3919 if (CheckTemplateSpecializationScope(*this,
3920 Specialization->getPrimaryTemplate(),
3921 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003922 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003923 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003924
3925 // C++ [temp.expl.spec]p6:
3926 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003927 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003928 // before the first use of that specialization that would cause an implicit
3929 // instantiation to take place, in every translation unit in which such a
3930 // use occurs; no diagnostic is required.
3931 FunctionTemplateSpecializationInfo *SpecInfo
3932 = Specialization->getTemplateSpecializationInfo();
3933 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00003934
3935 bool SuppressNew = false;
3936 if (CheckSpecializationInstantiationRedecl(FD->getLocation(),
3937 TSK_ExplicitSpecialization,
3938 Specialization,
3939 SpecInfo->getTemplateSpecializationKind(),
3940 SpecInfo->getPointOfInstantiation(),
3941 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003942 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00003943
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003944 // Mark the prior declaration as an explicit specialization, so that later
3945 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003946 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003947
3948 // Turn the given function declaration into a function template
3949 // specialization, with the template arguments from the previous
3950 // specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00003951 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003952 new (Context) TemplateArgumentList(
3953 *Specialization->getTemplateSpecializationArgs()),
3954 /*InsertPos=*/0,
3955 TSK_ExplicitSpecialization);
3956
3957 // The "previous declaration" for this function template specialization is
3958 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00003959 Previous.clear();
3960 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003961 return false;
3962}
3963
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003964/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003965/// specialization.
3966///
3967/// This routine performs all of the semantic analysis required for an
3968/// explicit member function specialization. On successful completion,
3969/// the function declaration \p FD will become a member function
3970/// specialization.
3971///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003972/// \param Member the member declaration, which will be updated to become a
3973/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003974///
John McCall68263142009-11-18 22:49:29 +00003975/// \param Previous the set of declarations, one of which may be specialized
3976/// by this function specialization; the set will be modified to contain the
3977/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003978bool
John McCall68263142009-11-18 22:49:29 +00003979Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003980 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3981
3982 // Try to find the member we are instantiating.
3983 NamedDecl *Instantiation = 0;
3984 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003985 MemberSpecializationInfo *MSInfo = 0;
3986
John McCall68263142009-11-18 22:49:29 +00003987 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003988 // Nowhere to look anyway.
3989 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003990 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3991 I != E; ++I) {
3992 NamedDecl *D = (*I)->getUnderlyingDecl();
3993 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003994 if (Context.hasSameType(Function->getType(), Method->getType())) {
3995 Instantiation = Method;
3996 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003997 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003998 break;
3999 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004000 }
4001 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004002 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004003 VarDecl *PrevVar;
4004 if (Previous.isSingleResult() &&
4005 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004006 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004007 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004008 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004009 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004010 }
4011 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004012 CXXRecordDecl *PrevRecord;
4013 if (Previous.isSingleResult() &&
4014 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4015 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004016 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004017 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004018 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004019 }
4020
4021 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004022 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004023 // specializations are always out-of-line, the caller will complain about
4024 // this mismatch later.
4025 return false;
4026 }
4027
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004028 // Make sure that this is a specialization of a member.
4029 if (!InstantiatedFrom) {
4030 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4031 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004032 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4033 return true;
4034 }
4035
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004036 // C++ [temp.expl.spec]p6:
4037 // If a template, a member template or the member of a class template is
4038 // explicitly specialized then that spe- cialization shall be declared
4039 // before the first use of that specialization that would cause an implicit
4040 // instantiation to take place, in every translation unit in which such a
4041 // use occurs; no diagnostic is required.
4042 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004043
4044 bool SuppressNew = false;
4045 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4046 TSK_ExplicitSpecialization,
4047 Instantiation,
4048 MSInfo->getTemplateSpecializationKind(),
4049 MSInfo->getPointOfInstantiation(),
4050 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004051 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004052
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004053 // Check the scope of this explicit specialization.
4054 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004055 InstantiatedFrom,
4056 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004057 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004058 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004059
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004060 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004061 // the original declaration to note that it is an explicit specialization
4062 // (if it was previously an implicit instantiation). This latter step
4063 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004064 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004065 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4066 if (InstantiationFunction->getTemplateSpecializationKind() ==
4067 TSK_ImplicitInstantiation) {
4068 InstantiationFunction->setTemplateSpecializationKind(
4069 TSK_ExplicitSpecialization);
4070 InstantiationFunction->setLocation(Member->getLocation());
4071 }
4072
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004073 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4074 cast<CXXMethodDecl>(InstantiatedFrom),
4075 TSK_ExplicitSpecialization);
4076 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004077 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4078 if (InstantiationVar->getTemplateSpecializationKind() ==
4079 TSK_ImplicitInstantiation) {
4080 InstantiationVar->setTemplateSpecializationKind(
4081 TSK_ExplicitSpecialization);
4082 InstantiationVar->setLocation(Member->getLocation());
4083 }
4084
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004085 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4086 cast<VarDecl>(InstantiatedFrom),
4087 TSK_ExplicitSpecialization);
4088 } else {
4089 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004090 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4091 if (InstantiationClass->getTemplateSpecializationKind() ==
4092 TSK_ImplicitInstantiation) {
4093 InstantiationClass->setTemplateSpecializationKind(
4094 TSK_ExplicitSpecialization);
4095 InstantiationClass->setLocation(Member->getLocation());
4096 }
4097
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004098 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004099 cast<CXXRecordDecl>(InstantiatedFrom),
4100 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004101 }
4102
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004103 // Save the caller the trouble of having to figure out which declaration
4104 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004105 Previous.clear();
4106 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004107 return false;
4108}
4109
Douglas Gregor558c0322009-10-14 23:41:34 +00004110/// \brief Check the scope of an explicit instantiation.
4111static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4112 SourceLocation InstLoc,
4113 bool WasQualifiedName) {
4114 DeclContext *ExpectedContext
4115 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4116 DeclContext *CurContext = S.CurContext->getLookupContext();
4117
4118 // C++0x [temp.explicit]p2:
4119 // An explicit instantiation shall appear in an enclosing namespace of its
4120 // template.
4121 //
4122 // This is DR275, which we do not retroactively apply to C++98/03.
4123 if (S.getLangOptions().CPlusPlus0x &&
4124 !CurContext->Encloses(ExpectedContext)) {
4125 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4126 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4127 << D << NS;
4128 else
4129 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4130 << D;
4131 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4132 return;
4133 }
4134
4135 // C++0x [temp.explicit]p2:
4136 // If the name declared in the explicit instantiation is an unqualified
4137 // name, the explicit instantiation shall appear in the namespace where
4138 // its template is declared or, if that namespace is inline (7.3.1), any
4139 // namespace from its enclosing namespace set.
4140 if (WasQualifiedName)
4141 return;
4142
4143 if (CurContext->Equals(ExpectedContext))
4144 return;
4145
4146 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4147 << D << ExpectedContext;
4148 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4149}
4150
4151/// \brief Determine whether the given scope specifier has a template-id in it.
4152static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4153 if (!SS.isSet())
4154 return false;
4155
4156 // C++0x [temp.explicit]p2:
4157 // If the explicit instantiation is for a member function, a member class
4158 // or a static data member of a class template specialization, the name of
4159 // the class template specialization in the qualified-id for the member
4160 // name shall be a simple-template-id.
4161 //
4162 // C++98 has the same restriction, just worded differently.
4163 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4164 NNS; NNS = NNS->getPrefix())
4165 if (Type *T = NNS->getAsType())
4166 if (isa<TemplateSpecializationType>(T))
4167 return true;
4168
4169 return false;
4170}
4171
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004172// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00004173// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004174Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004175Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004176 SourceLocation ExternLoc,
4177 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004178 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004179 SourceLocation KWLoc,
4180 const CXXScopeSpec &SS,
4181 TemplateTy TemplateD,
4182 SourceLocation TemplateNameLoc,
4183 SourceLocation LAngleLoc,
4184 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004185 SourceLocation RAngleLoc,
4186 AttributeList *Attr) {
4187 // Find the class template we're specializing
4188 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004189 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004190 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4191
4192 // Check that the specialization uses the same tag kind as the
4193 // original template.
4194 TagDecl::TagKind Kind;
4195 switch (TagSpec) {
4196 default: assert(0 && "Unknown tag type!");
4197 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4198 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4199 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4200 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004201 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004202 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004203 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004204 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004205 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00004206 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004207 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004208 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004209 diag::note_previous_use);
4210 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4211 }
4212
Douglas Gregor558c0322009-10-14 23:41:34 +00004213 // C++0x [temp.explicit]p2:
4214 // There are two forms of explicit instantiation: an explicit instantiation
4215 // definition and an explicit instantiation declaration. An explicit
4216 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004217 TemplateSpecializationKind TSK
4218 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4219 : TSK_ExplicitInstantiationDeclaration;
4220
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004221 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004222 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004223 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004224
4225 // Check that the template argument list is well-formed for this
4226 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004227 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4228 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004229 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4230 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004231 return true;
4232
Mike Stump1eb44332009-09-09 15:08:12 +00004233 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004234 ClassTemplate->getTemplateParameters()->size()) &&
4235 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004236
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004237 // Find the class template specialization declaration that
4238 // corresponds to these arguments.
4239 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004240 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004241 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004242 Converted.flatSize(),
4243 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004244 void *InsertPos = 0;
4245 ClassTemplateSpecializationDecl *PrevDecl
4246 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4247
Douglas Gregord5cb8762009-10-07 00:13:32 +00004248 // C++0x [temp.explicit]p2:
4249 // [...] An explicit instantiation shall appear in an enclosing
4250 // namespace of its template. [...]
4251 //
4252 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004253 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4254 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004255
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004256 ClassTemplateSpecializationDecl *Specialization = 0;
4257
Douglas Gregord78f5982009-11-25 06:01:46 +00004258 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004259 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004260 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004261 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004262 PrevDecl,
4263 PrevDecl->getSpecializationKind(),
4264 PrevDecl->getPointOfInstantiation(),
4265 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004266 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004267
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004268 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004269 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004270
Douglas Gregor52604ab2009-09-11 21:19:12 +00004271 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4272 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4273 // Since the only prior class template specialization with these
4274 // arguments was referenced but not declared, reuse that
4275 // declaration node as our own, updating its source location to
4276 // reflect our new declaration.
4277 Specialization = PrevDecl;
4278 Specialization->setLocation(TemplateNameLoc);
4279 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004280 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004281 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004282 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004283
4284 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004285 // Create a new class template specialization declaration node for
4286 // this explicit specialization.
4287 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00004288 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004289 ClassTemplate->getDeclContext(),
4290 TemplateNameLoc,
4291 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004292 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004293
Douglas Gregor52604ab2009-09-11 21:19:12 +00004294 if (PrevDecl) {
4295 // Remove the previous declaration from the folding set, since we want
4296 // to introduce a new declaration.
4297 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4298 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4299 }
4300
4301 // Insert the new specialization.
4302 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004303 }
4304
4305 // Build the fully-sugared type for this explicit instantiation as
4306 // the user wrote in the explicit instantiation itself. This means
4307 // that we'll pretty-print the type retrieved from the
4308 // specialization's declaration the way that the user actually wrote
4309 // the explicit instantiation, rather than formatting the name based
4310 // on the "canonical" representation used to store the template
4311 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004312 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00004313 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004314 Context.getTypeDeclType(Specialization));
4315 Specialization->setTypeAsWritten(WrittenTy);
4316 TemplateArgsIn.release();
4317
Douglas Gregord78f5982009-11-25 06:01:46 +00004318 if (!ReusedDecl) {
4319 // Add the explicit instantiation into its lexical context. However,
4320 // since explicit instantiations are never found by name lookup, we
4321 // just put it into the declaration context directly.
4322 Specialization->setLexicalDeclContext(CurContext);
4323 CurContext->addDecl(Specialization);
4324 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004325
4326 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004327 // A definition of a class template or class member template
4328 // shall be in scope at the point of the explicit instantiation of
4329 // the class template or class member template.
4330 //
4331 // This check comes when we actually try to perform the
4332 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004333 ClassTemplateSpecializationDecl *Def
4334 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004335 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004336 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004337 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004338
4339 // Instantiate the members of this class template specialization.
4340 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004341 Specialization->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004342 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004343 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004344
4345 return DeclPtrTy::make(Specialization);
4346}
4347
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004348// Explicit instantiation of a member class of a class template.
4349Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004350Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004351 SourceLocation ExternLoc,
4352 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004353 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004354 SourceLocation KWLoc,
4355 const CXXScopeSpec &SS,
4356 IdentifierInfo *Name,
4357 SourceLocation NameLoc,
4358 AttributeList *Attr) {
4359
Douglas Gregor402abb52009-05-28 23:31:59 +00004360 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004361 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004362 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004363 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004364 MultiTemplateParamsArg(*this, 0, 0),
4365 Owned, IsDependent);
4366 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4367
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004368 if (!TagD)
4369 return true;
4370
4371 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4372 if (Tag->isEnum()) {
4373 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4374 << Context.getTypeDeclType(Tag);
4375 return true;
4376 }
4377
Douglas Gregord0c87372009-05-27 17:30:49 +00004378 if (Tag->isInvalidDecl())
4379 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004380
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004381 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4382 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4383 if (!Pattern) {
4384 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4385 << Context.getTypeDeclType(Record);
4386 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4387 return true;
4388 }
4389
Douglas Gregor558c0322009-10-14 23:41:34 +00004390 // C++0x [temp.explicit]p2:
4391 // If the explicit instantiation is for a class or member class, the
4392 // elaborated-type-specifier in the declaration shall include a
4393 // simple-template-id.
4394 //
4395 // C++98 has the same restriction, just worded differently.
4396 if (!ScopeSpecifierHasTemplateId(SS))
4397 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4398 << Record << SS.getRange();
4399
4400 // C++0x [temp.explicit]p2:
4401 // There are two forms of explicit instantiation: an explicit instantiation
4402 // definition and an explicit instantiation declaration. An explicit
4403 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004404 TemplateSpecializationKind TSK
4405 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4406 : TSK_ExplicitInstantiationDeclaration;
4407
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004408 // C++0x [temp.explicit]p2:
4409 // [...] An explicit instantiation shall appear in an enclosing
4410 // namespace of its template. [...]
4411 //
4412 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004413 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004414
4415 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004416 CXXRecordDecl *PrevDecl
4417 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004418 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004419 PrevDecl = Record;
4420 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004421 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4422 bool SuppressNew = false;
4423 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004424 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004425 PrevDecl,
4426 MSInfo->getTemplateSpecializationKind(),
4427 MSInfo->getPointOfInstantiation(),
4428 SuppressNew))
4429 return true;
4430 if (SuppressNew)
4431 return TagD;
4432 }
4433
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004434 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004435 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004436 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004437 // C++ [temp.explicit]p3:
4438 // A definition of a member class of a class template shall be in scope
4439 // at the point of an explicit instantiation of the member class.
4440 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004441 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004442 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004443 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4444 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004445 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4446 << Pattern;
4447 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004448 } else {
4449 if (InstantiateClass(NameLoc, Record, Def,
4450 getTemplateInstantiationArgs(Record),
4451 TSK))
4452 return true;
4453
Douglas Gregor952b0172010-02-11 01:04:33 +00004454 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004455 if (!RecordDef)
4456 return true;
4457 }
4458 }
4459
4460 // Instantiate all of the members of the class.
4461 InstantiateClassMembers(NameLoc, RecordDef,
4462 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004463
Mike Stump390b4cc2009-05-16 07:39:55 +00004464 // FIXME: We don't have any representation for explicit instantiations of
4465 // member classes. Such a representation is not needed for compilation, but it
4466 // should be available for clients that want to see all of the declarations in
4467 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004468 return TagD;
4469}
4470
Douglas Gregord5a423b2009-09-25 18:43:00 +00004471Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4472 SourceLocation ExternLoc,
4473 SourceLocation TemplateLoc,
4474 Declarator &D) {
4475 // Explicit instantiations always require a name.
4476 DeclarationName Name = GetNameForDeclarator(D);
4477 if (!Name) {
4478 if (!D.isInvalidType())
4479 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4480 diag::err_explicit_instantiation_requires_name)
4481 << D.getDeclSpec().getSourceRange()
4482 << D.getSourceRange();
4483
4484 return true;
4485 }
4486
4487 // The scope passed in may not be a decl scope. Zip up the scope tree until
4488 // we find one that is.
4489 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4490 (S->getFlags() & Scope::TemplateParamScope) != 0)
4491 S = S->getParent();
4492
4493 // Determine the type of the declaration.
4494 QualType R = GetTypeForDeclarator(D, S, 0);
4495 if (R.isNull())
4496 return true;
4497
4498 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4499 // Cannot explicitly instantiate a typedef.
4500 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4501 << Name;
4502 return true;
4503 }
4504
Douglas Gregor663b5a02009-10-14 20:14:33 +00004505 // C++0x [temp.explicit]p1:
4506 // [...] An explicit instantiation of a function template shall not use the
4507 // inline or constexpr specifiers.
4508 // Presumably, this also applies to member functions of class templates as
4509 // well.
4510 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4511 Diag(D.getDeclSpec().getInlineSpecLoc(),
4512 diag::err_explicit_instantiation_inline)
Chris Lattner29d9c1a2009-12-06 17:36:05 +00004513 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004514
4515 // FIXME: check for constexpr specifier.
4516
Douglas Gregor558c0322009-10-14 23:41:34 +00004517 // C++0x [temp.explicit]p2:
4518 // There are two forms of explicit instantiation: an explicit instantiation
4519 // definition and an explicit instantiation declaration. An explicit
4520 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004521 TemplateSpecializationKind TSK
4522 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4523 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004524
John McCalla24dc2e2009-11-17 02:14:36 +00004525 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4526 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004527
4528 if (!R->isFunctionType()) {
4529 // C++ [temp.explicit]p1:
4530 // A [...] static data member of a class template can be explicitly
4531 // instantiated from the member definition associated with its class
4532 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004533 if (Previous.isAmbiguous())
4534 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004535
John McCall1bcee0a2009-12-02 08:25:40 +00004536 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004537 if (!Prev || !Prev->isStaticDataMember()) {
4538 // We expect to see a data data member here.
4539 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4540 << Name;
4541 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4542 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004543 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004544 return true;
4545 }
4546
4547 if (!Prev->getInstantiatedFromStaticDataMember()) {
4548 // FIXME: Check for explicit specialization?
4549 Diag(D.getIdentifierLoc(),
4550 diag::err_explicit_instantiation_data_member_not_instantiated)
4551 << Prev;
4552 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4553 // FIXME: Can we provide a note showing where this was declared?
4554 return true;
4555 }
4556
Douglas Gregor558c0322009-10-14 23:41:34 +00004557 // C++0x [temp.explicit]p2:
4558 // If the explicit instantiation is for a member function, a member class
4559 // or a static data member of a class template specialization, the name of
4560 // the class template specialization in the qualified-id for the member
4561 // name shall be a simple-template-id.
4562 //
4563 // C++98 has the same restriction, just worded differently.
4564 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4565 Diag(D.getIdentifierLoc(),
4566 diag::err_explicit_instantiation_without_qualified_id)
4567 << Prev << D.getCXXScopeSpec().getRange();
4568
4569 // Check the scope of this explicit instantiation.
4570 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4571
Douglas Gregor454885e2009-10-15 15:54:05 +00004572 // Verify that it is okay to explicitly instantiate here.
4573 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4574 assert(MSInfo && "Missing static data member specialization info?");
4575 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004576 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004577 MSInfo->getTemplateSpecializationKind(),
4578 MSInfo->getPointOfInstantiation(),
4579 SuppressNew))
4580 return true;
4581 if (SuppressNew)
4582 return DeclPtrTy();
4583
Douglas Gregord5a423b2009-09-25 18:43:00 +00004584 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004585 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004586 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004587 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4588 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004589
4590 // FIXME: Create an ExplicitInstantiation node?
4591 return DeclPtrTy();
4592 }
4593
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004594 // If the declarator is a template-id, translate the parser's template
4595 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004596 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004597 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004598 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4599 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00004600 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4601 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00004602 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4603 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004604 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00004605 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00004606 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004607 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004608 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004609
Douglas Gregord5a423b2009-09-25 18:43:00 +00004610 // C++ [temp.explicit]p1:
4611 // A [...] function [...] can be explicitly instantiated from its template.
4612 // A member function [...] of a class template can be explicitly
4613 // instantiated from the member definition associated with its class
4614 // template.
John McCallc373d482010-01-27 01:50:18 +00004615 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004616 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4617 P != PEnd; ++P) {
4618 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004619 if (!HasExplicitTemplateArgs) {
4620 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4621 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4622 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00004623
John McCallc373d482010-01-27 01:50:18 +00004624 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00004625 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4626 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00004627 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004628 }
4629 }
4630
4631 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4632 if (!FunTmpl)
4633 continue;
4634
John McCall5769d612010-02-08 23:07:23 +00004635 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004636 FunctionDecl *Specialization = 0;
4637 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00004638 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00004639 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004640 R, Specialization, Info)) {
4641 // FIXME: Keep track of almost-matches?
4642 (void)TDK;
4643 continue;
4644 }
4645
John McCallc373d482010-01-27 01:50:18 +00004646 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004647 }
4648
4649 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004650 UnresolvedSetIterator Result
4651 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00004652 D.getIdentifierLoc(),
4653 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4654 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4655 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4656
John McCallc373d482010-01-27 01:50:18 +00004657 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00004658 return true;
John McCallc373d482010-01-27 01:50:18 +00004659
4660 // Ignore access control bits, we don't need them for redeclaration checking.
4661 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004662
Douglas Gregor0a897e32009-10-15 17:21:20 +00004663 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004664 Diag(D.getIdentifierLoc(),
4665 diag::err_explicit_instantiation_member_function_not_instantiated)
4666 << Specialization
4667 << (Specialization->getTemplateSpecializationKind() ==
4668 TSK_ExplicitSpecialization);
4669 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4670 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004671 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004672
Douglas Gregor0a897e32009-10-15 17:21:20 +00004673 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004674 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4675 PrevDecl = Specialization;
4676
Douglas Gregor0a897e32009-10-15 17:21:20 +00004677 if (PrevDecl) {
4678 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004679 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004680 PrevDecl,
4681 PrevDecl->getTemplateSpecializationKind(),
4682 PrevDecl->getPointOfInstantiation(),
4683 SuppressNew))
4684 return true;
4685
4686 // FIXME: We may still want to build some representation of this
4687 // explicit specialization.
4688 if (SuppressNew)
4689 return DeclPtrTy();
4690 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00004691
4692 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00004693
4694 if (TSK == TSK_ExplicitInstantiationDefinition)
4695 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4696 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00004697
Douglas Gregor558c0322009-10-14 23:41:34 +00004698 // C++0x [temp.explicit]p2:
4699 // If the explicit instantiation is for a member function, a member class
4700 // or a static data member of a class template specialization, the name of
4701 // the class template specialization in the qualified-id for the member
4702 // name shall be a simple-template-id.
4703 //
4704 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004705 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004706 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004707 D.getCXXScopeSpec().isSet() &&
4708 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4709 Diag(D.getIdentifierLoc(),
4710 diag::err_explicit_instantiation_without_qualified_id)
4711 << Specialization << D.getCXXScopeSpec().getRange();
4712
4713 CheckExplicitInstantiationScope(*this,
4714 FunTmpl? (NamedDecl *)FunTmpl
4715 : Specialization->getInstantiatedFromMemberFunction(),
4716 D.getIdentifierLoc(),
4717 D.getCXXScopeSpec().isSet());
4718
Douglas Gregord5a423b2009-09-25 18:43:00 +00004719 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4720 return DeclPtrTy();
4721}
4722
Douglas Gregord57959a2009-03-27 23:10:48 +00004723Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004724Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4725 const CXXScopeSpec &SS, IdentifierInfo *Name,
4726 SourceLocation TagLoc, SourceLocation NameLoc) {
4727 // This has to hold, because SS is expected to be defined.
4728 assert(Name && "Expected a name in a dependent tag");
4729
4730 NestedNameSpecifier *NNS
4731 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4732 if (!NNS)
4733 return true;
4734
4735 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4736 if (T.isNull())
4737 return true;
4738
4739 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4740 QualType ElabType = Context.getElaboratedType(T, TagKind);
4741
4742 return ElabType.getAsOpaquePtr();
4743}
4744
4745Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004746Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4747 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004748 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004749 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4750 if (!NNS)
4751 return true;
4752
4753 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004754 if (T.isNull())
4755 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004756 return T.getAsOpaquePtr();
4757}
4758
Douglas Gregor17343172009-04-01 00:28:59 +00004759Sema::TypeResult
4760Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4761 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004762 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004763 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004764 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004765 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004766 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004767 assert(TemplateId && "Expected a template specialization type");
4768
Douglas Gregor6946baf2009-09-02 13:05:45 +00004769 if (computeDeclContext(SS, false)) {
4770 // If we can compute a declaration context, then the "typename"
4771 // keyword was superfluous. Just build a QualifiedNameType to keep
4772 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Douglas Gregor6946baf2009-09-02 13:05:45 +00004774 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4775 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4776 }
Mike Stump1eb44332009-09-09 15:08:12 +00004777
Douglas Gregor6946baf2009-09-02 13:05:45 +00004778 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004779}
4780
Douglas Gregord57959a2009-03-27 23:10:48 +00004781/// \brief Build the type that describes a C++ typename specifier,
4782/// e.g., "typename T::type".
4783QualType
4784Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4785 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004786 CXXRecordDecl *CurrentInstantiation = 0;
4787 if (NNS->isDependent()) {
4788 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004789
Douglas Gregor42af25f2009-05-11 19:58:34 +00004790 // If the nested-name-specifier does not refer to the current
4791 // instantiation, then build a typename type.
4792 if (!CurrentInstantiation)
4793 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004794
Douglas Gregorde18d122009-09-02 13:12:51 +00004795 // The nested-name-specifier refers to the current instantiation, so the
4796 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004797 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004798 // extraneous "typename" keywords, and we retroactively apply this DR to
4799 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004800 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004801
Douglas Gregor42af25f2009-05-11 19:58:34 +00004802 DeclContext *Ctx = 0;
4803
4804 if (CurrentInstantiation)
4805 Ctx = CurrentInstantiation;
4806 else {
4807 CXXScopeSpec SS;
4808 SS.setScopeRep(NNS);
4809 SS.setRange(Range);
4810 if (RequireCompleteDeclContext(SS))
4811 return QualType();
4812
4813 Ctx = computeDeclContext(SS);
4814 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004815 assert(Ctx && "No declaration context?");
4816
4817 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00004818 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4819 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00004820 unsigned DiagID = 0;
4821 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004822 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004823 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004824 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004825 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00004826
4827 case LookupResult::NotFoundInCurrentInstantiation:
4828 // Okay, it's a member of an unknown instantiation.
4829 return Context.getTypenameType(NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00004830
4831 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004832 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004833 // We found a type. Build a QualifiedNameType, since the
4834 // typename-specifier was just sugar. FIXME: Tell
4835 // QualifiedNameType that it has a "typename" prefix.
4836 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4837 }
4838
4839 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004840 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004841 break;
4842
John McCall7ba107a2009-11-18 02:36:19 +00004843 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004844 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00004845 return QualType();
4846
Douglas Gregord57959a2009-03-27 23:10:48 +00004847 case LookupResult::FoundOverloaded:
4848 DiagID = diag::err_typename_nested_not_type;
4849 Referenced = *Result.begin();
4850 break;
4851
John McCall6e247262009-10-10 05:48:19 +00004852 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004853 return QualType();
4854 }
4855
4856 // If we get here, it's because name lookup did not find a
4857 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004858 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004859 if (Referenced)
4860 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4861 << Name;
4862 return QualType();
4863}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004864
4865namespace {
4866 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00004867 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00004868 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004869 SourceLocation Loc;
4870 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004871
Douglas Gregor4a959d82009-08-06 16:20:37 +00004872 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004873 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004874 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004875 DeclarationName Entity)
4876 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004877 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004878
4879 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004880 /// transformed.
4881 ///
4882 /// For the purposes of type reconstruction, a type has already been
4883 /// transformed if it is NULL or if it is not dependent.
4884 bool AlreadyTransformed(QualType T) {
4885 return T.isNull() || !T->isDependentType();
4886 }
Mike Stump1eb44332009-09-09 15:08:12 +00004887
4888 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004889 /// rebuilt.
4890 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004891
Douglas Gregor4a959d82009-08-06 16:20:37 +00004892 /// \brief Returns the name of the entity whose type is being rebuilt.
4893 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004894
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004895 /// \brief Sets the "base" location and entity when that
4896 /// information is known based on another transformation.
4897 void setBase(SourceLocation Loc, DeclarationName Entity) {
4898 this->Loc = Loc;
4899 this->Entity = Entity;
4900 }
4901
Douglas Gregor4a959d82009-08-06 16:20:37 +00004902 /// \brief Transforms an expression by returning the expression itself
4903 /// (an identity function).
4904 ///
4905 /// FIXME: This is completely unsafe; we will need to actually clone the
4906 /// expressions.
4907 Sema::OwningExprResult TransformExpr(Expr *E) {
4908 return getSema().Owned(E);
4909 }
Mike Stump1eb44332009-09-09 15:08:12 +00004910
Douglas Gregor4a959d82009-08-06 16:20:37 +00004911 /// \brief Transforms a typename type by determining whether the type now
4912 /// refers to a member of the current instantiation, and then
4913 /// type-checking and building a QualifiedNameType (when possible).
Douglas Gregor124b8782010-02-16 19:09:40 +00004914 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL,
4915 QualType ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004916 };
4917}
4918
Mike Stump1eb44332009-09-09 15:08:12 +00004919QualType
John McCalla2becad2009-10-21 00:40:46 +00004920CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
Douglas Gregor124b8782010-02-16 19:09:40 +00004921 TypenameTypeLoc TL,
4922 QualType ObjectType) {
John McCall833ca992009-10-29 08:12:44 +00004923 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004924
Douglas Gregor4a959d82009-08-06 16:20:37 +00004925 NestedNameSpecifier *NNS
4926 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregor124b8782010-02-16 19:09:40 +00004927 /*FIXME:*/SourceRange(getBaseLocation()),
4928 ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004929 if (!NNS)
4930 return QualType();
4931
4932 // If the nested-name-specifier did not change, and we cannot compute the
4933 // context corresponding to the nested-name-specifier, then this
4934 // typename type will not change; exit early.
4935 CXXScopeSpec SS;
4936 SS.setRange(SourceRange(getBaseLocation()));
4937 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004938
4939 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004940 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004941 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004942
4943 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004944 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004945 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004946 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004947 = TransformType(QualType(TemplateId, 0));
4948 if (NewTemplateId.isNull())
4949 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004950
Douglas Gregor4a959d82009-08-06 16:20:37 +00004951 if (NNS == T->getQualifier() &&
4952 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004953 Result = QualType(T, 0);
4954 else
4955 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4956 } else
4957 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4958 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004959
John McCall833ca992009-10-29 08:12:44 +00004960 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4961 NewTL.setNameLoc(TL.getNameLoc());
4962 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004963}
4964
4965/// \brief Rebuilds a type within the context of the current instantiation.
4966///
Mike Stump1eb44332009-09-09 15:08:12 +00004967/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004968/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004969/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004970/// partial specialization thereof). This routine will rebuild that type now
4971/// that we have entered the declarator's scope, which may produce different
4972/// canonical types, e.g.,
4973///
4974/// \code
4975/// template<typename T>
4976/// struct X {
4977/// typedef T* pointer;
4978/// pointer data();
4979/// };
4980///
4981/// template<typename T>
4982/// typename X<T>::pointer X<T>::data() { ... }
4983/// \endcode
4984///
4985/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4986/// since we do not know that we can look into X<T> when we parsed the type.
4987/// This function will rebuild the type, performing the lookup of "pointer"
4988/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4989/// as the canonical type of T*, allowing the return types of the out-of-line
4990/// definition and the declaration to match.
4991QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4992 DeclarationName Name) {
4993 if (T.isNull() || !T->isDependentType())
4994 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004995
Douglas Gregor4a959d82009-08-06 16:20:37 +00004996 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4997 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004998}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004999
5000/// \brief Produces a formatted string that describes the binding of
5001/// template parameters to template arguments.
5002std::string
5003Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5004 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005005 // FIXME: For variadic templates, we'll need to get the structured list.
5006 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5007 Args.flat_size());
5008}
5009
5010std::string
5011Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5012 const TemplateArgument *Args,
5013 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005014 std::string Result;
5015
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005016 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005017 return Result;
5018
5019 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005020 if (I >= NumArgs)
5021 break;
5022
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005023 if (I == 0)
5024 Result += "[with ";
5025 else
5026 Result += ", ";
5027
5028 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5029 Result += Id->getName();
5030 } else {
5031 Result += '$';
5032 Result += llvm::utostr(I);
5033 }
5034
5035 Result += " = ";
5036
5037 switch (Args[I].getKind()) {
5038 case TemplateArgument::Null:
5039 Result += "<no value>";
5040 break;
5041
5042 case TemplateArgument::Type: {
5043 std::string TypeStr;
5044 Args[I].getAsType().getAsStringInternal(TypeStr,
5045 Context.PrintingPolicy);
5046 Result += TypeStr;
5047 break;
5048 }
5049
5050 case TemplateArgument::Declaration: {
5051 bool Unnamed = true;
5052 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5053 if (ND->getDeclName()) {
5054 Unnamed = false;
5055 Result += ND->getNameAsString();
5056 }
5057 }
5058
5059 if (Unnamed) {
5060 Result += "<anonymous>";
5061 }
5062 break;
5063 }
5064
Douglas Gregor788cd062009-11-11 01:00:40 +00005065 case TemplateArgument::Template: {
5066 std::string Str;
5067 llvm::raw_string_ostream OS(Str);
5068 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5069 Result += OS.str();
5070 break;
5071 }
5072
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005073 case TemplateArgument::Integral: {
5074 Result += Args[I].getAsIntegral()->toString(10);
5075 break;
5076 }
5077
5078 case TemplateArgument::Expression: {
5079 assert(false && "No expressions in deduced template arguments!");
5080 Result += "<expression>";
5081 break;
5082 }
5083
5084 case TemplateArgument::Pack:
5085 // FIXME: Format template argument packs
5086 Result += "<template argument pack>";
5087 break;
5088 }
5089 }
5090
5091 Result += ']';
5092 return Result;
5093}