blob: 2e4eed8b2860f30cbb05559cb5139547a923b3b0 [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 Gregor4a959d82009-08-06 16:20:37 +000023#include "llvm/Support/Compiler.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregor2dd078a2009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Douglas Gregor2dd078a2009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000036
Douglas Gregor2dd078a2009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor2dd078a2009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump1eb44332009-09-09 15:08:12 +000061
Douglas Gregor2dd078a2009-09-02 22:59:36 +000062 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
63 if (!Ovl)
64 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Douglas Gregor2dd078a2009-09-02 22:59:36 +000066 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
67 FEnd = Ovl->function_end();
68 F != FEnd; ++F) {
69 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
70 // We've found a function template. Determine whether there are
71 // any other function templates we need to bundle together in an
72 // OverloadedFunctionDecl
73 for (++F; F != FEnd; ++F) {
74 if (isa<FunctionTemplateDecl>(*F))
75 break;
76 }
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregor2dd078a2009-09-02 22:59:36 +000078 if (F != FEnd) {
79 // Build an overloaded function decl containing only the
80 // function templates in Ovl.
Mike Stump1eb44332009-09-09 15:08:12 +000081 OverloadedFunctionDecl *OvlTemplate
Douglas Gregor2dd078a2009-09-02 22:59:36 +000082 = OverloadedFunctionDecl::Create(Context,
83 Ovl->getDeclContext(),
84 Ovl->getDeclName());
85 OvlTemplate->addOverload(FuncTmpl);
86 OvlTemplate->addOverload(*F);
87 for (++F; F != FEnd; ++F) {
88 if (isa<FunctionTemplateDecl>(*F))
89 OvlTemplate->addOverload(*F);
90 }
Mike Stump1eb44332009-09-09 15:08:12 +000091
Douglas Gregor2dd078a2009-09-02 22:59:36 +000092 return OvlTemplate;
93 }
94
95 return FuncTmpl;
96 }
97 }
Mike Stump1eb44332009-09-09 15:08:12 +000098
Douglas Gregor2dd078a2009-09-02 22:59:36 +000099 return 0;
100}
101
John McCallf7a1a742009-11-24 19:00:30 +0000102static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
103 LookupResult::Filter filter = R.makeFilter();
104 while (filter.hasNext()) {
105 NamedDecl *Orig = filter.next();
106 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
107 if (!Repl)
108 filter.erase();
109 else if (Repl != Orig)
110 filter.replace(Repl);
111 }
112 filter.done();
113}
114
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000115TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000116 const CXXScopeSpec &SS,
117 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000118 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000119 bool EnteringContext,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000120 TemplateTy &TemplateResult) {
Douglas Gregor014e88d2009-11-03 23:16:33 +0000121 DeclarationName TName;
122
123 switch (Name.getKind()) {
124 case UnqualifiedId::IK_Identifier:
125 TName = DeclarationName(Name.Identifier);
126 break;
127
128 case UnqualifiedId::IK_OperatorFunctionId:
129 TName = Context.DeclarationNames.getCXXOperatorName(
130 Name.OperatorFunctionId.Operator);
131 break;
132
Sean Hunte6252d12009-11-28 08:58:14 +0000133 case UnqualifiedId::IK_LiteralOperatorId:
134 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
135
136
Douglas Gregor014e88d2009-11-03 23:16:33 +0000137 default:
138 return TNK_Non_template;
139 }
Mike Stump1eb44332009-09-09 15:08:12 +0000140
John McCallf7a1a742009-11-24 19:00:30 +0000141 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000142
John McCallf7a1a742009-11-24 19:00:30 +0000143 LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName);
144 R.suppressDiagnostics();
145 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
146 if (R.empty())
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000147 return TNK_Non_template;
148
John McCallf7a1a742009-11-24 19:00:30 +0000149 NamedDecl *Template = R.getAsSingleDecl(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Douglas Gregor014e88d2009-11-03 23:16:33 +0000151 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000152 NestedNameSpecifier *Qualifier
Douglas Gregor014e88d2009-11-03 23:16:33 +0000153 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +0000154 if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000155 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump1eb44332009-09-09 15:08:12 +0000156 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000157 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
158 Ovl));
159 else
Mike Stump1eb44332009-09-09 15:08:12 +0000160 TemplateResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000161 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump1eb44332009-09-09 15:08:12 +0000162 cast<TemplateDecl>(Template)));
163 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000164 = dyn_cast<OverloadedFunctionDecl>(Template)) {
165 TemplateResult = TemplateTy::make(TemplateName(Ovl));
166 } else {
167 TemplateResult = TemplateTy::make(
168 TemplateName(cast<TemplateDecl>(Template)));
169 }
Mike Stump1eb44332009-09-09 15:08:12 +0000170
171 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000172 isa<TemplateTemplateParmDecl>(Template))
173 return TNK_Type_template;
Mike Stump1eb44332009-09-09 15:08:12 +0000174
175 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 isa<OverloadedFunctionDecl>(Template)) &&
177 "Unhandled template kind in Sema::isTemplateName");
John McCallf7a1a742009-11-24 19:00:30 +0000178 return TNK_Function_template;
179}
180
181void Sema::LookupTemplateName(LookupResult &Found,
182 Scope *S, const CXXScopeSpec &SS,
183 QualType ObjectType,
184 bool EnteringContext) {
185 // Determine where to perform name lookup
186 DeclContext *LookupCtx = 0;
187 bool isDependent = false;
188 if (!ObjectType.isNull()) {
189 // This nested-name-specifier occurs in a member access expression, e.g.,
190 // x->B::f, and we are looking into the type of the object.
191 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
192 LookupCtx = computeDeclContext(ObjectType);
193 isDependent = ObjectType->isDependentType();
194 assert((isDependent || !ObjectType->isIncompleteType()) &&
195 "Caller should have completed object type");
196 } else if (SS.isSet()) {
197 // This nested-name-specifier occurs after another nested-name-specifier,
198 // so long into the context associated with the prior nested-name-specifier.
199 LookupCtx = computeDeclContext(SS, EnteringContext);
200 isDependent = isDependentScopeSpecifier(SS);
201
202 // The declaration context must be complete.
203 if (LookupCtx && RequireCompleteDeclContext(SS))
204 return;
205 }
206
207 bool ObjectTypeSearchedInScope = false;
208 if (LookupCtx) {
209 // Perform "qualified" name lookup into the declaration context we
210 // computed, which is either the type of the base of a member access
211 // expression or the declaration context associated with a prior
212 // nested-name-specifier.
213 LookupQualifiedName(Found, LookupCtx);
214
215 if (!ObjectType.isNull() && Found.empty()) {
216 // C++ [basic.lookup.classref]p1:
217 // In a class member access expression (5.2.5), if the . or -> token is
218 // immediately followed by an identifier followed by a <, the
219 // identifier must be looked up to determine whether the < is the
220 // beginning of a template argument list (14.2) or a less-than operator.
221 // The identifier is first looked up in the class of the object
222 // expression. If the identifier is not found, it is then looked up in
223 // the context of the entire postfix-expression and shall name a class
224 // or function template.
225 //
226 // FIXME: When we're instantiating a template, do we actually have to
227 // look in the scope of the template? Seems fishy...
228 if (S) LookupName(Found, S);
229 ObjectTypeSearchedInScope = true;
230 }
231 } else if (isDependent) {
232 // We cannot look into a dependent object type or
233 return;
234 } else {
235 // Perform unqualified name lookup in the current scope.
236 LookupName(Found, S);
237 }
238
239 // FIXME: Cope with ambiguous name-lookup results.
240 assert(!Found.isAmbiguous() &&
241 "Cannot handle template name-lookup ambiguities");
242
243 FilterAcceptableTemplateNames(Context, Found);
244 if (Found.empty())
245 return;
246
247 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
248 // C++ [basic.lookup.classref]p1:
249 // [...] If the lookup in the class of the object expression finds a
250 // template, the name is also looked up in the context of the entire
251 // postfix-expression and [...]
252 //
253 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
254 LookupOrdinaryName);
255 LookupName(FoundOuter, S);
256 FilterAcceptableTemplateNames(Context, FoundOuter);
257 // FIXME: Handle ambiguities in this lookup better
258
259 if (FoundOuter.empty()) {
260 // - if the name is not found, the name found in the class of the
261 // object expression is used, otherwise
262 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
263 // - if the name is found in the context of the entire
264 // postfix-expression and does not name a class template, the name
265 // found in the class of the object expression is used, otherwise
266 } else {
267 // - if the name found is a class template, it must refer to the same
268 // entity as the one found in the class of the object expression,
269 // otherwise the program is ill-formed.
270 if (!Found.isSingleResult() ||
271 Found.getFoundDecl()->getCanonicalDecl()
272 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
273 Diag(Found.getNameLoc(),
274 diag::err_nested_name_member_ref_lookup_ambiguous)
275 << Found.getLookupName();
276 Diag(Found.getRepresentativeDecl()->getLocation(),
277 diag::note_ambig_member_ref_object_type)
278 << ObjectType;
279 Diag(FoundOuter.getFoundDecl()->getLocation(),
280 diag::note_ambig_member_ref_scope);
281
282 // Recover by taking the template that we found in the object
283 // expression's type.
284 }
285 }
286 }
287}
288
289/// Constructs a full type for the given nested-name-specifier.
290static QualType GetTypeForQualifier(ASTContext &Context,
291 NestedNameSpecifier *Qualifier) {
292 // Three possibilities:
293
294 // 1. A namespace (global or not).
295 assert(!Qualifier->getAsNamespace() && "can't construct type for namespace");
296
297 // 2. A type (templated or not).
298 Type *Ty = Qualifier->getAsType();
299 if (Ty) return QualType(Ty, 0);
300
301 // 3. A dependent identifier.
302 assert(Qualifier->getAsIdentifier());
303 return Context.getTypenameType(Qualifier->getPrefix(),
304 Qualifier->getAsIdentifier());
305}
306
307static bool HasDependentTypeAsBase(ASTContext &Context,
308 CXXRecordDecl *Record,
309 CanQualType T) {
310 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
311 E = Record->bases_end(); I != E; ++I) {
312 CanQualType BaseT = Context.getCanonicalType((*I).getType());
313 if (BaseT == T)
314 return true;
315
316 // We have to recurse here to cover some really bizarre cases.
317 // Obviously, we can only have the dependent type as an indirect
318 // base class through a dependent base class, and usually it's
319 // impossible to know which instantiation a dependent base class
320 // will have. But! If we're actually *inside* the dependent base
321 // class, then we know its instantiation and can therefore be
322 // reasonably expected to look into it.
323
324 // template <class T> class A : Base<T> {
325 // class Inner : A<T> {
326 // void foo() {
327 // Base<T>::foo(); // statically known to be an implicit member
328 // reference
329 // }
330 // };
331 // };
332
333 CanQual<RecordType> RT = BaseT->getAs<RecordType>();
John McCall26416062009-11-24 20:33:45 +0000334
335 // Base might be a dependent member type, in which case we
336 // obviously can't look into it.
337 if (!RT) continue;
338
John McCallf7a1a742009-11-24 19:00:30 +0000339 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(RT->getDecl());
340 if (BaseRecord->isDefinition() &&
341 HasDependentTypeAsBase(Context, BaseRecord, T))
342 return true;
343 }
344
345 return false;
346}
347
348/// Checks whether the given dependent nested-name specifier
349/// introduces an implicit member reference. This is only true if the
350/// nested-name specifier names a type identical to one of the current
351/// instance method's context's (possibly indirect) base classes.
352static bool IsImplicitDependentMemberReference(Sema &SemaRef,
353 NestedNameSpecifier *Qualifier,
354 QualType &ThisType) {
355 // If the context isn't a C++ method, then it isn't an implicit
356 // member reference.
357 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext);
358 if (!MD || MD->isStatic())
359 return false;
360
361 ASTContext &Context = SemaRef.Context;
362
363 // We want to check whether the method's context is known to inherit
364 // from the type named by the nested name specifier. The trivial
365 // case here is:
366 // template <class T> class Base { ... };
367 // template <class T> class Derived : Base<T> {
368 // void foo() {
369 // Base<T>::foo();
370 // }
371 // };
372
373 QualType QT = GetTypeForQualifier(Context, Qualifier);
374 CanQualType T = Context.getCanonicalType(QT);
John McCall26416062009-11-24 20:33:45 +0000375
John McCallf7a1a742009-11-24 19:00:30 +0000376 // And now, just walk the non-dependent type hierarchy, trying to
377 // find the given type as a literal base class.
378 CXXRecordDecl *Record = cast<CXXRecordDecl>(MD->getParent());
John McCall26416062009-11-24 20:33:45 +0000379 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T ||
380 HasDependentTypeAsBase(Context, Record, T)) {
381 ThisType = MD->getThisType(Context);
John McCallf7a1a742009-11-24 19:00:30 +0000382 return true;
John McCall26416062009-11-24 20:33:45 +0000383 }
John McCallf7a1a742009-11-24 19:00:30 +0000384
John McCall26416062009-11-24 20:33:45 +0000385 return false;
John McCallf7a1a742009-11-24 19:00:30 +0000386}
387
388/// ActOnDependentIdExpression - Handle a dependent declaration name
389/// that was just parsed.
390Sema::OwningExprResult
391Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
392 DeclarationName Name,
393 SourceLocation NameLoc,
394 bool CheckForImplicitMember,
395 const TemplateArgumentListInfo *TemplateArgs) {
396 NestedNameSpecifier *Qualifier
397 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
398
399 QualType ThisType;
400 if (CheckForImplicitMember &&
401 IsImplicitDependentMemberReference(*this, Qualifier, ThisType)) {
402 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
403
404 // Since the 'this' expression is synthesized, we don't need to
405 // perform the double-lookup check.
406 NamedDecl *FirstQualifierInScope = 0;
407
408 return Owned(CXXDependentScopeMemberExpr::Create(Context, This, true,
409 /*Op*/ SourceLocation(),
410 Qualifier, SS.getRange(),
411 FirstQualifierInScope,
412 Name, NameLoc,
413 TemplateArgs));
414 }
415
416 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
417}
418
419Sema::OwningExprResult
420Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
421 DeclarationName Name,
422 SourceLocation NameLoc,
423 const TemplateArgumentListInfo *TemplateArgs) {
424 return Owned(DependentScopeDeclRefExpr::Create(Context,
425 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
426 SS.getRange(),
427 Name, NameLoc,
428 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000429}
430
Douglas Gregor72c3f312008-12-05 18:15:24 +0000431/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
432/// that the template parameter 'PrevDecl' is being shadowed by a new
433/// declaration at location Loc. Returns true to indicate that this is
434/// an error, and false otherwise.
435bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000436 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000437
438 // Microsoft Visual C++ permits template parameters to be shadowed.
439 if (getLangOptions().Microsoft)
440 return false;
441
442 // C++ [temp.local]p4:
443 // A template-parameter shall not be redeclared within its
444 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000445 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000446 << cast<NamedDecl>(PrevDecl)->getDeclName();
447 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
448 return true;
449}
450
Douglas Gregor2943aed2009-03-03 04:44:36 +0000451/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000452/// the parameter D to reference the templated declaration and return a pointer
453/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000454TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000455 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000456 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000457 return Temp;
458 }
459 return 0;
460}
461
Douglas Gregor788cd062009-11-11 01:00:40 +0000462static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
463 const ParsedTemplateArgument &Arg) {
464
465 switch (Arg.getKind()) {
466 case ParsedTemplateArgument::Type: {
467 DeclaratorInfo *DI;
468 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
469 if (!DI)
470 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
471 return TemplateArgumentLoc(TemplateArgument(T), DI);
472 }
473
474 case ParsedTemplateArgument::NonType: {
475 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
476 return TemplateArgumentLoc(TemplateArgument(E), E);
477 }
478
479 case ParsedTemplateArgument::Template: {
480 TemplateName Template
481 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
482 return TemplateArgumentLoc(TemplateArgument(Template),
483 Arg.getScopeSpec().getRange(),
484 Arg.getLocation());
485 }
486 }
487
488 llvm::llvm_unreachable("Unhandled parsed template argument");
489 return TemplateArgumentLoc();
490}
491
492/// \brief Translates template arguments as provided by the parser
493/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000494void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
495 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000496 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000497 TemplateArgs.addArgument(translateTemplateArgument(*this,
498 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000499}
500
Douglas Gregor72c3f312008-12-05 18:15:24 +0000501/// ActOnTypeParameter - Called when a C++ template type parameter
502/// (e.g., "typename T") has been parsed. Typename specifies whether
503/// the keyword "typename" was used to declare the type parameter
504/// (otherwise, "class" was used), and KeyLoc is the location of the
505/// "class" or "typename" keyword. ParamName is the name of the
506/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000507/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000508/// If the type parameter has a default argument, it will be added
509/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000510Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000511 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000512 SourceLocation KeyLoc,
513 IdentifierInfo *ParamName,
514 SourceLocation ParamNameLoc,
515 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000516 assert(S->isTemplateParamScope() &&
517 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000518 bool Invalid = false;
519
520 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000521 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000522 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000523 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000524 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000525 }
526
Douglas Gregorddc29e12009-02-06 22:42:48 +0000527 SourceLocation Loc = ParamNameLoc;
528 if (!ParamName)
529 Loc = KeyLoc;
530
Douglas Gregor72c3f312008-12-05 18:15:24 +0000531 TemplateTypeParmDecl *Param
Mike Stump1eb44332009-09-09 15:08:12 +0000532 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
533 Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000534 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000535 if (Invalid)
536 Param->setInvalidDecl();
537
538 if (ParamName) {
539 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000540 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000541 IdResolver.AddDecl(Param);
542 }
543
Chris Lattnerb28317a2009-03-28 19:18:32 +0000544 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000545}
546
Douglas Gregord684b002009-02-10 19:49:53 +0000547/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000548/// Default) to the given template type parameter (TypeParam).
549void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000550 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000551 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000552 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000553 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000554 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000555
556 DeclaratorInfo *DefaultDInfo;
557 GetTypeFromParser(DefaultT, &DefaultDInfo);
558
559 assert(DefaultDInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000560
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000561 // C++0x [temp.param]p9:
562 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000563 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000564 if (Parm->isParameterPack()) {
565 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000566 return;
567 }
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Douglas Gregord684b002009-02-10 19:49:53 +0000569 // C++ [temp.param]p14:
570 // A template-parameter shall not be used in its own default argument.
571 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Douglas Gregord684b002009-02-10 19:49:53 +0000573 // Check the template argument itself.
John McCall833ca992009-10-29 08:12:44 +0000574 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000575 Parm->setInvalidDecl();
576 return;
577 }
578
John McCall833ca992009-10-29 08:12:44 +0000579 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000580}
581
Douglas Gregor2943aed2009-03-03 04:44:36 +0000582/// \brief Check that the type of a non-type template parameter is
583/// well-formed.
584///
585/// \returns the (possibly-promoted) parameter type if valid;
586/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000587QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000588Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
589 // C++ [temp.param]p4:
590 //
591 // A non-type template-parameter shall have one of the following
592 // (optionally cv-qualified) types:
593 //
594 // -- integral or enumeration type,
595 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000596 // -- pointer to object or pointer to function,
597 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000598 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
599 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000600 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 T->isReferenceType() ||
602 // -- pointer to member.
603 T->isMemberPointerType() ||
604 // If T is a dependent type, we can't do the check now, so we
605 // assume that it is well-formed.
606 T->isDependentType())
607 return T;
608 // C++ [temp.param]p8:
609 //
610 // A non-type template-parameter of type "array of T" or
611 // "function returning T" is adjusted to be of type "pointer to
612 // T" or "pointer to function returning T", respectively.
613 else if (T->isArrayType())
614 // FIXME: Keep the type prior to promotion?
615 return Context.getArrayDecayedType(T);
616 else if (T->isFunctionType())
617 // FIXME: Keep the type prior to promotion?
618 return Context.getPointerType(T);
619
620 Diag(Loc, diag::err_template_nontype_parm_bad_type)
621 << T;
622
623 return QualType();
624}
625
Douglas Gregor72c3f312008-12-05 18:15:24 +0000626/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
627/// template parameter (e.g., "int Size" in "template<int Size>
628/// class Array") has been parsed. S is the current scope and D is
629/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000630Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000631 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000632 unsigned Position) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000633 DeclaratorInfo *DInfo = 0;
634 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000635
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000636 assert(S->isTemplateParamScope() &&
637 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000638 bool Invalid = false;
639
640 IdentifierInfo *ParamName = D.getIdentifier();
641 if (ParamName) {
John McCallf36e02d2009-10-09 21:13:30 +0000642 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000643 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000644 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000645 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000646 }
647
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000649 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000650 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000651 Invalid = true;
652 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000653
Douglas Gregor72c3f312008-12-05 18:15:24 +0000654 NonTypeTemplateParmDecl *Param
655 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000656 Depth, Position, ParamName, T, DInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000657 if (Invalid)
658 Param->setInvalidDecl();
659
660 if (D.getIdentifier()) {
661 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000662 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000663 IdResolver.AddDecl(Param);
664 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000665 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000666}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000667
Douglas Gregord684b002009-02-10 19:49:53 +0000668/// \brief Adds a default argument to the given non-type template
669/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000670void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000671 SourceLocation EqualLoc,
672 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000673 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000674 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000675 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Douglas Gregord684b002009-02-10 19:49:53 +0000677 // C++ [temp.param]p14:
678 // A template-parameter shall not be used in its own default argument.
679 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Douglas Gregord684b002009-02-10 19:49:53 +0000681 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000682 TemplateArgument Converted;
683 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
684 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000685 TemplateParm->setInvalidDecl();
686 return;
687 }
688
Anders Carlssone9146f22009-05-01 19:49:17 +0000689 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000690}
691
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000692
693/// ActOnTemplateTemplateParameter - Called when a C++ template template
694/// parameter (e.g. T in template <template <typename> class T> class array)
695/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000696Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
697 SourceLocation TmpLoc,
698 TemplateParamsTy *Params,
699 IdentifierInfo *Name,
700 SourceLocation NameLoc,
701 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000702 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000703 assert(S->isTemplateParamScope() &&
704 "Template template parameter not in template parameter scope!");
705
706 // Construct the parameter object.
707 TemplateTemplateParmDecl *Param =
708 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
709 Position, Name,
710 (TemplateParameterList*)Params);
711
712 // Make sure the parameter is valid.
713 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
714 // do anything yet. However, if the template parameter list or (eventual)
715 // default value is ever invalidated, that will propagate here.
716 bool Invalid = false;
717 if (Invalid) {
718 Param->setInvalidDecl();
719 }
720
721 // If the tt-param has a name, then link the identifier into the scope
722 // and lookup mechanisms.
723 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000724 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000725 IdResolver.AddDecl(Param);
726 }
727
Chris Lattnerb28317a2009-03-28 19:18:32 +0000728 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000729}
730
Douglas Gregord684b002009-02-10 19:49:53 +0000731/// \brief Adds a default argument to the given template template
732/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000733void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000734 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000735 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000736 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000737 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000738
Douglas Gregord684b002009-02-10 19:49:53 +0000739 // C++ [temp.param]p14:
740 // A template-parameter shall not be used in its own default argument.
741 // FIXME: Implement this check! Needs a recursive walk over the types.
742
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000743 // Check only that we have a template template argument. We don't want to
744 // try to check well-formedness now, because our template template parameter
745 // might have dependent types in its template parameters, which we wouldn't
746 // be able to match now.
747 //
748 // If none of the template template parameter's template arguments mention
749 // other template parameters, we could actually perform more checking here.
750 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000751 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000752 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
753 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
754 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000755 return;
756 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000757
Douglas Gregor788cd062009-11-11 01:00:40 +0000758 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000759}
760
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000761/// ActOnTemplateParameterList - Builds a TemplateParameterList that
762/// contains the template parameters in Params/NumParams.
763Sema::TemplateParamsTy *
764Sema::ActOnTemplateParameterList(unsigned Depth,
765 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000766 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000767 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000768 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000769 SourceLocation RAngleLoc) {
770 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000771 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000772
Douglas Gregorddc29e12009-02-06 22:42:48 +0000773 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000774 (NamedDecl**)Params, NumParams,
775 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000776}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000777
Douglas Gregor212e81c2009-03-25 00:13:59 +0000778Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000779Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000780 SourceLocation KWLoc, const CXXScopeSpec &SS,
781 IdentifierInfo *Name, SourceLocation NameLoc,
782 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000783 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000784 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000785 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000786 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000787 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000788 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000789
790 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000791 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000792 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000793
John McCall05b23ea2009-09-14 21:59:20 +0000794 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
795 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000796
797 // There is no such thing as an unnamed class template.
798 if (!Name) {
799 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000800 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000801 }
802
803 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000804 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000805 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000806 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000807 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregorf0510d42009-10-12 23:11:44 +0000808 if (RequireCompleteDeclContext(SS))
809 return true;
810
Douglas Gregor05396e22009-08-25 17:23:04 +0000811 SemanticContext = computeDeclContext(SS, true);
812 if (!SemanticContext) {
813 // FIXME: Produce a reasonable diagnostic here
814 return true;
815 }
Mike Stump1eb44332009-09-09 15:08:12 +0000816
John McCalla24dc2e2009-11-17 02:14:36 +0000817 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000818 } else {
819 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000820 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000821 }
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Douglas Gregorddc29e12009-02-06 22:42:48 +0000823 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
824 NamedDecl *PrevDecl = 0;
825 if (Previous.begin() != Previous.end())
826 PrevDecl = *Previous.begin();
827
Douglas Gregor6102d982009-09-26 07:05:09 +0000828 if (PrevDecl && TUK == TUK_Friend) {
829 // C++ [namespace.memdef]p3:
830 // [...] When looking for a prior declaration of a class or a function
831 // declared as a friend, and when the name of the friend class or
832 // function is neither a qualified name nor a template-id, scopes outside
833 // the innermost enclosing namespace scope are not considered.
834 DeclContext *OutermostContext = CurContext;
835 while (!OutermostContext->isFileContext())
836 OutermostContext = OutermostContext->getLookupParent();
837
838 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
839 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
840 SemanticContext = PrevDecl->getDeclContext();
841 } else {
842 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregor259571e2009-10-30 22:42:42 +0000843 // context we computed is the semantic context for our new
Douglas Gregor6102d982009-09-26 07:05:09 +0000844 // declaration.
845 PrevDecl = 0;
846 SemanticContext = OutermostContext;
847 }
Douglas Gregor259571e2009-10-30 22:42:42 +0000848
849 if (CurContext->isDependentContext()) {
850 // If this is a dependent context, we don't want to link the friend
851 // class template to the template in scope, because that would perform
852 // checking of the template parameter lists that can't be performed
853 // until the outer context is instantiated.
854 PrevDecl = 0;
855 }
Douglas Gregor6102d982009-09-26 07:05:09 +0000856 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000857 PrevDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Douglas Gregorddc29e12009-02-06 22:42:48 +0000859 // If there is a previous declaration with the same name, check
860 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000861 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000862 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000863
864 // We may have found the injected-class-name of a class template,
865 // class template partial specialization, or class template specialization.
866 // In these cases, grab the template that is being defined or specialized.
867 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
868 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
869 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
870 PrevClassTemplate
871 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
872 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
873 PrevClassTemplate
874 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
875 ->getSpecializedTemplate();
876 }
877 }
878
Douglas Gregorddc29e12009-02-06 22:42:48 +0000879 if (PrevClassTemplate) {
880 // Ensure that the template parameter lists are compatible.
881 if (!TemplateParameterListsAreEqual(TemplateParams,
882 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000883 /*Complain=*/true,
884 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000885 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000886
887 // C++ [temp.class]p4:
888 // In a redeclaration, partial specialization, explicit
889 // specialization or explicit instantiation of a class template,
890 // the class-key shall agree in kind with the original class
891 // template declaration (7.1.5.3).
892 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000893 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000894 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000895 << Name
Mike Stump1eb44332009-09-09 15:08:12 +0000896 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +0000897 PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000898 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000899 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000900 }
901
Douglas Gregorddc29e12009-02-06 22:42:48 +0000902 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000903 if (TUK == TUK_Definition) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000904 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
905 Diag(NameLoc, diag::err_redefinition) << Name;
906 Diag(Def->getLocation(), diag::note_previous_definition);
907 // FIXME: Would it make sense to try to "forget" the previous
908 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000909 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000910 }
911 }
912 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
913 // Maybe we will complain about the shadowed template parameter.
914 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
915 // Just pretend that we didn't see the previous declaration.
916 PrevDecl = 0;
917 } else if (PrevDecl) {
918 // C++ [temp]p5:
919 // A class template shall not have the same name as any other
920 // template, class, function, object, enumeration, enumerator,
921 // namespace, or type in the same scope (3.3), except as specified
922 // in (14.5.4).
923 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
924 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000925 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000926 }
927
Douglas Gregord684b002009-02-10 19:49:53 +0000928 // Check the template parameter list of this declaration, possibly
929 // merging in the template parameter list from the previous class
930 // template declaration.
931 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000932 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
933 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000934 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Douglas Gregor7da97d02009-05-10 22:57:19 +0000936 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorddc29e12009-02-06 22:42:48 +0000937 // declaration!
938
Mike Stump1eb44332009-09-09 15:08:12 +0000939 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000940 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000941 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000942 PrevClassTemplate->getTemplatedDecl() : 0,
943 /*DelayTypeCreation=*/true);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000944
945 ClassTemplateDecl *NewTemplate
946 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
947 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000948 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000949 NewClass->setDescribedClassTemplate(NewTemplate);
950
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000951 // Build the type for the class template declaration now.
Mike Stump1eb44332009-09-09 15:08:12 +0000952 QualType T =
953 Context.getTypeDeclType(NewClass,
954 PrevClassTemplate?
955 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000956 assert(T->isDependentType() && "Class template type is not dependent?");
957 (void)T;
958
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000959 // If we are providing an explicit specialization of a member that is a
960 // class template, make a note of that.
961 if (PrevClassTemplate &&
962 PrevClassTemplate->getInstantiatedFromMemberTemplate())
963 PrevClassTemplate->setMemberSpecialization();
964
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000965 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000966 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000967 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Douglas Gregorddc29e12009-02-06 22:42:48 +0000969 // Set the lexical context of these templates
970 NewClass->setLexicalDeclContext(CurContext);
971 NewTemplate->setLexicalDeclContext(CurContext);
972
John McCall0f434ec2009-07-31 02:45:11 +0000973 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000974 NewClass->startDefinition();
975
976 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000977 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000978
John McCall05b23ea2009-09-14 21:59:20 +0000979 if (TUK != TUK_Friend)
980 PushOnScopeChains(NewTemplate, S);
981 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000982 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000983 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000984 NewClass->setAccess(PrevClassTemplate->getAccess());
985 }
John McCall05b23ea2009-09-14 21:59:20 +0000986
Douglas Gregord85bea22009-09-26 06:47:28 +0000987 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
988 PrevClassTemplate != NULL);
989
John McCall05b23ea2009-09-14 21:59:20 +0000990 // Friend templates are visible in fairly strange ways.
991 if (!CurContext->isDependentContext()) {
992 DeclContext *DC = SemanticContext->getLookupContext();
993 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
994 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
995 PushOnScopeChains(NewTemplate, EnclosingScope,
996 /* AddToContext = */ false);
997 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000998
999 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1000 NewClass->getLocation(),
1001 NewTemplate,
1002 /*FIXME:*/NewClass->getLocation());
1003 Friend->setAccess(AS_public);
1004 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +00001005 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00001006
Douglas Gregord684b002009-02-10 19:49:53 +00001007 if (Invalid) {
1008 NewTemplate->setInvalidDecl();
1009 NewClass->setInvalidDecl();
1010 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00001011 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +00001012}
1013
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001014/// \brief Diagnose the presence of a default template argument on a
1015/// template parameter, which is ill-formed in certain contexts.
1016///
1017/// \returns true if the default template argument should be dropped.
1018static bool DiagnoseDefaultTemplateArgument(Sema &S,
1019 Sema::TemplateParamListContext TPC,
1020 SourceLocation ParamLoc,
1021 SourceRange DefArgRange) {
1022 switch (TPC) {
1023 case Sema::TPC_ClassTemplate:
1024 return false;
1025
1026 case Sema::TPC_FunctionTemplate:
1027 // C++ [temp.param]p9:
1028 // A default template-argument shall not be specified in a
1029 // function template declaration or a function template
1030 // definition [...]
1031 // (This sentence is not in C++0x, per DR226).
1032 if (!S.getLangOptions().CPlusPlus0x)
1033 S.Diag(ParamLoc,
1034 diag::err_template_parameter_default_in_function_template)
1035 << DefArgRange;
1036 return false;
1037
1038 case Sema::TPC_ClassTemplateMember:
1039 // C++0x [temp.param]p9:
1040 // A default template-argument shall not be specified in the
1041 // template-parameter-lists of the definition of a member of a
1042 // class template that appears outside of the member's class.
1043 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1044 << DefArgRange;
1045 return true;
1046
1047 case Sema::TPC_FriendFunctionTemplate:
1048 // C++ [temp.param]p9:
1049 // A default template-argument shall not be specified in a
1050 // friend template declaration.
1051 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1052 << DefArgRange;
1053 return true;
1054
1055 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1056 // for friend function templates if there is only a single
1057 // declaration (and it is a definition). Strange!
1058 }
1059
1060 return false;
1061}
1062
Douglas Gregord684b002009-02-10 19:49:53 +00001063/// \brief Checks the validity of a template parameter list, possibly
1064/// considering the template parameter list from a previous
1065/// declaration.
1066///
1067/// If an "old" template parameter list is provided, it must be
1068/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1069/// template parameter list.
1070///
1071/// \param NewParams Template parameter list for a new template
1072/// declaration. This template parameter list will be updated with any
1073/// default arguments that are carried through from the previous
1074/// template parameter list.
1075///
1076/// \param OldParams If provided, template parameter list from a
1077/// previous declaration of the same template. Default template
1078/// arguments will be merged from the old template parameter list to
1079/// the new template parameter list.
1080///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001081/// \param TPC Describes the context in which we are checking the given
1082/// template parameter list.
1083///
Douglas Gregord684b002009-02-10 19:49:53 +00001084/// \returns true if an error occurred, false otherwise.
1085bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001086 TemplateParameterList *OldParams,
1087 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001088 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Douglas Gregord684b002009-02-10 19:49:53 +00001090 // C++ [temp.param]p10:
1091 // The set of default template-arguments available for use with a
1092 // template declaration or definition is obtained by merging the
1093 // default arguments from the definition (if in scope) and all
1094 // declarations in scope in the same way default function
1095 // arguments are (8.3.6).
1096 bool SawDefaultArgument = false;
1097 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001098
Anders Carlsson49d25572009-06-12 23:20:15 +00001099 bool SawParameterPack = false;
1100 SourceLocation ParameterPackLoc;
1101
Mike Stump1a35fde2009-02-11 23:03:27 +00001102 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001103 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001104 if (OldParams)
1105 OldParam = OldParams->begin();
1106
1107 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1108 NewParamEnd = NewParams->end();
1109 NewParam != NewParamEnd; ++NewParam) {
1110 // Variables used to diagnose redundant default arguments
1111 bool RedundantDefaultArg = false;
1112 SourceLocation OldDefaultLoc;
1113 SourceLocation NewDefaultLoc;
1114
1115 // Variables used to diagnose missing default arguments
1116 bool MissingDefaultArg = false;
1117
Anders Carlsson49d25572009-06-12 23:20:15 +00001118 // C++0x [temp.param]p11:
1119 // If a template parameter of a class template is a template parameter pack,
1120 // it must be the last template parameter.
1121 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001122 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001123 diag::err_template_param_pack_must_be_last_template_parameter);
1124 Invalid = true;
1125 }
1126
Douglas Gregord684b002009-02-10 19:49:53 +00001127 if (TemplateTypeParmDecl *NewTypeParm
1128 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001129 // Check the presence of a default argument here.
1130 if (NewTypeParm->hasDefaultArgument() &&
1131 DiagnoseDefaultTemplateArgument(*this, TPC,
1132 NewTypeParm->getLocation(),
1133 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1134 .getFullSourceRange()))
1135 NewTypeParm->removeDefaultArgument();
1136
1137 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001138 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001139 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Anders Carlsson49d25572009-06-12 23:20:15 +00001141 if (NewTypeParm->isParameterPack()) {
1142 assert(!NewTypeParm->hasDefaultArgument() &&
1143 "Parameter packs can't have a default argument!");
1144 SawParameterPack = true;
1145 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001146 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001147 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001148 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1149 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1150 SawDefaultArgument = true;
1151 RedundantDefaultArg = true;
1152 PreviousDefaultArgLoc = NewDefaultLoc;
1153 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1154 // Merge the default argument from the old declaration to the
1155 // new declaration.
1156 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001157 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001158 true);
1159 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1160 } else if (NewTypeParm->hasDefaultArgument()) {
1161 SawDefaultArgument = true;
1162 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1163 } else if (SawDefaultArgument)
1164 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001165 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001166 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001167 // Check the presence of a default argument here.
1168 if (NewNonTypeParm->hasDefaultArgument() &&
1169 DiagnoseDefaultTemplateArgument(*this, TPC,
1170 NewNonTypeParm->getLocation(),
1171 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1172 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1173 NewNonTypeParm->setDefaultArgument(0);
1174 }
1175
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001176 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001177 NonTypeTemplateParmDecl *OldNonTypeParm
1178 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001179 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001180 NewNonTypeParm->hasDefaultArgument()) {
1181 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1182 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1183 SawDefaultArgument = true;
1184 RedundantDefaultArg = true;
1185 PreviousDefaultArgLoc = NewDefaultLoc;
1186 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1187 // Merge the default argument from the old declaration to the
1188 // new declaration.
1189 SawDefaultArgument = true;
1190 // FIXME: We need to create a new kind of "default argument"
1191 // expression that points to a previous template template
1192 // parameter.
1193 NewNonTypeParm->setDefaultArgument(
1194 OldNonTypeParm->getDefaultArgument());
1195 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1196 } else if (NewNonTypeParm->hasDefaultArgument()) {
1197 SawDefaultArgument = true;
1198 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1199 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001200 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001201 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001202 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001203 TemplateTemplateParmDecl *NewTemplateParm
1204 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001205 if (NewTemplateParm->hasDefaultArgument() &&
1206 DiagnoseDefaultTemplateArgument(*this, TPC,
1207 NewTemplateParm->getLocation(),
1208 NewTemplateParm->getDefaultArgument().getSourceRange()))
1209 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1210
1211 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001212 TemplateTemplateParmDecl *OldTemplateParm
1213 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001214 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001215 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001216 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1217 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001218 SawDefaultArgument = true;
1219 RedundantDefaultArg = true;
1220 PreviousDefaultArgLoc = NewDefaultLoc;
1221 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1222 // Merge the default argument from the old declaration to the
1223 // new declaration.
1224 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001225 // FIXME: We need to create a new kind of "default argument" expression
1226 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001227 NewTemplateParm->setDefaultArgument(
1228 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001229 PreviousDefaultArgLoc
1230 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001231 } else if (NewTemplateParm->hasDefaultArgument()) {
1232 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001233 PreviousDefaultArgLoc
1234 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001235 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001236 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001237 }
1238
1239 if (RedundantDefaultArg) {
1240 // C++ [temp.param]p12:
1241 // A template-parameter shall not be given default arguments
1242 // by two different declarations in the same scope.
1243 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1244 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1245 Invalid = true;
1246 } else if (MissingDefaultArg) {
1247 // C++ [temp.param]p11:
1248 // If a template-parameter has a default template-argument,
1249 // all subsequent template-parameters shall have a default
1250 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001251 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001252 diag::err_template_param_default_arg_missing);
1253 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1254 Invalid = true;
1255 }
1256
1257 // If we have an old template parameter list that we're merging
1258 // in, move on to the next parameter.
1259 if (OldParams)
1260 ++OldParam;
1261 }
1262
1263 return Invalid;
1264}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001265
Mike Stump1eb44332009-09-09 15:08:12 +00001266/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001267/// specifier, returning the template parameter list that applies to the
1268/// name.
1269///
1270/// \param DeclStartLoc the start of the declaration that has a scope
1271/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001272///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001273/// \param SS the scope specifier that will be matched to the given template
1274/// parameter lists. This scope specifier precedes a qualified name that is
1275/// being declared.
1276///
1277/// \param ParamLists the template parameter lists, from the outermost to the
1278/// innermost template parameter lists.
1279///
1280/// \param NumParamLists the number of template parameter lists in ParamLists.
1281///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001282/// \param IsExplicitSpecialization will be set true if the entity being
1283/// declared is an explicit specialization, false otherwise.
1284///
Mike Stump1eb44332009-09-09 15:08:12 +00001285/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001286/// name that is preceded by the scope specifier @p SS. This template
1287/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001288/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001289/// template specialization), or may be NULL (if we were's declaring isn't
1290/// itself a template).
1291TemplateParameterList *
1292Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1293 const CXXScopeSpec &SS,
1294 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001295 unsigned NumParamLists,
1296 bool &IsExplicitSpecialization) {
1297 IsExplicitSpecialization = false;
1298
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001299 // Find the template-ids that occur within the nested-name-specifier. These
1300 // template-ids will match up with the template parameter lists.
1301 llvm::SmallVector<const TemplateSpecializationType *, 4>
1302 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001303 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1304 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001305 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1306 NNS; NNS = NNS->getPrefix()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001307 if (const TemplateSpecializationType *SpecType
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001308 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1309 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1310 if (!Template)
1311 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Ted Kremenek6217b802009-07-29 21:53:49 +00001313 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001314 ClassTemplateSpecializationDecl *SpecDecl
1315 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1316 // If the nested name specifier refers to an explicit specialization,
1317 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001318 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1319 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001320 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001321 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001322 }
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001324 TemplateIdsInSpecifier.push_back(SpecType);
1325 }
1326 }
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001328 // Reverse the list of template-ids in the scope specifier, so that we can
1329 // more easily match up the template-ids and the template parameter lists.
1330 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001332 SourceLocation FirstTemplateLoc = DeclStartLoc;
1333 if (NumParamLists)
1334 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001336 // Match the template-ids found in the specifier to the template parameter
1337 // lists.
1338 unsigned Idx = 0;
1339 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1340 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001341 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1342 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001343 if (Idx >= NumParamLists) {
1344 // We have a template-id without a corresponding template parameter
1345 // list.
1346 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001347 // FIXME: the location information here isn't great.
1348 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001349 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001350 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001351 << SS.getRange();
1352 } else {
1353 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1354 << SS.getRange()
1355 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1356 "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001357 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001358 }
1359 return 0;
1360 }
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001362 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001363 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001364 TemplateDecl *Template
Douglas Gregorb88e8882009-07-30 17:40:51 +00001365 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1366
Mike Stump1eb44332009-09-09 15:08:12 +00001367 if (ClassTemplateDecl *ClassTemplate
Douglas Gregorb88e8882009-07-30 17:40:51 +00001368 = dyn_cast<ClassTemplateDecl>(Template)) {
1369 TemplateParameterList *ExpectedTemplateParams = 0;
1370 // Is this template-id naming the primary template?
1371 if (Context.hasSameType(TemplateId,
1372 ClassTemplate->getInjectedClassNameType(Context)))
1373 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1374 // ... or a partial specialization?
1375 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1376 = ClassTemplate->findPartialSpecialization(TemplateId))
1377 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1378
1379 if (ExpectedTemplateParams)
Mike Stump1eb44332009-09-09 15:08:12 +00001380 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregorb88e8882009-07-30 17:40:51 +00001381 ExpectedTemplateParams,
Douglas Gregorfb898e12009-11-12 16:20:59 +00001382 true, TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00001383 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001384
1385 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001386 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001387 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001388 diag::err_template_param_list_matches_nontemplate)
1389 << TemplateId
1390 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001391 else
1392 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001393 }
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001395 // If there were at least as many template-ids as there were template
1396 // parameter lists, then there are no template parameter lists remaining for
1397 // the declaration itself.
1398 if (Idx >= NumParamLists)
1399 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001401 // If there were too many template parameter lists, complain about that now.
1402 if (Idx != NumParamLists - 1) {
1403 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001404 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001405 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001406 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1407 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001408 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1409 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001410
1411 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1412 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1413 diag::note_explicit_template_spec_does_not_need_header)
1414 << ExplicitSpecializationsInSpecifier.back();
1415 ExplicitSpecializationsInSpecifier.pop_back();
1416 }
1417
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001418 ++Idx;
1419 }
1420 }
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001422 // Return the last template parameter list, which corresponds to the
1423 // entity being declared.
1424 return ParamLists[NumParamLists - 1];
1425}
1426
Douglas Gregor7532dc62009-03-30 22:58:21 +00001427QualType Sema::CheckTemplateIdType(TemplateName Name,
1428 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001429 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001430 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001431 if (!Template) {
1432 // The template name does not resolve to a template, so we just
1433 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001434 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001435 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001436
Douglas Gregor40808ce2009-03-09 23:48:35 +00001437 // Check that the template argument list is well-formed for this
1438 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001439 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001440 TemplateArgs.size());
1441 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001442 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001443 return QualType();
1444
Mike Stump1eb44332009-09-09 15:08:12 +00001445 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001446 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001447 "Converted template argument list is too short!");
1448
1449 QualType CanonType;
1450
Douglas Gregorcaddba02009-11-12 18:38:13 +00001451 if (Name.isDependent() ||
1452 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001453 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001454 // This class template specialization is a dependent
1455 // type. Therefore, its canonical type is another class template
1456 // specialization type that contains all of the converted
1457 // arguments in canonical form. This ensures that, e.g., A<T> and
1458 // A<T, T> have identical types when A is declared as:
1459 //
1460 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001461 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001462 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001463 Converted.getFlatArguments(),
1464 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Douglas Gregor1275ae02009-07-28 23:00:59 +00001466 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001467 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001468 // In the future, we need to teach getTemplateSpecializationType to only
1469 // build the canonical type and return that to us.
1470 CanonType = Context.getCanonicalType(CanonType);
Mike Stump1eb44332009-09-09 15:08:12 +00001471 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001472 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001473 // Find the class template specialization declaration that
1474 // corresponds to these arguments.
1475 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001476 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001477 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001478 Converted.flatSize(),
1479 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001480 void *InsertPos = 0;
1481 ClassTemplateSpecializationDecl *Decl
1482 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1483 if (!Decl) {
1484 // This is the first time we have referenced this class template
1485 // specialization. Create the canonical declaration and add it to
1486 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001487 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001488 ClassTemplate->getDeclContext(),
John McCall9cc78072009-09-11 07:25:08 +00001489 ClassTemplate->getLocation(),
Anders Carlsson1c5976e2009-06-05 03:43:12 +00001490 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00001491 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001492 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1493 Decl->setLexicalDeclContext(CurContext);
1494 }
1495
1496 CanonType = Context.getTypeDeclType(Decl);
1497 }
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Douglas Gregor40808ce2009-03-09 23:48:35 +00001499 // Build the fully-sugared type for this class template
1500 // specialization, which refers back to the class template
1501 // specialization we created or found.
John McCalld5532b62009-11-23 01:53:49 +00001502 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001503}
1504
Douglas Gregorcc636682009-02-17 23:15:12 +00001505Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001506Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001507 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001508 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001509 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001510 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001511
Douglas Gregor40808ce2009-03-09 23:48:35 +00001512 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001513 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001514 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001515
John McCalld5532b62009-11-23 01:53:49 +00001516 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001517 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001518
1519 if (Result.isNull())
1520 return true;
1521
John McCall833ca992009-10-29 08:12:44 +00001522 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1523 TemplateSpecializationTypeLoc TL
1524 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1525 TL.setTemplateNameLoc(TemplateLoc);
1526 TL.setLAngleLoc(LAngleLoc);
1527 TL.setRAngleLoc(RAngleLoc);
1528 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1529 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1530
1531 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001532}
John McCallf1bbbb42009-09-04 01:14:41 +00001533
John McCall6b2becf2009-09-08 17:47:29 +00001534Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1535 TagUseKind TUK,
1536 DeclSpec::TST TagSpec,
1537 SourceLocation TagLoc) {
1538 if (TypeResult.isInvalid())
1539 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001540
John McCall833ca992009-10-29 08:12:44 +00001541 // FIXME: preserve source info, ideally without copying the DI.
1542 DeclaratorInfo *DI;
1543 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001544
John McCall6b2becf2009-09-08 17:47:29 +00001545 // Verify the tag specifier.
1546 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
John McCall6b2becf2009-09-08 17:47:29 +00001548 if (const RecordType *RT = Type->getAs<RecordType>()) {
1549 RecordDecl *D = RT->getDecl();
1550
1551 IdentifierInfo *Id = D->getIdentifier();
1552 assert(Id && "templated class must have an identifier");
1553
1554 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1555 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001556 << Type
John McCall6b2becf2009-09-08 17:47:29 +00001557 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1558 D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001559 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001560 }
1561 }
1562
John McCall6b2becf2009-09-08 17:47:29 +00001563 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1564
1565 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001566}
1567
John McCallf7a1a742009-11-24 19:00:30 +00001568Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1569 LookupResult &R,
1570 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001571 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001572 // FIXME: Can we do any checking at this point? I guess we could check the
1573 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001574 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001575 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001576
1577 // These should be filtered out by our callers.
1578 assert(!R.empty() && "empty lookup results when building templateid");
1579 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1580
1581 NestedNameSpecifier *Qualifier = 0;
1582 SourceRange QualifierRange;
1583 if (SS.isSet()) {
1584 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1585 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001586 }
1587
John McCallf7a1a742009-11-24 19:00:30 +00001588 bool Dependent
1589 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1590 &TemplateArgs);
1591 UnresolvedLookupExpr *ULE
1592 = UnresolvedLookupExpr::Create(Context, Dependent,
1593 Qualifier, QualifierRange,
1594 R.getLookupName(), R.getNameLoc(),
1595 RequiresADL, TemplateArgs);
1596 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1597 ULE->addDecl(*I);
1598
1599 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001600}
1601
John McCallf7a1a742009-11-24 19:00:30 +00001602// We actually only call this from template instantiation.
1603Sema::OwningExprResult
1604Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1605 DeclarationName Name,
1606 SourceLocation NameLoc,
1607 const TemplateArgumentListInfo &TemplateArgs) {
1608 DeclContext *DC;
1609 if (!(DC = computeDeclContext(SS, false)) ||
1610 DC->isDependentContext() ||
1611 RequireCompleteDeclContext(SS))
1612 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001613
John McCallf7a1a742009-11-24 19:00:30 +00001614 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1615 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00001616
John McCallf7a1a742009-11-24 19:00:30 +00001617 if (R.isAmbiguous())
1618 return ExprError();
1619
1620 if (R.empty()) {
1621 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1622 << Name << SS.getRange();
1623 return ExprError();
1624 }
1625
1626 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1627 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1628 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1629 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1630 return ExprError();
1631 }
1632
1633 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001634}
1635
Douglas Gregorc45c2322009-03-31 00:43:58 +00001636/// \brief Form a dependent template name.
1637///
1638/// This action forms a dependent template name given the template
1639/// name and its (presumably dependent) scope specifier. For
1640/// example, given "MetaFun::template apply", the scope specifier \p
1641/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1642/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001643Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001644Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001645 const CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001646 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001647 TypeTy *ObjectType,
1648 bool EnteringContext) {
Mike Stump1eb44332009-09-09 15:08:12 +00001649 if ((ObjectType &&
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001650 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregora481edb2009-11-20 23:39:24 +00001651 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001652 // C++0x [temp.names]p5:
1653 // If a name prefixed by the keyword template is not the name of
1654 // a template, the program is ill-formed. [Note: the keyword
1655 // template may not be applied to non-template members of class
1656 // templates. -end note ] [ Note: as is the case with the
1657 // typename prefix, the template prefix is allowed in cases
1658 // where it is not strictly necessary; i.e., when the
1659 // nested-name-specifier or the expression on the left of the ->
1660 // or . is not dependent on a template-parameter, or the use
1661 // does not appear in the scope of a template. -end note]
1662 //
1663 // Note: C++03 was more strict here, because it banned the use of
1664 // the "template" keyword prior to a template-name that was not a
1665 // dependent name. C++ DR468 relaxed this requirement (the
1666 // "template" keyword is now permitted). We follow the C++0x
1667 // rules, even in C++03 mode, retroactively applying the DR.
1668 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001669 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregora481edb2009-11-20 23:39:24 +00001670 EnteringContext, Template);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001671 if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001672 Diag(Name.getSourceRange().getBegin(),
1673 diag::err_template_kw_refers_to_non_template)
1674 << GetNameFromUnqualifiedId(Name)
1675 << Name.getSourceRange();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001676 return TemplateTy();
1677 }
1678
1679 return Template;
1680 }
1681
Mike Stump1eb44332009-09-09 15:08:12 +00001682 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001683 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001684
1685 switch (Name.getKind()) {
1686 case UnqualifiedId::IK_Identifier:
1687 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1688 Name.Identifier));
1689
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001690 case UnqualifiedId::IK_OperatorFunctionId:
1691 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1692 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001693
1694 case UnqualifiedId::IK_LiteralOperatorId:
1695 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1696
Douglas Gregor014e88d2009-11-03 23:16:33 +00001697 default:
1698 break;
1699 }
1700
1701 Diag(Name.getSourceRange().getBegin(),
1702 diag::err_template_kw_refers_to_non_template)
1703 << GetNameFromUnqualifiedId(Name)
1704 << Name.getSourceRange();
1705 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001706}
1707
Mike Stump1eb44332009-09-09 15:08:12 +00001708bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001709 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001710 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001711 const TemplateArgument &Arg = AL.getArgument();
1712
Anders Carlsson436b1562009-06-13 00:33:33 +00001713 // Check template type parameter.
1714 if (Arg.getKind() != TemplateArgument::Type) {
1715 // C++ [temp.arg.type]p1:
1716 // A template-argument for a template-parameter which is a
1717 // type shall be a type-id.
1718
1719 // We have a template type parameter but the template argument
1720 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001721 SourceRange SR = AL.getSourceRange();
1722 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001723 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Anders Carlsson436b1562009-06-13 00:33:33 +00001725 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001726 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001727
John McCall833ca992009-10-29 08:12:44 +00001728 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001729 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Anders Carlsson436b1562009-06-13 00:33:33 +00001731 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001732 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001733 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001734 return false;
1735}
1736
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001737/// \brief Substitute template arguments into the default template argument for
1738/// the given template type 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///
1752/// \param Param the template template parameter whose default we are
1753/// 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 DeclaratorInfo *
1760SubstDefaultTemplateArgument(Sema &SemaRef,
1761 TemplateDecl *Template,
1762 SourceLocation TemplateLoc,
1763 SourceLocation RAngleLoc,
1764 TemplateTypeParmDecl *Param,
1765 TemplateArgumentListBuilder &Converted) {
1766 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1767
1768 // If the argument type is dependent, instantiate it now based
1769 // on the previously-computed template arguments.
1770 if (ArgType->getType()->isDependentType()) {
1771 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1772 /*TakeArgs=*/false);
1773
1774 MultiLevelTemplateArgumentList AllTemplateArgs
1775 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1776
1777 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1778 Template, Converted.getFlatArguments(),
1779 Converted.flatSize(),
1780 SourceRange(TemplateLoc, RAngleLoc));
1781
1782 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1783 Param->getDefaultArgumentLoc(),
1784 Param->getDeclName());
1785 }
1786
1787 return ArgType;
1788}
1789
1790/// \brief Substitute template arguments into the default template argument for
1791/// the given non-type template parameter.
1792///
1793/// \param SemaRef the semantic analysis object for which we are performing
1794/// the substitution.
1795///
1796/// \param Template the template that we are synthesizing template arguments
1797/// for.
1798///
1799/// \param TemplateLoc the location of the template name that started the
1800/// template-id we are checking.
1801///
1802/// \param RAngleLoc the location of the right angle bracket ('>') that
1803/// terminates the template-id.
1804///
Douglas Gregor788cd062009-11-11 01:00:40 +00001805/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001806/// substituting into.
1807///
1808/// \param Converted the list of template arguments provided for template
1809/// parameters that precede \p Param in the template parameter list.
1810///
1811/// \returns the substituted template argument, or NULL if an error occurred.
1812static Sema::OwningExprResult
1813SubstDefaultTemplateArgument(Sema &SemaRef,
1814 TemplateDecl *Template,
1815 SourceLocation TemplateLoc,
1816 SourceLocation RAngleLoc,
1817 NonTypeTemplateParmDecl *Param,
1818 TemplateArgumentListBuilder &Converted) {
1819 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1820 /*TakeArgs=*/false);
1821
1822 MultiLevelTemplateArgumentList AllTemplateArgs
1823 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1824
1825 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1826 Template, Converted.getFlatArguments(),
1827 Converted.flatSize(),
1828 SourceRange(TemplateLoc, RAngleLoc));
1829
1830 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1831}
1832
Douglas Gregor788cd062009-11-11 01:00:40 +00001833/// \brief Substitute template arguments into the default template argument for
1834/// the given template template parameter.
1835///
1836/// \param SemaRef the semantic analysis object for which we are performing
1837/// the substitution.
1838///
1839/// \param Template the template that we are synthesizing template arguments
1840/// for.
1841///
1842/// \param TemplateLoc the location of the template name that started the
1843/// template-id we are checking.
1844///
1845/// \param RAngleLoc the location of the right angle bracket ('>') that
1846/// terminates the template-id.
1847///
1848/// \param Param the template template parameter whose default we are
1849/// substituting into.
1850///
1851/// \param Converted the list of template arguments provided for template
1852/// parameters that precede \p Param in the template parameter list.
1853///
1854/// \returns the substituted template argument, or NULL if an error occurred.
1855static TemplateName
1856SubstDefaultTemplateArgument(Sema &SemaRef,
1857 TemplateDecl *Template,
1858 SourceLocation TemplateLoc,
1859 SourceLocation RAngleLoc,
1860 TemplateTemplateParmDecl *Param,
1861 TemplateArgumentListBuilder &Converted) {
1862 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1863 /*TakeArgs=*/false);
1864
1865 MultiLevelTemplateArgumentList AllTemplateArgs
1866 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1867
1868 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1869 Template, Converted.getFlatArguments(),
1870 Converted.flatSize(),
1871 SourceRange(TemplateLoc, RAngleLoc));
1872
1873 return SemaRef.SubstTemplateName(
1874 Param->getDefaultArgument().getArgument().getAsTemplate(),
1875 Param->getDefaultArgument().getTemplateNameLoc(),
1876 AllTemplateArgs);
1877}
1878
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001879/// \brief If the given template parameter has a default template
1880/// argument, substitute into that default template argument and
1881/// return the corresponding template argument.
1882TemplateArgumentLoc
1883Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1884 SourceLocation TemplateLoc,
1885 SourceLocation RAngleLoc,
1886 Decl *Param,
1887 TemplateArgumentListBuilder &Converted) {
1888 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1889 if (!TypeParm->hasDefaultArgument())
1890 return TemplateArgumentLoc();
1891
1892 DeclaratorInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1893 TemplateLoc,
1894 RAngleLoc,
1895 TypeParm,
1896 Converted);
1897 if (DI)
1898 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1899
1900 return TemplateArgumentLoc();
1901 }
1902
1903 if (NonTypeTemplateParmDecl *NonTypeParm
1904 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1905 if (!NonTypeParm->hasDefaultArgument())
1906 return TemplateArgumentLoc();
1907
1908 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1909 TemplateLoc,
1910 RAngleLoc,
1911 NonTypeParm,
1912 Converted);
1913 if (Arg.isInvalid())
1914 return TemplateArgumentLoc();
1915
1916 Expr *ArgE = Arg.takeAs<Expr>();
1917 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1918 }
1919
1920 TemplateTemplateParmDecl *TempTempParm
1921 = cast<TemplateTemplateParmDecl>(Param);
1922 if (!TempTempParm->hasDefaultArgument())
1923 return TemplateArgumentLoc();
1924
1925 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1926 TemplateLoc,
1927 RAngleLoc,
1928 TempTempParm,
1929 Converted);
1930 if (TName.isNull())
1931 return TemplateArgumentLoc();
1932
1933 return TemplateArgumentLoc(TemplateArgument(TName),
1934 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1935 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1936}
1937
Douglas Gregore7526412009-11-11 19:31:23 +00001938/// \brief Check that the given template argument corresponds to the given
1939/// template parameter.
1940bool Sema::CheckTemplateArgument(NamedDecl *Param,
1941 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00001942 TemplateDecl *Template,
1943 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00001944 SourceLocation RAngleLoc,
1945 TemplateArgumentListBuilder &Converted) {
Douglas Gregord9e15302009-11-11 19:41:09 +00001946 // Check template type parameters.
1947 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00001948 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00001949
Douglas Gregord9e15302009-11-11 19:41:09 +00001950 // Check non-type template parameters.
1951 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00001952 // Do substitution on the type of the non-type template parameter
1953 // with the template arguments we've seen thus far.
1954 QualType NTTPType = NTTP->getType();
1955 if (NTTPType->isDependentType()) {
1956 // Do substitution on the type of the non-type template parameter.
1957 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1958 NTTP, Converted.getFlatArguments(),
1959 Converted.flatSize(),
1960 SourceRange(TemplateLoc, RAngleLoc));
1961
1962 TemplateArgumentList TemplateArgs(Context, Converted,
1963 /*TakeArgs=*/false);
1964 NTTPType = SubstType(NTTPType,
1965 MultiLevelTemplateArgumentList(TemplateArgs),
1966 NTTP->getLocation(),
1967 NTTP->getDeclName());
1968 // If that worked, check the non-type template parameter type
1969 // for validity.
1970 if (!NTTPType.isNull())
1971 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1972 NTTP->getLocation());
1973 if (NTTPType.isNull())
1974 return true;
1975 }
1976
1977 switch (Arg.getArgument().getKind()) {
1978 case TemplateArgument::Null:
1979 assert(false && "Should never see a NULL template argument here");
1980 return true;
1981
1982 case TemplateArgument::Expression: {
1983 Expr *E = Arg.getArgument().getAsExpr();
1984 TemplateArgument Result;
1985 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1986 return true;
1987
1988 Converted.Append(Result);
1989 break;
1990 }
1991
1992 case TemplateArgument::Declaration:
1993 case TemplateArgument::Integral:
1994 // We've already checked this template argument, so just copy
1995 // it to the list of converted arguments.
1996 Converted.Append(Arg.getArgument());
1997 break;
1998
1999 case TemplateArgument::Template:
2000 // We were given a template template argument. It may not be ill-formed;
2001 // see below.
2002 if (DependentTemplateName *DTN
2003 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2004 // We have a template argument such as \c T::template X, which we
2005 // parsed as a template template argument. However, since we now
2006 // know that we need a non-type template argument, convert this
2007 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00002008 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2009 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002010 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00002011 DTN->getIdentifier(),
2012 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00002013
2014 TemplateArgument Result;
2015 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2016 return true;
2017
2018 Converted.Append(Result);
2019 break;
2020 }
2021
2022 // We have a template argument that actually does refer to a class
2023 // template, template alias, or template template parameter, and
2024 // therefore cannot be a non-type template argument.
2025 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2026 << Arg.getSourceRange();
2027
2028 Diag(Param->getLocation(), diag::note_template_param_here);
2029 return true;
2030
2031 case TemplateArgument::Type: {
2032 // We have a non-type template parameter but the template
2033 // argument is a type.
2034
2035 // C++ [temp.arg]p2:
2036 // In a template-argument, an ambiguity between a type-id and
2037 // an expression is resolved to a type-id, regardless of the
2038 // form of the corresponding template-parameter.
2039 //
2040 // We warn specifically about this case, since it can be rather
2041 // confusing for users.
2042 QualType T = Arg.getArgument().getAsType();
2043 SourceRange SR = Arg.getSourceRange();
2044 if (T->isFunctionType())
2045 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2046 else
2047 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2048 Diag(Param->getLocation(), diag::note_template_param_here);
2049 return true;
2050 }
2051
2052 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00002053 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002054 break;
2055 }
2056
2057 return false;
2058 }
2059
2060
2061 // Check template template parameters.
2062 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2063
2064 // Substitute into the template parameter list of the template
2065 // template parameter, since previously-supplied template arguments
2066 // may appear within the template template parameter.
2067 {
2068 // Set up a template instantiation context.
2069 LocalInstantiationScope Scope(*this);
2070 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2071 TempParm, Converted.getFlatArguments(),
2072 Converted.flatSize(),
2073 SourceRange(TemplateLoc, RAngleLoc));
2074
2075 TemplateArgumentList TemplateArgs(Context, Converted,
2076 /*TakeArgs=*/false);
2077 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2078 SubstDecl(TempParm, CurContext,
2079 MultiLevelTemplateArgumentList(TemplateArgs)));
2080 if (!TempParm)
2081 return true;
2082
2083 // FIXME: TempParam is leaked.
2084 }
2085
2086 switch (Arg.getArgument().getKind()) {
2087 case TemplateArgument::Null:
2088 assert(false && "Should never see a NULL template argument here");
2089 return true;
2090
2091 case TemplateArgument::Template:
2092 if (CheckTemplateArgument(TempParm, Arg))
2093 return true;
2094
2095 Converted.Append(Arg.getArgument());
2096 break;
2097
2098 case TemplateArgument::Expression:
2099 case TemplateArgument::Type:
2100 // We have a template template parameter but the template
2101 // argument does not refer to a template.
2102 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2103 return true;
2104
2105 case TemplateArgument::Declaration:
2106 llvm::llvm_unreachable(
2107 "Declaration argument with template template parameter");
2108 break;
2109 case TemplateArgument::Integral:
2110 llvm::llvm_unreachable(
2111 "Integral argument with template template parameter");
2112 break;
2113
2114 case TemplateArgument::Pack:
Douglas Gregord9e15302009-11-11 19:41:09 +00002115 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002116 break;
2117 }
2118
2119 return false;
2120}
2121
Douglas Gregorc15cb382009-02-09 23:23:08 +00002122/// \brief Check that the given template argument list is well-formed
2123/// for specializing the given template.
2124bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2125 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002126 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002127 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002128 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002129 TemplateParameterList *Params = Template->getTemplateParameters();
2130 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002131 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002132 bool Invalid = false;
2133
John McCalld5532b62009-11-23 01:53:49 +00002134 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2135
Mike Stump1eb44332009-09-09 15:08:12 +00002136 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002137 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002139 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002140 (NumArgs < Params->getMinRequiredArguments() &&
2141 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002142 // FIXME: point at either the first arg beyond what we can handle,
2143 // or the '>', depending on whether we have too many or too few
2144 // arguments.
2145 SourceRange Range;
2146 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002147 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002148 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2149 << (NumArgs > NumParams)
2150 << (isa<ClassTemplateDecl>(Template)? 0 :
2151 isa<FunctionTemplateDecl>(Template)? 1 :
2152 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2153 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002154 Diag(Template->getLocation(), diag::note_template_decl_here)
2155 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002156 Invalid = true;
2157 }
Mike Stump1eb44332009-09-09 15:08:12 +00002158
2159 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002160 // [...] The type and form of each template-argument specified in
2161 // a template-id shall match the type and form specified for the
2162 // corresponding parameter declared by the template in its
2163 // template-parameter-list.
2164 unsigned ArgIdx = 0;
2165 for (TemplateParameterList::iterator Param = Params->begin(),
2166 ParamEnd = Params->end();
2167 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002168 if (ArgIdx > NumArgs && PartialTemplateArgs)
2169 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Douglas Gregord9e15302009-11-11 19:41:09 +00002171 // If we have a template parameter pack, check every remaining template
2172 // argument against that template parameter pack.
2173 if ((*Param)->isTemplateParameterPack()) {
2174 Converted.BeginPack();
2175 for (; ArgIdx < NumArgs; ++ArgIdx) {
2176 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2177 TemplateLoc, RAngleLoc, Converted)) {
2178 Invalid = true;
2179 break;
2180 }
2181 }
2182 Converted.EndPack();
2183 continue;
2184 }
2185
Douglas Gregorf35f8282009-11-11 21:54:23 +00002186 if (ArgIdx < NumArgs) {
2187 // Check the template argument we were given.
2188 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2189 TemplateLoc, RAngleLoc, Converted))
2190 return true;
2191
2192 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002193 }
Douglas Gregore7526412009-11-11 19:31:23 +00002194
Douglas Gregorf35f8282009-11-11 21:54:23 +00002195 // We have a default template argument that we will use.
2196 TemplateArgumentLoc Arg;
2197
2198 // Retrieve the default template argument from the template
2199 // parameter. For each kind of template parameter, we substitute the
2200 // template arguments provided thus far and any "outer" template arguments
2201 // (when the template parameter was part of a nested template) into
2202 // the default argument.
2203 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2204 if (!TTP->hasDefaultArgument()) {
2205 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2206 break;
2207 }
2208
2209 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
2210 Template,
2211 TemplateLoc,
2212 RAngleLoc,
2213 TTP,
2214 Converted);
2215 if (!ArgType)
2216 return true;
2217
2218 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2219 ArgType);
2220 } else if (NonTypeTemplateParmDecl *NTTP
2221 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2222 if (!NTTP->hasDefaultArgument()) {
2223 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2224 break;
2225 }
2226
2227 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2228 TemplateLoc,
2229 RAngleLoc,
2230 NTTP,
2231 Converted);
2232 if (E.isInvalid())
2233 return true;
2234
2235 Expr *Ex = E.takeAs<Expr>();
2236 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2237 } else {
2238 TemplateTemplateParmDecl *TempParm
2239 = cast<TemplateTemplateParmDecl>(*Param);
2240
2241 if (!TempParm->hasDefaultArgument()) {
2242 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2243 break;
2244 }
2245
2246 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2247 TemplateLoc,
2248 RAngleLoc,
2249 TempParm,
2250 Converted);
2251 if (Name.isNull())
2252 return true;
2253
2254 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2255 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2256 TempParm->getDefaultArgument().getTemplateNameLoc());
2257 }
2258
2259 // Introduce an instantiation record that describes where we are using
2260 // the default template argument.
2261 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2262 Converted.getFlatArguments(),
2263 Converted.flatSize(),
2264 SourceRange(TemplateLoc, RAngleLoc));
2265
2266 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002267 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002268 RAngleLoc, Converted))
2269 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002270 }
2271
2272 return Invalid;
2273}
2274
2275/// \brief Check a template argument against its corresponding
2276/// template type parameter.
2277///
2278/// This routine implements the semantics of C++ [temp.arg.type]. It
2279/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002280bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00002281 DeclaratorInfo *ArgInfo) {
2282 assert(ArgInfo && "invalid DeclaratorInfo");
2283 QualType Arg = ArgInfo->getType();
2284
Douglas Gregorc15cb382009-02-09 23:23:08 +00002285 // C++ [temp.arg.type]p2:
2286 // A local type, a type with no linkage, an unnamed type or a type
2287 // compounded from any of these types shall not be used as a
2288 // template-argument for a template type-parameter.
2289 //
2290 // FIXME: Perform the recursive and no-linkage type checks.
2291 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002292 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002293 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002294 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002295 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002296 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2297 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2298 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2299 << QualType(Tag, 0) << SR;
2300 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002301 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002302 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2303 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002304 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2305 return true;
2306 }
2307
2308 return false;
2309}
2310
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002311/// \brief Checks whether the given template argument is the address
2312/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002313bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2314 NamedDecl *&Entity) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002315 bool Invalid = false;
2316
2317 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002318 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002319 Arg = Cast->getSubExpr();
2320
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002321 // C++0x allows nullptr, and there's no further checking to be done for that.
2322 if (Arg->getType()->isNullPtrType())
2323 return false;
2324
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002325 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002326 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002327 // A template-argument for a non-type, non-template
2328 // template-parameter shall be one of: [...]
2329 //
2330 // -- the address of an object or function with external
2331 // linkage, including function templates and function
2332 // template-ids but excluding non-static class members,
2333 // expressed as & id-expression where the & is optional if
2334 // the name refers to a function or array, or if the
2335 // corresponding template-parameter is a reference; or
2336 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002338 // Ignore (and complain about) any excess parentheses.
2339 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2340 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002341 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002342 diag::err_template_arg_extra_parens)
2343 << Arg->getSourceRange();
2344 Invalid = true;
2345 }
2346
2347 Arg = Parens->getSubExpr();
2348 }
2349
2350 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2351 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2352 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2353 } else
2354 DRE = dyn_cast<DeclRefExpr>(Arg);
2355
2356 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002357 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002358 diag::err_template_arg_not_object_or_func_form)
2359 << Arg->getSourceRange();
2360
2361 // Cannot refer to non-static data members
2362 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2363 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2364 << Field << Arg->getSourceRange();
2365
2366 // Cannot refer to non-static member functions
2367 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2368 if (!Method->isStatic())
Mike Stump1eb44332009-09-09 15:08:12 +00002369 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002370 diag::err_template_arg_method)
2371 << Method << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002373 // Functions must have external linkage.
2374 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002375 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002376 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002377 diag::err_template_arg_function_not_extern)
2378 << Func << Arg->getSourceRange();
2379 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2380 << true;
2381 return true;
2382 }
2383
2384 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002385 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002386 return Invalid;
2387 }
2388
2389 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregord85b5b92009-11-25 22:24:25 +00002390 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump1eb44332009-09-09 15:08:12 +00002391 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002392 diag::err_template_arg_object_not_extern)
2393 << Var << Arg->getSourceRange();
2394 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2395 << true;
2396 return true;
2397 }
2398
2399 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002400 Entity = Var;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002401 return Invalid;
2402 }
Mike Stump1eb44332009-09-09 15:08:12 +00002403
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002404 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002405 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002406 diag::err_template_arg_not_object_or_func)
2407 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002408 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002409 diag::note_template_arg_refers_here);
2410 return true;
2411}
2412
2413/// \brief Checks whether the given template argument is a pointer to
2414/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002415bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2416 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002417 bool Invalid = false;
2418
2419 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002420 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002421 Arg = Cast->getSubExpr();
2422
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002423 // C++0x allows nullptr, and there's no further checking to be done for that.
2424 if (Arg->getType()->isNullPtrType())
2425 return false;
2426
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002427 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002428 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002429 // A template-argument for a non-type, non-template
2430 // template-parameter shall be one of: [...]
2431 //
2432 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002433 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002434
2435 // Ignore (and complain about) any excess parentheses.
2436 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2437 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002438 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002439 diag::err_template_arg_extra_parens)
2440 << Arg->getSourceRange();
2441 Invalid = true;
2442 }
2443
2444 Arg = Parens->getSubExpr();
2445 }
2446
Douglas Gregorcaddba02009-11-12 18:38:13 +00002447 // A pointer-to-member constant written &Class::member.
2448 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002449 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2450 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2451 if (DRE && !DRE->getQualifier())
2452 DRE = 0;
2453 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002454 }
2455 // A constant of pointer-to-member type.
2456 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2457 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2458 if (VD->getType()->isMemberPointerType()) {
2459 if (isa<NonTypeTemplateParmDecl>(VD) ||
2460 (isa<VarDecl>(VD) &&
2461 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2462 if (Arg->isTypeDependent() || Arg->isValueDependent())
2463 Converted = TemplateArgument(Arg->Retain());
2464 else
2465 Converted = TemplateArgument(VD->getCanonicalDecl());
2466 return Invalid;
2467 }
2468 }
2469 }
2470
2471 DRE = 0;
2472 }
2473
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002474 if (!DRE)
2475 return Diag(Arg->getSourceRange().getBegin(),
2476 diag::err_template_arg_not_pointer_to_member_form)
2477 << Arg->getSourceRange();
2478
2479 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2480 assert((isa<FieldDecl>(DRE->getDecl()) ||
2481 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2482 "Only non-static member pointers can make it here");
2483
2484 // Okay: this is the address of a non-static member, and therefore
2485 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002486 if (Arg->isTypeDependent() || Arg->isValueDependent())
2487 Converted = TemplateArgument(Arg->Retain());
2488 else
2489 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002490 return Invalid;
2491 }
2492
2493 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002494 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002495 diag::err_template_arg_not_pointer_to_member_form)
2496 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002497 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002498 diag::note_template_arg_refers_here);
2499 return true;
2500}
2501
Douglas Gregorc15cb382009-02-09 23:23:08 +00002502/// \brief Check a template argument against its corresponding
2503/// non-type template parameter.
2504///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002505/// This routine implements the semantics of C++ [temp.arg.nontype].
2506/// It returns true if an error occurred, and false otherwise. \p
2507/// InstantiatedParamType is the type of the non-type template
2508/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002509///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002510/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002511bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002512 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002513 TemplateArgument &Converted) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002514 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2515
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002516 // If either the parameter has a dependent type or the argument is
2517 // type-dependent, there's nothing we can check now.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002518 // FIXME: Add template argument to Converted!
Douglas Gregor40808ce2009-03-09 23:48:35 +00002519 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2520 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002521 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002522 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002523 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002524
2525 // C++ [temp.arg.nontype]p5:
2526 // The following conversions are performed on each expression used
2527 // as a non-type template-argument. If a non-type
2528 // template-argument cannot be converted to the type of the
2529 // corresponding template-parameter then the program is
2530 // ill-formed.
2531 //
2532 // -- for a non-type template-parameter of integral or
2533 // enumeration type, integral promotions (4.5) and integral
2534 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002535 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002536 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002537 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002538 // C++ [temp.arg.nontype]p1:
2539 // A template-argument for a non-type, non-template
2540 // template-parameter shall be one of:
2541 //
2542 // -- an integral constant-expression of integral or enumeration
2543 // type; or
2544 // -- the name of a non-type template-parameter; or
2545 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002546 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002547 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002548 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002549 diag::err_template_arg_not_integral_or_enumeral)
2550 << ArgType << Arg->getSourceRange();
2551 Diag(Param->getLocation(), diag::note_template_param_here);
2552 return true;
2553 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002554 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002555 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2556 << ArgType << Arg->getSourceRange();
2557 return true;
2558 }
2559
2560 // FIXME: We need some way to more easily get the unqualified form
2561 // of the types without going all the way to the
2562 // canonical type.
2563 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2564 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2565 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2566 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2567
2568 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002569 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002570 // Okay: no conversion necessary
2571 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2572 !ParamType->isEnumeralType()) {
2573 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002574 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002575 } else {
2576 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002577 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002578 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002579 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002580 Diag(Param->getLocation(), diag::note_template_param_here);
2581 return true;
2582 }
2583
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002584 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002585 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002586 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002587
2588 if (!Arg->isValueDependent()) {
2589 // Check that an unsigned parameter does not receive a negative
2590 // value.
2591 if (IntegerType->isUnsignedIntegerType()
2592 && (Value.isSigned() && Value.isNegative())) {
2593 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2594 << Value.toString(10) << Param->getType()
2595 << Arg->getSourceRange();
2596 Diag(Param->getLocation(), diag::note_template_param_here);
2597 return true;
2598 }
2599
2600 // Check that we don't overflow the template parameter type.
2601 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2602 if (Value.getActiveBits() > AllowedBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00002603 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002604 diag::err_template_arg_too_large)
2605 << Value.toString(10) << Param->getType()
2606 << Arg->getSourceRange();
2607 Diag(Param->getLocation(), diag::note_template_param_here);
2608 return true;
2609 }
2610
2611 if (Value.getBitWidth() != AllowedBits)
2612 Value.extOrTrunc(AllowedBits);
2613 Value.setIsSigned(IntegerType->isSignedIntegerType());
2614 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002615
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002616 // Add the value of this argument to the list of converted
2617 // arguments. We use the bitwidth and signedness of the template
2618 // parameter.
2619 if (Arg->isValueDependent()) {
2620 // The argument is value-dependent. Create a new
2621 // TemplateArgument with the converted expression.
2622 Converted = TemplateArgument(Arg);
2623 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002624 }
2625
John McCall833ca992009-10-29 08:12:44 +00002626 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002627 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002628 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002629 return false;
2630 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002631
Douglas Gregorb86b0572009-02-11 01:18:59 +00002632 // Handle pointer-to-function, reference-to-function, and
2633 // pointer-to-member-function all in (roughly) the same way.
2634 if (// -- For a non-type template-parameter of type pointer to
2635 // function, only the function-to-pointer conversion (4.3) is
2636 // applied. If the template-argument represents a set of
2637 // overloaded functions (or a pointer to such), the matching
2638 // function is selected from the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002639 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002640 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002641 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002642 // -- For a non-type template-parameter of type reference to
2643 // function, no conversions apply. If the template-argument
2644 // represents a set of overloaded functions, the matching
2645 // function is selected from the set (13.4).
2646 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002647 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002648 // -- For a non-type template-parameter of type pointer to
2649 // member function, no conversions apply. If the
2650 // template-argument represents a set of overloaded member
2651 // functions, the matching member function is selected from
2652 // the set (13.4).
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002653 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregorb86b0572009-02-11 01:18:59 +00002654 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002655 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002656 ->isFunctionType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00002657 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002658 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002659 // We don't have to do anything: the types already match.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002660 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2661 ParamType->isMemberPointerType())) {
2662 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002663 if (ParamType->isMemberPointerType())
2664 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2665 else
2666 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002667 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002668 ArgType = Context.getPointerType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002669 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump1eb44332009-09-09 15:08:12 +00002670 } else if (FunctionDecl *Fn
Douglas Gregora35284b2009-02-11 00:19:33 +00002671 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002672 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2673 return true;
2674
Anders Carlsson96ad5332009-10-21 17:16:23 +00002675 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00002676 ArgType = Arg->getType();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002677 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002678 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman73c39ab2009-10-20 08:27:19 +00002679 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregora35284b2009-02-11 00:19:33 +00002680 }
2681 }
2682
Mike Stump1eb44332009-09-09 15:08:12 +00002683 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002684 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002685 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002686 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002687 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002688 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002689 Diag(Param->getLocation(), diag::note_template_param_here);
2690 return true;
2691 }
Mike Stump1eb44332009-09-09 15:08:12 +00002692
Douglas Gregorcaddba02009-11-12 18:38:13 +00002693 if (ParamType->isMemberPointerType())
2694 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002696 NamedDecl *Entity = 0;
2697 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2698 return true;
2699
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002700 if (Entity)
2701 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002702 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002703 return false;
Douglas Gregora35284b2009-02-11 00:19:33 +00002704 }
2705
Chris Lattnerfe90de72009-02-20 21:37:53 +00002706 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002707 // -- for a non-type template-parameter of type pointer to
2708 // object, qualification conversions (4.4) and the
2709 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002710 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002711 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002712 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002713
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002714 if (ArgType->isNullPtrType()) {
2715 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002716 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002717 } else if (ArgType->isArrayType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002718 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman73c39ab2009-10-20 08:27:19 +00002719 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002720 }
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002721
Douglas Gregorb86b0572009-02-11 01:18:59 +00002722 if (IsQualificationConversion(ArgType, ParamType)) {
2723 ArgType = ParamType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002724 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002725 }
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002727 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002728 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002729 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002730 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002731 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregorb86b0572009-02-11 01:18:59 +00002732 Diag(Param->getLocation(), diag::note_template_param_here);
2733 return true;
2734 }
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002736 NamedDecl *Entity = 0;
2737 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2738 return true;
2739
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002740 if (Entity)
2741 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002742 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002743 return false;
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002744 }
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Ted Kremenek6217b802009-07-29 21:53:49 +00002746 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002747 // -- For a non-type template-parameter of type reference to
2748 // object, no conversions apply. The type referred to by the
2749 // reference may be more cv-qualified than the (otherwise
2750 // identical) type of the template-argument. The
2751 // template-parameter is bound directly to the
2752 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002753 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002754 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002755
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002756 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002757 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00002758 diag::err_template_arg_no_ref_bind)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002759 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002760 << Arg->getSourceRange();
2761 Diag(Param->getLocation(), diag::note_template_param_here);
2762 return true;
2763 }
2764
Mike Stump1eb44332009-09-09 15:08:12 +00002765 unsigned ParamQuals
Douglas Gregorb86b0572009-02-11 01:18:59 +00002766 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2767 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Douglas Gregorb86b0572009-02-11 01:18:59 +00002769 if ((ParamQuals | ArgQuals) != ParamQuals) {
2770 Diag(Arg->getSourceRange().getBegin(),
2771 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002772 << InstantiatedParamType << Arg->getType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002773 << Arg->getSourceRange();
2774 Diag(Param->getLocation(), diag::note_template_param_here);
2775 return true;
2776 }
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002778 NamedDecl *Entity = 0;
2779 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2780 return true;
2781
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002782 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall833ca992009-10-29 08:12:44 +00002783 Converted = TemplateArgument(Entity);
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002784 return false;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002785 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002786
2787 // -- For a non-type template-parameter of type pointer to data
2788 // member, qualification conversions (4.4) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002789 // C++0x allows std::nullptr_t values.
Douglas Gregor658bbb52009-02-11 16:16:59 +00002790 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2791
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002792 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002793 // Types match exactly: nothing more to do here.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002794 } else if (ArgType->isNullPtrType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002795 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002796 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002797 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002798 } else {
2799 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002800 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002801 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002802 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002803 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00002804 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00002805 }
2806
Douglas Gregorcaddba02009-11-12 18:38:13 +00002807 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002808}
2809
2810/// \brief Check a template argument against its corresponding
2811/// template template parameter.
2812///
2813/// This routine implements the semantics of C++ [temp.arg.template].
2814/// It returns true if an error occurred, and false otherwise.
2815bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00002816 const TemplateArgumentLoc &Arg) {
2817 TemplateName Name = Arg.getArgument().getAsTemplate();
2818 TemplateDecl *Template = Name.getAsTemplateDecl();
2819 if (!Template) {
2820 // Any dependent template name is fine.
2821 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2822 return false;
2823 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002824
2825 // C++ [temp.arg.template]p1:
2826 // A template-argument for a template template-parameter shall be
2827 // the name of a class template, expressed as id-expression. Only
2828 // primary class templates are considered when matching the
2829 // template template argument with the corresponding parameter;
2830 // partial specializations are not considered even if their
2831 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002832 //
2833 // Note that we also allow template template parameters here, which
2834 // will happen when we are dealing with, e.g., class template
2835 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00002836 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00002837 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002838 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00002839 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00002840 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00002841 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002842 << Template;
2843 }
2844
2845 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2846 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00002847 true,
2848 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00002849 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00002850}
2851
Douglas Gregorddc29e12009-02-06 22:42:48 +00002852/// \brief Determine whether the given template parameter lists are
2853/// equivalent.
2854///
Mike Stump1eb44332009-09-09 15:08:12 +00002855/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00002856/// source code as part of a new template declaration.
2857///
2858/// \param Old The old template parameter list, typically found via
2859/// name lookup of the template declared with this template parameter
2860/// list.
2861///
2862/// \param Complain If true, this routine will produce a diagnostic if
2863/// the template parameter lists are not equivalent.
2864///
Douglas Gregorfb898e12009-11-12 16:20:59 +00002865/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00002866///
2867/// \param TemplateArgLoc If this source location is valid, then we
2868/// are actually checking the template parameter list of a template
2869/// argument (New) against the template parameter list of its
2870/// corresponding template template parameter (Old). We produce
2871/// slightly different diagnostics in this scenario.
2872///
Douglas Gregorddc29e12009-02-06 22:42:48 +00002873/// \returns True if the template parameter lists are equal, false
2874/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002875bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00002876Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2877 TemplateParameterList *Old,
2878 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002879 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002880 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002881 if (Old->size() != New->size()) {
2882 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002883 unsigned NextDiag = diag::err_template_param_list_different_arity;
2884 if (TemplateArgLoc.isValid()) {
2885 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2886 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00002887 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00002888 Diag(New->getTemplateLoc(), NextDiag)
2889 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00002890 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00002891 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00002892 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002893 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002894 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2895 }
2896
2897 return false;
2898 }
2899
2900 for (TemplateParameterList::iterator OldParm = Old->begin(),
2901 OldParmEnd = Old->end(), NewParm = New->begin();
2902 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2903 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002904 if (Complain) {
2905 unsigned NextDiag = diag::err_template_param_different_kind;
2906 if (TemplateArgLoc.isValid()) {
2907 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2908 NextDiag = diag::note_template_param_different_kind;
2909 }
2910 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002911 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00002912 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00002913 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00002914 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00002915 return false;
2916 }
2917
2918 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2919 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00002920 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00002921 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002922 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2923 // The types of non-type template parameters must agree.
2924 NonTypeTemplateParmDecl *NewNTTP
2925 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00002926
2927 // If we are matching a template template argument to a template
2928 // template parameter and one of the non-type template parameter types
2929 // is dependent, then we must wait until template instantiation time
2930 // to actually compare the arguments.
2931 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2932 (OldNTTP->getType()->isDependentType() ||
2933 NewNTTP->getType()->isDependentType()))
2934 continue;
2935
Douglas Gregorddc29e12009-02-06 22:42:48 +00002936 if (Context.getCanonicalType(OldNTTP->getType()) !=
2937 Context.getCanonicalType(NewNTTP->getType())) {
2938 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00002939 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2940 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002941 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00002942 diag::err_template_arg_template_params_mismatch);
2943 NextDiag = diag::note_template_nontype_parm_different_type;
2944 }
2945 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00002946 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00002947 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00002948 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00002949 diag::note_template_nontype_parm_prev_declaration)
2950 << OldNTTP->getType();
2951 }
2952 return false;
2953 }
2954 } else {
2955 // The template parameter lists of template template
2956 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00002957 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00002958 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00002959 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00002960 = cast<TemplateTemplateParmDecl>(*OldParm);
2961 TemplateTemplateParmDecl *NewTTP
2962 = cast<TemplateTemplateParmDecl>(*NewParm);
2963 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2964 OldTTP->getTemplateParameters(),
2965 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00002966 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00002967 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002968 return false;
2969 }
2970 }
2971
2972 return true;
2973}
2974
2975/// \brief Check whether a template can be declared within this scope.
2976///
2977/// If the template declaration is valid in this scope, returns
2978/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00002979bool
Douglas Gregor05396e22009-08-25 17:23:04 +00002980Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00002981 // Find the nearest enclosing declaration scope.
2982 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2983 (S->getFlags() & Scope::TemplateParamScope) != 0)
2984 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Douglas Gregorddc29e12009-02-06 22:42:48 +00002986 // C++ [temp]p2:
2987 // A template-declaration can appear only as a namespace scope or
2988 // class scope declaration.
2989 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00002990 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2991 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00002992 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00002993 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002994
Eli Friedman1503f772009-07-31 01:43:05 +00002995 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00002996 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00002997
2998 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2999 return false;
3000
Mike Stump1eb44332009-09-09 15:08:12 +00003001 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003002 diag::err_template_outside_namespace_or_class_scope)
3003 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003004}
Douglas Gregorcc636682009-02-17 23:15:12 +00003005
Douglas Gregord5cb8762009-10-07 00:13:32 +00003006/// \brief Determine what kind of template specialization the given declaration
3007/// is.
3008static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3009 if (!D)
3010 return TSK_Undeclared;
3011
Douglas Gregorf6b11852009-10-08 15:14:33 +00003012 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3013 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003014 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3015 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003016 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3017 return Var->getTemplateSpecializationKind();
3018
Douglas Gregord5cb8762009-10-07 00:13:32 +00003019 return TSK_Undeclared;
3020}
3021
Douglas Gregor9302da62009-10-14 23:50:59 +00003022/// \brief Check whether a specialization is well-formed in the current
3023/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003024///
Douglas Gregor9302da62009-10-14 23:50:59 +00003025/// This routine determines whether a template specialization can be declared
3026/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003027///
3028/// \param S the semantic analysis object for which this check is being
3029/// performed.
3030///
3031/// \param Specialized the entity being specialized or instantiated, which
3032/// may be a kind of template (class template, function template, etc.) or
3033/// a member of a class template (member function, static data member,
3034/// member class).
3035///
3036/// \param PrevDecl the previous declaration of this entity, if any.
3037///
3038/// \param Loc the location of the explicit specialization or instantiation of
3039/// this entity.
3040///
3041/// \param IsPartialSpecialization whether this is a partial specialization of
3042/// a class template.
3043///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003044/// \returns true if there was an error that we cannot recover from, false
3045/// otherwise.
3046static bool CheckTemplateSpecializationScope(Sema &S,
3047 NamedDecl *Specialized,
3048 NamedDecl *PrevDecl,
3049 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003050 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003051 // Keep these "kind" numbers in sync with the %select statements in the
3052 // various diagnostics emitted by this routine.
3053 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003054 bool isTemplateSpecialization = false;
3055 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003056 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003057 isTemplateSpecialization = true;
3058 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003059 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003060 isTemplateSpecialization = true;
3061 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003062 EntityKind = 3;
3063 else if (isa<VarDecl>(Specialized))
3064 EntityKind = 4;
3065 else if (isa<RecordDecl>(Specialized))
3066 EntityKind = 5;
3067 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003068 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3069 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003070 return true;
3071 }
3072
Douglas Gregor88b70942009-02-25 22:02:03 +00003073 // C++ [temp.expl.spec]p2:
3074 // An explicit specialization shall be declared in the namespace
3075 // of which the template is a member, or, for member templates, in
3076 // the namespace of which the enclosing class or enclosing class
3077 // template is a member. An explicit specialization of a member
3078 // function, member class or static data member of a class
3079 // template shall be declared in the namespace of which the class
3080 // template is a member. Such a declaration may also be a
3081 // definition. If the declaration is not a definition, the
3082 // specialization may be defined later in the name- space in which
3083 // the explicit specialization was declared, or in a namespace
3084 // that encloses the one in which the explicit specialization was
3085 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003086 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3087 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003088 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003089 return true;
3090 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003091
Douglas Gregor0a407472009-10-07 17:30:37 +00003092 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3093 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003094 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003095 return true;
3096 }
3097
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003098 // C++ [temp.class.spec]p6:
3099 // A class template partial specialization may be declared or redeclared
3100 // in any namespace scope in which its definition may be defined (14.5.1
3101 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003102 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003103 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003104 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003105 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003106 if ((!PrevDecl ||
3107 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3108 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3109 // There is no prior declaration of this entity, so this
3110 // specialization must be in the same context as the template
3111 // itself.
3112 if (!DC->Equals(SpecializedContext)) {
3113 if (isa<TranslationUnitDecl>(SpecializedContext))
3114 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3115 << EntityKind << Specialized;
3116 else if (isa<NamespaceDecl>(SpecializedContext))
3117 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3118 << EntityKind << Specialized
3119 << cast<NamedDecl>(SpecializedContext);
3120
3121 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3122 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003123 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003124 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003125
3126 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003127 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003128 // Note that HandleDeclarator() performs this check for explicit
3129 // specializations of function templates, static data members, and member
3130 // functions, so we skip the check here for those kinds of entities.
3131 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003132 // Should we refactor that check, so that it occurs later?
3133 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003134 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3135 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003136 if (isa<TranslationUnitDecl>(SpecializedContext))
3137 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3138 << EntityKind << Specialized;
3139 else if (isa<NamespaceDecl>(SpecializedContext))
3140 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3141 << EntityKind << Specialized
3142 << cast<NamedDecl>(SpecializedContext);
3143
Douglas Gregor9302da62009-10-14 23:50:59 +00003144 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003145 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003146
3147 // FIXME: check for specialization-after-instantiation errors and such.
3148
Douglas Gregor88b70942009-02-25 22:02:03 +00003149 return false;
3150}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003151
Douglas Gregore94866f2009-06-12 21:21:02 +00003152/// \brief Check the non-type template arguments of a class template
3153/// partial specialization according to C++ [temp.class.spec]p9.
3154///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003155/// \param TemplateParams the template parameters of the primary class
3156/// template.
3157///
3158/// \param TemplateArg the template arguments of the class template
3159/// partial specialization.
3160///
3161/// \param MirrorsPrimaryTemplate will be set true if the class
3162/// template partial specialization arguments are identical to the
3163/// implicit template arguments of the primary template. This is not
3164/// necessarily an error (C++0x), and it is left to the caller to diagnose
3165/// this condition when it is an error.
3166///
Douglas Gregore94866f2009-06-12 21:21:02 +00003167/// \returns true if there was an error, false otherwise.
3168bool Sema::CheckClassTemplatePartialSpecializationArgs(
3169 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003170 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003171 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003172 // FIXME: the interface to this function will have to change to
3173 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003174 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003175
Anders Carlssonfb250522009-06-23 01:26:57 +00003176 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Douglas Gregore94866f2009-06-12 21:21:02 +00003178 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003179 // Determine whether the template argument list of the partial
3180 // specialization is identical to the implicit argument list of
3181 // the primary template. The caller may need to diagnostic this as
3182 // an error per C++ [temp.class.spec]p9b3.
3183 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003184 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003185 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3186 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003187 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003188 MirrorsPrimaryTemplate = false;
3189 } else if (TemplateTemplateParmDecl *TTP
3190 = dyn_cast<TemplateTemplateParmDecl>(
3191 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003192 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003193 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003194 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003195 if (!ArgDecl ||
3196 ArgDecl->getIndex() != TTP->getIndex() ||
3197 ArgDecl->getDepth() != TTP->getDepth())
3198 MirrorsPrimaryTemplate = false;
3199 }
3200 }
3201
Mike Stump1eb44332009-09-09 15:08:12 +00003202 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003203 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003204 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003205 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003206 }
3207
Anders Carlsson6360be72009-06-13 18:20:51 +00003208 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003209 if (!ArgExpr) {
3210 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003211 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003212 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003213
3214 // C++ [temp.class.spec]p8:
3215 // A non-type argument is non-specialized if it is the name of a
3216 // non-type parameter. All other non-type arguments are
3217 // specialized.
3218 //
3219 // Below, we check the two conditions that only apply to
3220 // specialized non-type arguments, so skip any non-specialized
3221 // arguments.
3222 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003223 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003224 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003225 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003226 (Param->getIndex() != NTTP->getIndex() ||
3227 Param->getDepth() != NTTP->getDepth()))
3228 MirrorsPrimaryTemplate = false;
3229
Douglas Gregore94866f2009-06-12 21:21:02 +00003230 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003231 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003232
3233 // C++ [temp.class.spec]p9:
3234 // Within the argument list of a class template partial
3235 // specialization, the following restrictions apply:
3236 // -- A partially specialized non-type argument expression
3237 // shall not involve a template parameter of the partial
3238 // specialization except when the argument expression is a
3239 // simple identifier.
3240 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003241 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003242 diag::err_dependent_non_type_arg_in_partial_spec)
3243 << ArgExpr->getSourceRange();
3244 return true;
3245 }
3246
3247 // -- The type of a template parameter corresponding to a
3248 // specialized non-type argument shall not be dependent on a
3249 // parameter of the specialization.
3250 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003251 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003252 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3253 << Param->getType()
3254 << ArgExpr->getSourceRange();
3255 Diag(Param->getLocation(), diag::note_template_param_here);
3256 return true;
3257 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003258
3259 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003260 }
3261
3262 return false;
3263}
3264
Douglas Gregor212e81c2009-03-25 00:13:59 +00003265Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003266Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3267 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003268 SourceLocation KWLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +00003269 const CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003270 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003271 SourceLocation TemplateNameLoc,
3272 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003273 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003274 SourceLocation RAngleLoc,
3275 AttributeList *Attr,
3276 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003277 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003278
Douglas Gregorcc636682009-02-17 23:15:12 +00003279 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003280 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003281 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003282 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3283
3284 if (!ClassTemplate) {
3285 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3286 << (Name.getAsTemplateDecl() &&
3287 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3288 return true;
3289 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003290
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003291 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003292 bool isPartialSpecialization = false;
3293
Douglas Gregor88b70942009-02-25 22:02:03 +00003294 // Check the validity of the template headers that introduce this
3295 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003296 // FIXME: We probably shouldn't complain about these headers for
3297 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003298 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003299 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3300 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003301 TemplateParameterLists.size(),
3302 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003303 if (TemplateParams && TemplateParams->size() > 0) {
3304 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003305
Douglas Gregor05396e22009-08-25 17:23:04 +00003306 // C++ [temp.class.spec]p10:
3307 // The template parameter list of a specialization shall not
3308 // contain default template argument values.
3309 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3310 Decl *Param = TemplateParams->getParam(I);
3311 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3312 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003313 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003314 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003315 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003316 }
3317 } else if (NonTypeTemplateParmDecl *NTTP
3318 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3319 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003320 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003321 diag::err_default_arg_in_partial_spec)
3322 << DefArg->getSourceRange();
3323 NTTP->setDefaultArgument(0);
3324 DefArg->Destroy(Context);
3325 }
3326 } else {
3327 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003328 if (TTP->hasDefaultArgument()) {
3329 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003330 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003331 << TTP->getDefaultArgument().getSourceRange();
3332 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003333 }
3334 }
3335 }
Douglas Gregora735b202009-10-13 14:39:41 +00003336 } else if (TemplateParams) {
3337 if (TUK == TUK_Friend)
3338 Diag(KWLoc, diag::err_template_spec_friend)
3339 << CodeModificationHint::CreateRemoval(
3340 SourceRange(TemplateParams->getTemplateLoc(),
3341 TemplateParams->getRAngleLoc()))
3342 << SourceRange(LAngleLoc, RAngleLoc);
3343 else
3344 isExplicitSpecialization = true;
3345 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003346 Diag(KWLoc, diag::err_template_spec_needs_header)
3347 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003348 isExplicitSpecialization = true;
3349 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003350
Douglas Gregorcc636682009-02-17 23:15:12 +00003351 // Check that the specialization uses the same tag kind as the
3352 // original template.
3353 TagDecl::TagKind Kind;
3354 switch (TagSpec) {
3355 default: assert(0 && "Unknown tag type!");
3356 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3357 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3358 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3359 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003360 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003361 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003362 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003363 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003364 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00003365 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003366 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003367 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003368 diag::note_previous_use);
3369 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3370 }
3371
Douglas Gregor40808ce2009-03-09 23:48:35 +00003372 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003373 TemplateArgumentListInfo TemplateArgs;
3374 TemplateArgs.setLAngleLoc(LAngleLoc);
3375 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003376 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003377
Douglas Gregorcc636682009-02-17 23:15:12 +00003378 // Check that the template argument list is well-formed for this
3379 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003380 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3381 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003382 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3383 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003384 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003385
Mike Stump1eb44332009-09-09 15:08:12 +00003386 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003387 ClassTemplate->getTemplateParameters()->size()) &&
3388 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003389
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003390 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003391 // corresponds to these arguments.
3392 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003393 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003394 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003395 if (CheckClassTemplatePartialSpecializationArgs(
3396 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003397 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003398 return true;
3399
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003400 if (MirrorsPrimaryTemplate) {
3401 // C++ [temp.class.spec]p9b3:
3402 //
Mike Stump1eb44332009-09-09 15:08:12 +00003403 // -- The argument list of the specialization shall not be identical
3404 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003405 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003406 << (TUK == TUK_Definition)
Mike Stump1eb44332009-09-09 15:08:12 +00003407 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003408 RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003409 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003410 ClassTemplate->getIdentifier(),
3411 TemplateNameLoc,
3412 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003413 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003414 AS_none);
3415 }
3416
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003417 // FIXME: Diagnose friend partial specializations
3418
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003419 // FIXME: Template parameter list matters, too
Mike Stump1eb44332009-09-09 15:08:12 +00003420 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003421 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003422 Converted.flatSize(),
3423 Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003424 } else
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003425 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003426 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003427 Converted.flatSize(),
3428 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003429 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003430 ClassTemplateSpecializationDecl *PrevDecl = 0;
3431
3432 if (isPartialSpecialization)
3433 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003434 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003435 InsertPos);
3436 else
3437 PrevDecl
3438 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003439
3440 ClassTemplateSpecializationDecl *Specialization = 0;
3441
Douglas Gregor88b70942009-02-25 22:02:03 +00003442 // Check whether we can declare a class template specialization in
3443 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003444 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003445 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003446 TemplateNameLoc,
3447 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003448 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003449
Douglas Gregorb88e8882009-07-30 17:40:51 +00003450 // The canonical type
3451 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003452 if (PrevDecl &&
3453 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3454 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003455 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003456 // arguments was referenced but not declared, or we're only
3457 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003458 // declaration node as our own, updating its source location to
3459 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003460 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003461 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003462 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003463 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003464 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003465 // Build the canonical type that describes the converted template
3466 // arguments of the class template partial specialization.
3467 CanonType = Context.getTemplateSpecializationType(
3468 TemplateName(ClassTemplate),
3469 Converted.getFlatArguments(),
3470 Converted.flatSize());
3471
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003472 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003473 ClassTemplatePartialSpecializationDecl *PrevPartial
3474 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00003475 ClassTemplatePartialSpecializationDecl *Partial
3476 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003477 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003478 TemplateNameLoc,
3479 TemplateParams,
3480 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003481 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003482 TemplateArgs,
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003483 PrevPartial);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003484
3485 if (PrevPartial) {
3486 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3487 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3488 } else {
3489 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3490 }
3491 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003492
Douglas Gregored9c0f92009-10-29 00:04:11 +00003493 // If we are providing an explicit specialization of a member class
3494 // template specialization, make a note of that.
3495 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3496 PrevPartial->setMemberSpecialization();
3497
Douglas Gregor031a5882009-06-13 00:26:55 +00003498 // Check that all of the template parameters of the class template
3499 // partial specialization are deducible from the template
3500 // arguments. If not, this class template partial specialization
3501 // will never be used.
3502 llvm::SmallVector<bool, 8> DeducibleParams;
3503 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003504 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003505 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003506 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003507 unsigned NumNonDeducible = 0;
3508 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3509 if (!DeducibleParams[I])
3510 ++NumNonDeducible;
3511
3512 if (NumNonDeducible) {
3513 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3514 << (NumNonDeducible > 1)
3515 << SourceRange(TemplateNameLoc, RAngleLoc);
3516 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3517 if (!DeducibleParams[I]) {
3518 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3519 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003520 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003521 diag::note_partial_spec_unused_parameter)
3522 << Param->getDeclName();
3523 else
Mike Stump1eb44332009-09-09 15:08:12 +00003524 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003525 diag::note_partial_spec_unused_parameter)
3526 << std::string("<anonymous>");
3527 }
3528 }
3529 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003530 } else {
3531 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003532 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003533 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00003534 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregorcc636682009-02-17 23:15:12 +00003535 ClassTemplate->getDeclContext(),
3536 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003537 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003538 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003539 PrevDecl);
3540
3541 if (PrevDecl) {
3542 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3543 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3544 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003545 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003546 InsertPos);
3547 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003548
3549 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003550 }
3551
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003552 // C++ [temp.expl.spec]p6:
3553 // If a template, a member template or the member of a class template is
3554 // explicitly specialized then that specialization shall be declared
3555 // before the first use of that specialization that would cause an implicit
3556 // instantiation to take place, in every translation unit in which such a
3557 // use occurs; no diagnostic is required.
3558 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3559 SourceRange Range(TemplateNameLoc, RAngleLoc);
3560 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3561 << Context.getTypeDeclType(Specialization) << Range;
3562
3563 Diag(PrevDecl->getPointOfInstantiation(),
3564 diag::note_instantiation_required_here)
3565 << (PrevDecl->getTemplateSpecializationKind()
3566 != TSK_ImplicitInstantiation);
3567 return true;
3568 }
3569
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003570 // If this is not a friend, note that this is an explicit specialization.
3571 if (TUK != TUK_Friend)
3572 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003573
3574 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003575 if (TUK == TUK_Definition) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003576 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003577 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003578 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003579 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003580 Diag(Def->getLocation(), diag::note_previous_definition);
3581 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003582 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003583 }
3584 }
3585
Douglas Gregorfc705b82009-02-26 22:19:44 +00003586 // Build the fully-sugared type for this class template
3587 // specialization as the user wrote in the specialization
3588 // itself. This means that we'll pretty-print the type retrieved
3589 // from the specialization's declaration the way that the user
3590 // actually wrote the specialization, rather than formatting the
3591 // name based on the "canonical" representation used to store the
3592 // template arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003593 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00003594 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003595 if (TUK != TUK_Friend)
3596 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003597 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003598
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003599 // C++ [temp.expl.spec]p9:
3600 // A template explicit specialization is in the scope of the
3601 // namespace in which the template was defined.
3602 //
3603 // We actually implement this paragraph where we set the semantic
3604 // context (in the creation of the ClassTemplateSpecializationDecl),
3605 // but we also maintain the lexical context where the actual
3606 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003607 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003608
Douglas Gregorcc636682009-02-17 23:15:12 +00003609 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003610 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003611 Specialization->startDefinition();
3612
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003613 if (TUK == TUK_Friend) {
3614 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3615 TemplateNameLoc,
3616 WrittenTy.getTypePtr(),
3617 /*FIXME:*/KWLoc);
3618 Friend->setAccess(AS_public);
3619 CurContext->addDecl(Friend);
3620 } else {
3621 // Add the specialization into its lexical context, so that it can
3622 // be seen when iterating through the list of declarations in that
3623 // context. However, specializations are not found by name lookup.
3624 CurContext->addDecl(Specialization);
3625 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003626 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003627}
Douglas Gregord57959a2009-03-27 23:10:48 +00003628
Mike Stump1eb44332009-09-09 15:08:12 +00003629Sema::DeclPtrTy
3630Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003631 MultiTemplateParamsArg TemplateParameterLists,
3632 Declarator &D) {
3633 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3634}
3635
Mike Stump1eb44332009-09-09 15:08:12 +00003636Sema::DeclPtrTy
3637Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003638 MultiTemplateParamsArg TemplateParameterLists,
3639 Declarator &D) {
3640 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3641 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3642 "Not a function declarator!");
3643 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003644
Douglas Gregor52591bf2009-06-24 00:54:41 +00003645 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003646 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003647 }
Mike Stump1eb44332009-09-09 15:08:12 +00003648
Douglas Gregor52591bf2009-06-24 00:54:41 +00003649 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003650
3651 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003652 move(TemplateParameterLists),
3653 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003654 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003655 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00003656 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00003657 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003658 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3659 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00003660 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00003661}
3662
Douglas Gregor454885e2009-10-15 15:54:05 +00003663/// \brief Diagnose cases where we have an explicit template specialization
3664/// before/after an explicit template instantiation, producing diagnostics
3665/// for those cases where they are required and determining whether the
3666/// new specialization/instantiation will have any effect.
3667///
Douglas Gregor454885e2009-10-15 15:54:05 +00003668/// \param NewLoc the location of the new explicit specialization or
3669/// instantiation.
3670///
3671/// \param NewTSK the kind of the new explicit specialization or instantiation.
3672///
3673/// \param PrevDecl the previous declaration of the entity.
3674///
3675/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3676///
3677/// \param PrevPointOfInstantiation if valid, indicates where the previus
3678/// declaration was instantiated (either implicitly or explicitly).
3679///
3680/// \param SuppressNew will be set to true to indicate that the new
3681/// specialization or instantiation has no effect and should be ignored.
3682///
3683/// \returns true if there was an error that should prevent the introduction of
3684/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00003685bool
3686Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3687 TemplateSpecializationKind NewTSK,
3688 NamedDecl *PrevDecl,
3689 TemplateSpecializationKind PrevTSK,
3690 SourceLocation PrevPointOfInstantiation,
3691 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00003692 SuppressNew = false;
3693
3694 switch (NewTSK) {
3695 case TSK_Undeclared:
3696 case TSK_ImplicitInstantiation:
3697 assert(false && "Don't check implicit instantiations here");
3698 return false;
3699
3700 case TSK_ExplicitSpecialization:
3701 switch (PrevTSK) {
3702 case TSK_Undeclared:
3703 case TSK_ExplicitSpecialization:
3704 // Okay, we're just specializing something that is either already
3705 // explicitly specialized or has merely been mentioned without any
3706 // instantiation.
3707 return false;
3708
3709 case TSK_ImplicitInstantiation:
3710 if (PrevPointOfInstantiation.isInvalid()) {
3711 // The declaration itself has not actually been instantiated, so it is
3712 // still okay to specialize it.
3713 return false;
3714 }
3715 // Fall through
3716
3717 case TSK_ExplicitInstantiationDeclaration:
3718 case TSK_ExplicitInstantiationDefinition:
3719 assert((PrevTSK == TSK_ImplicitInstantiation ||
3720 PrevPointOfInstantiation.isValid()) &&
3721 "Explicit instantiation without point of instantiation?");
3722
3723 // C++ [temp.expl.spec]p6:
3724 // If a template, a member template or the member of a class template
3725 // is explicitly specialized then that specialization shall be declared
3726 // before the first use of that specialization that would cause an
3727 // implicit instantiation to take place, in every translation unit in
3728 // which such a use occurs; no diagnostic is required.
Douglas Gregor0d035142009-10-27 18:42:08 +00003729 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00003730 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003731 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00003732 << (PrevTSK != TSK_ImplicitInstantiation);
3733
3734 return true;
3735 }
3736 break;
3737
3738 case TSK_ExplicitInstantiationDeclaration:
3739 switch (PrevTSK) {
3740 case TSK_ExplicitInstantiationDeclaration:
3741 // This explicit instantiation declaration is redundant (that's okay).
3742 SuppressNew = true;
3743 return false;
3744
3745 case TSK_Undeclared:
3746 case TSK_ImplicitInstantiation:
3747 // We're explicitly instantiating something that may have already been
3748 // implicitly instantiated; that's fine.
3749 return false;
3750
3751 case TSK_ExplicitSpecialization:
3752 // C++0x [temp.explicit]p4:
3753 // For a given set of template parameters, if an explicit instantiation
3754 // of a template appears after a declaration of an explicit
3755 // specialization for that template, the explicit instantiation has no
3756 // effect.
3757 return false;
3758
3759 case TSK_ExplicitInstantiationDefinition:
3760 // C++0x [temp.explicit]p10:
3761 // If an entity is the subject of both an explicit instantiation
3762 // declaration and an explicit instantiation definition in the same
3763 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00003764 Diag(NewLoc,
3765 diag::err_explicit_instantiation_declaration_after_definition);
3766 Diag(PrevPointOfInstantiation,
3767 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00003768 assert(PrevPointOfInstantiation.isValid() &&
3769 "Explicit instantiation without point of instantiation?");
3770 SuppressNew = true;
3771 return false;
3772 }
3773 break;
3774
3775 case TSK_ExplicitInstantiationDefinition:
3776 switch (PrevTSK) {
3777 case TSK_Undeclared:
3778 case TSK_ImplicitInstantiation:
3779 // We're explicitly instantiating something that may have already been
3780 // implicitly instantiated; that's fine.
3781 return false;
3782
3783 case TSK_ExplicitSpecialization:
3784 // C++ DR 259, C++0x [temp.explicit]p4:
3785 // For a given set of template parameters, if an explicit
3786 // instantiation of a template appears after a declaration of
3787 // an explicit specialization for that template, the explicit
3788 // instantiation has no effect.
3789 //
3790 // In C++98/03 mode, we only give an extension warning here, because it
3791 // is not not harmful to try to explicitly instantiate something that
3792 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00003793 if (!getLangOptions().CPlusPlus0x) {
3794 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00003795 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003796 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00003797 diag::note_previous_template_specialization);
3798 }
3799 SuppressNew = true;
3800 return false;
3801
3802 case TSK_ExplicitInstantiationDeclaration:
3803 // We're explicity instantiating a definition for something for which we
3804 // were previously asked to suppress instantiations. That's fine.
3805 return false;
3806
3807 case TSK_ExplicitInstantiationDefinition:
3808 // C++0x [temp.spec]p5:
3809 // For a given template and a given set of template-arguments,
3810 // - an explicit instantiation definition shall appear at most once
3811 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00003812 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00003813 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00003814 Diag(PrevPointOfInstantiation,
3815 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00003816 SuppressNew = true;
3817 return false;
3818 }
3819 break;
3820 }
3821
3822 assert(false && "Missing specialization/instantiation case?");
3823
3824 return false;
3825}
3826
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003827/// \brief Perform semantic analysis for the given function template
3828/// specialization.
3829///
3830/// This routine performs all of the semantic analysis required for an
3831/// explicit function template specialization. On successful completion,
3832/// the function declaration \p FD will become a function template
3833/// specialization.
3834///
3835/// \param FD the function declaration, which will be updated to become a
3836/// function template specialization.
3837///
3838/// \param HasExplicitTemplateArgs whether any template arguments were
3839/// explicitly provided.
3840///
3841/// \param LAngleLoc the location of the left angle bracket ('<'), if
3842/// template arguments were explicitly provided.
3843///
3844/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3845/// if any.
3846///
3847/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3848/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3849/// true as in, e.g., \c void sort<>(char*, char*);
3850///
3851/// \param RAngleLoc the location of the right angle bracket ('>'), if
3852/// template arguments were explicitly provided.
3853///
3854/// \param PrevDecl the set of declarations that
3855bool
3856Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00003857 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00003858 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003859 // The set of function template specializations that could match this
3860 // explicit function template specialization.
3861 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3862 CandidateSet Candidates;
3863
3864 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00003865 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3866 I != E; ++I) {
3867 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3868 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003869 // Only consider templates found within the same semantic lookup scope as
3870 // FD.
3871 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3872 continue;
3873
3874 // C++ [temp.expl.spec]p11:
3875 // A trailing template-argument can be left unspecified in the
3876 // template-id naming an explicit function template specialization
3877 // provided it can be deduced from the function argument type.
3878 // Perform template argument deduction to determine whether we may be
3879 // specializing this template.
3880 // FIXME: It is somewhat wasteful to build
3881 TemplateDeductionInfo Info(Context);
3882 FunctionDecl *Specialization = 0;
3883 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00003884 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003885 FD->getType(),
3886 Specialization,
3887 Info)) {
3888 // FIXME: Template argument deduction failed; record why it failed, so
3889 // that we can provide nifty diagnostics.
3890 (void)TDK;
3891 continue;
3892 }
3893
3894 // Record this candidate.
3895 Candidates.push_back(Specialization);
3896 }
3897 }
3898
Douglas Gregorc5df30f2009-09-26 03:41:46 +00003899 // Find the most specialized function template.
3900 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3901 Candidates.size(),
3902 TPOC_Other,
3903 FD->getLocation(),
3904 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));
3909 if (!Specialization)
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003910 return true;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003911
3912 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003913 // If so, we have run afoul of .
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003914
Douglas Gregord5cb8762009-10-07 00:13:32 +00003915 // Check the scope of this explicit specialization.
3916 if (CheckTemplateSpecializationScope(*this,
3917 Specialization->getPrimaryTemplate(),
3918 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00003919 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003920 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003921
3922 // C++ [temp.expl.spec]p6:
3923 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00003924 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003925 // before the first use of that specialization that would cause an implicit
3926 // instantiation to take place, in every translation unit in which such a
3927 // use occurs; no diagnostic is required.
3928 FunctionTemplateSpecializationInfo *SpecInfo
3929 = Specialization->getTemplateSpecializationInfo();
3930 assert(SpecInfo && "Function template specialization info missing?");
3931 if (SpecInfo->getPointOfInstantiation().isValid()) {
3932 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3933 << FD;
3934 Diag(SpecInfo->getPointOfInstantiation(),
3935 diag::note_instantiation_required_here)
3936 << (Specialization->getTemplateSpecializationKind()
3937 != TSK_ImplicitInstantiation);
3938 return true;
3939 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003940
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003941 // Mark the prior declaration as an explicit specialization, so that later
3942 // clients know that this is an explicit specialization.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003943 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003944
3945 // Turn the given function declaration into a function template
3946 // specialization, with the template arguments from the previous
3947 // specialization.
3948 FD->setFunctionTemplateSpecialization(Context,
3949 Specialization->getPrimaryTemplate(),
3950 new (Context) TemplateArgumentList(
3951 *Specialization->getTemplateSpecializationArgs()),
3952 /*InsertPos=*/0,
3953 TSK_ExplicitSpecialization);
3954
3955 // The "previous declaration" for this function template specialization is
3956 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00003957 Previous.clear();
3958 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003959 return false;
3960}
3961
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003962/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003963/// specialization.
3964///
3965/// This routine performs all of the semantic analysis required for an
3966/// explicit member function specialization. On successful completion,
3967/// the function declaration \p FD will become a member function
3968/// specialization.
3969///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003970/// \param Member the member declaration, which will be updated to become a
3971/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003972///
John McCall68263142009-11-18 22:49:29 +00003973/// \param Previous the set of declarations, one of which may be specialized
3974/// by this function specialization; the set will be modified to contain the
3975/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003976bool
John McCall68263142009-11-18 22:49:29 +00003977Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003978 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3979
3980 // Try to find the member we are instantiating.
3981 NamedDecl *Instantiation = 0;
3982 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003983 MemberSpecializationInfo *MSInfo = 0;
3984
John McCall68263142009-11-18 22:49:29 +00003985 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003986 // Nowhere to look anyway.
3987 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00003988 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3989 I != E; ++I) {
3990 NamedDecl *D = (*I)->getUnderlyingDecl();
3991 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003992 if (Context.hasSameType(Function->getType(), Method->getType())) {
3993 Instantiation = Method;
3994 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003995 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003996 break;
3997 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003998 }
3999 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004000 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004001 VarDecl *PrevVar;
4002 if (Previous.isSingleResult() &&
4003 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004004 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004005 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004006 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004007 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004008 }
4009 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004010 CXXRecordDecl *PrevRecord;
4011 if (Previous.isSingleResult() &&
4012 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4013 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004014 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004015 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004016 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004017 }
4018
4019 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004020 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004021 // specializations are always out-of-line, the caller will complain about
4022 // this mismatch later.
4023 return false;
4024 }
4025
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004026 // Make sure that this is a specialization of a member.
4027 if (!InstantiatedFrom) {
4028 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4029 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004030 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4031 return true;
4032 }
4033
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004034 // C++ [temp.expl.spec]p6:
4035 // If a template, a member template or the member of a class template is
4036 // explicitly specialized then that spe- cialization shall be declared
4037 // before the first use of that specialization that would cause an implicit
4038 // instantiation to take place, in every translation unit in which such a
4039 // use occurs; no diagnostic is required.
4040 assert(MSInfo && "Member specialization info missing?");
4041 if (MSInfo->getPointOfInstantiation().isValid()) {
4042 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
4043 << Member;
4044 Diag(MSInfo->getPointOfInstantiation(),
4045 diag::note_instantiation_required_here)
4046 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
4047 return true;
4048 }
4049
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004050 // Check the scope of this explicit specialization.
4051 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004052 InstantiatedFrom,
4053 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004054 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004055 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004056
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004057 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004058 // the original declaration to note that it is an explicit specialization
4059 // (if it was previously an implicit instantiation). This latter step
4060 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004061 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004062 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4063 if (InstantiationFunction->getTemplateSpecializationKind() ==
4064 TSK_ImplicitInstantiation) {
4065 InstantiationFunction->setTemplateSpecializationKind(
4066 TSK_ExplicitSpecialization);
4067 InstantiationFunction->setLocation(Member->getLocation());
4068 }
4069
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004070 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4071 cast<CXXMethodDecl>(InstantiatedFrom),
4072 TSK_ExplicitSpecialization);
4073 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004074 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4075 if (InstantiationVar->getTemplateSpecializationKind() ==
4076 TSK_ImplicitInstantiation) {
4077 InstantiationVar->setTemplateSpecializationKind(
4078 TSK_ExplicitSpecialization);
4079 InstantiationVar->setLocation(Member->getLocation());
4080 }
4081
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004082 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4083 cast<VarDecl>(InstantiatedFrom),
4084 TSK_ExplicitSpecialization);
4085 } else {
4086 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004087 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4088 if (InstantiationClass->getTemplateSpecializationKind() ==
4089 TSK_ImplicitInstantiation) {
4090 InstantiationClass->setTemplateSpecializationKind(
4091 TSK_ExplicitSpecialization);
4092 InstantiationClass->setLocation(Member->getLocation());
4093 }
4094
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004095 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004096 cast<CXXRecordDecl>(InstantiatedFrom),
4097 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004098 }
4099
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004100 // Save the caller the trouble of having to figure out which declaration
4101 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004102 Previous.clear();
4103 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004104 return false;
4105}
4106
Douglas Gregor558c0322009-10-14 23:41:34 +00004107/// \brief Check the scope of an explicit instantiation.
4108static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4109 SourceLocation InstLoc,
4110 bool WasQualifiedName) {
4111 DeclContext *ExpectedContext
4112 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4113 DeclContext *CurContext = S.CurContext->getLookupContext();
4114
4115 // C++0x [temp.explicit]p2:
4116 // An explicit instantiation shall appear in an enclosing namespace of its
4117 // template.
4118 //
4119 // This is DR275, which we do not retroactively apply to C++98/03.
4120 if (S.getLangOptions().CPlusPlus0x &&
4121 !CurContext->Encloses(ExpectedContext)) {
4122 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4123 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4124 << D << NS;
4125 else
4126 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4127 << D;
4128 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4129 return;
4130 }
4131
4132 // C++0x [temp.explicit]p2:
4133 // If the name declared in the explicit instantiation is an unqualified
4134 // name, the explicit instantiation shall appear in the namespace where
4135 // its template is declared or, if that namespace is inline (7.3.1), any
4136 // namespace from its enclosing namespace set.
4137 if (WasQualifiedName)
4138 return;
4139
4140 if (CurContext->Equals(ExpectedContext))
4141 return;
4142
4143 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4144 << D << ExpectedContext;
4145 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4146}
4147
4148/// \brief Determine whether the given scope specifier has a template-id in it.
4149static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4150 if (!SS.isSet())
4151 return false;
4152
4153 // C++0x [temp.explicit]p2:
4154 // If the explicit instantiation is for a member function, a member class
4155 // or a static data member of a class template specialization, the name of
4156 // the class template specialization in the qualified-id for the member
4157 // name shall be a simple-template-id.
4158 //
4159 // C++98 has the same restriction, just worded differently.
4160 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4161 NNS; NNS = NNS->getPrefix())
4162 if (Type *T = NNS->getAsType())
4163 if (isa<TemplateSpecializationType>(T))
4164 return true;
4165
4166 return false;
4167}
4168
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004169// Explicit instantiation of a class template specialization
Douglas Gregor45f96552009-09-04 06:33:52 +00004170// FIXME: Implement extern template semantics
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004171Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004172Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004173 SourceLocation ExternLoc,
4174 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004175 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004176 SourceLocation KWLoc,
4177 const CXXScopeSpec &SS,
4178 TemplateTy TemplateD,
4179 SourceLocation TemplateNameLoc,
4180 SourceLocation LAngleLoc,
4181 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004182 SourceLocation RAngleLoc,
4183 AttributeList *Attr) {
4184 // Find the class template we're specializing
4185 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004186 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004187 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4188
4189 // Check that the specialization uses the same tag kind as the
4190 // original template.
4191 TagDecl::TagKind Kind;
4192 switch (TagSpec) {
4193 default: assert(0 && "Unknown tag type!");
4194 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4195 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4196 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4197 }
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004198 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004199 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004200 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004201 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004202 << ClassTemplate
Mike Stump1eb44332009-09-09 15:08:12 +00004203 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004204 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004205 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004206 diag::note_previous_use);
4207 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4208 }
4209
Douglas Gregor558c0322009-10-14 23:41:34 +00004210 // C++0x [temp.explicit]p2:
4211 // There are two forms of explicit instantiation: an explicit instantiation
4212 // definition and an explicit instantiation declaration. An explicit
4213 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004214 TemplateSpecializationKind TSK
4215 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4216 : TSK_ExplicitInstantiationDeclaration;
4217
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004218 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004219 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004220 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004221
4222 // Check that the template argument list is well-formed for this
4223 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004224 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4225 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004226 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4227 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004228 return true;
4229
Mike Stump1eb44332009-09-09 15:08:12 +00004230 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004231 ClassTemplate->getTemplateParameters()->size()) &&
4232 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004233
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004234 // Find the class template specialization declaration that
4235 // corresponds to these arguments.
4236 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004237 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004238 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004239 Converted.flatSize(),
4240 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004241 void *InsertPos = 0;
4242 ClassTemplateSpecializationDecl *PrevDecl
4243 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4244
Douglas Gregord5cb8762009-10-07 00:13:32 +00004245 // C++0x [temp.explicit]p2:
4246 // [...] An explicit instantiation shall appear in an enclosing
4247 // namespace of its template. [...]
4248 //
4249 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004250 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4251 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004252
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004253 ClassTemplateSpecializationDecl *Specialization = 0;
4254
Douglas Gregord78f5982009-11-25 06:01:46 +00004255 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004256 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004257 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004258 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004259 PrevDecl,
4260 PrevDecl->getSpecializationKind(),
4261 PrevDecl->getPointOfInstantiation(),
4262 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004263 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004264
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004265 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004266 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004267
Douglas Gregor52604ab2009-09-11 21:19:12 +00004268 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4269 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4270 // Since the only prior class template specialization with these
4271 // arguments was referenced but not declared, reuse that
4272 // declaration node as our own, updating its source location to
4273 // reflect our new declaration.
4274 Specialization = PrevDecl;
4275 Specialization->setLocation(TemplateNameLoc);
4276 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004277 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004278 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004279 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004280
4281 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004282 // Create a new class template specialization declaration node for
4283 // this explicit specialization.
4284 Specialization
Mike Stump1eb44332009-09-09 15:08:12 +00004285 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004286 ClassTemplate->getDeclContext(),
4287 TemplateNameLoc,
4288 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004289 Converted, PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004290
Douglas Gregor52604ab2009-09-11 21:19:12 +00004291 if (PrevDecl) {
4292 // Remove the previous declaration from the folding set, since we want
4293 // to introduce a new declaration.
4294 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4295 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4296 }
4297
4298 // Insert the new specialization.
4299 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004300 }
4301
4302 // Build the fully-sugared type for this explicit instantiation as
4303 // the user wrote in the explicit instantiation itself. This means
4304 // that we'll pretty-print the type retrieved from the
4305 // specialization's declaration the way that the user actually wrote
4306 // the explicit instantiation, rather than formatting the name based
4307 // on the "canonical" representation used to store the template
4308 // arguments in the specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004309 QualType WrittenTy
John McCalld5532b62009-11-23 01:53:49 +00004310 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004311 Context.getTypeDeclType(Specialization));
4312 Specialization->setTypeAsWritten(WrittenTy);
4313 TemplateArgsIn.release();
4314
Douglas Gregord78f5982009-11-25 06:01:46 +00004315 if (!ReusedDecl) {
4316 // Add the explicit instantiation into its lexical context. However,
4317 // since explicit instantiations are never found by name lookup, we
4318 // just put it into the declaration context directly.
4319 Specialization->setLexicalDeclContext(CurContext);
4320 CurContext->addDecl(Specialization);
4321 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004322
4323 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004324 // A definition of a class template or class member template
4325 // shall be in scope at the point of the explicit instantiation of
4326 // the class template or class member template.
4327 //
4328 // This check comes when we actually try to perform the
4329 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004330 ClassTemplateSpecializationDecl *Def
4331 = cast_or_null<ClassTemplateSpecializationDecl>(
4332 Specialization->getDefinition(Context));
4333 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004334 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor0d035142009-10-27 18:42:08 +00004335
4336 // Instantiate the members of this class template specialization.
4337 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4338 Specialization->getDefinition(Context));
4339 if (Def)
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004340 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004341
4342 return DeclPtrTy::make(Specialization);
4343}
4344
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004345// Explicit instantiation of a member class of a class template.
4346Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004347Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004348 SourceLocation ExternLoc,
4349 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004350 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004351 SourceLocation KWLoc,
4352 const CXXScopeSpec &SS,
4353 IdentifierInfo *Name,
4354 SourceLocation NameLoc,
4355 AttributeList *Attr) {
4356
Douglas Gregor402abb52009-05-28 23:31:59 +00004357 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004358 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004359 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004360 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004361 MultiTemplateParamsArg(*this, 0, 0),
4362 Owned, IsDependent);
4363 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4364
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004365 if (!TagD)
4366 return true;
4367
4368 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4369 if (Tag->isEnum()) {
4370 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4371 << Context.getTypeDeclType(Tag);
4372 return true;
4373 }
4374
Douglas Gregord0c87372009-05-27 17:30:49 +00004375 if (Tag->isInvalidDecl())
4376 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004377
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004378 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4379 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4380 if (!Pattern) {
4381 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4382 << Context.getTypeDeclType(Record);
4383 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4384 return true;
4385 }
4386
Douglas Gregor558c0322009-10-14 23:41:34 +00004387 // C++0x [temp.explicit]p2:
4388 // If the explicit instantiation is for a class or member class, the
4389 // elaborated-type-specifier in the declaration shall include a
4390 // simple-template-id.
4391 //
4392 // C++98 has the same restriction, just worded differently.
4393 if (!ScopeSpecifierHasTemplateId(SS))
4394 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4395 << Record << SS.getRange();
4396
4397 // C++0x [temp.explicit]p2:
4398 // There are two forms of explicit instantiation: an explicit instantiation
4399 // definition and an explicit instantiation declaration. An explicit
4400 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004401 TemplateSpecializationKind TSK
4402 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4403 : TSK_ExplicitInstantiationDeclaration;
4404
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004405 // C++0x [temp.explicit]p2:
4406 // [...] An explicit instantiation shall appear in an enclosing
4407 // namespace of its template. [...]
4408 //
4409 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004410 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004411
4412 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004413 CXXRecordDecl *PrevDecl
4414 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4415 if (!PrevDecl && Record->getDefinition(Context))
4416 PrevDecl = Record;
4417 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004418 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4419 bool SuppressNew = false;
4420 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004421 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004422 PrevDecl,
4423 MSInfo->getTemplateSpecializationKind(),
4424 MSInfo->getPointOfInstantiation(),
4425 SuppressNew))
4426 return true;
4427 if (SuppressNew)
4428 return TagD;
4429 }
4430
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004431 CXXRecordDecl *RecordDef
4432 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4433 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004434 // C++ [temp.explicit]p3:
4435 // A definition of a member class of a class template shall be in scope
4436 // at the point of an explicit instantiation of the member class.
4437 CXXRecordDecl *Def
4438 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4439 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004440 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4441 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004442 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4443 << Pattern;
4444 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004445 } else {
4446 if (InstantiateClass(NameLoc, Record, Def,
4447 getTemplateInstantiationArgs(Record),
4448 TSK))
4449 return true;
4450
4451 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4452 if (!RecordDef)
4453 return true;
4454 }
4455 }
4456
4457 // Instantiate all of the members of the class.
4458 InstantiateClassMembers(NameLoc, RecordDef,
4459 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004460
Mike Stump390b4cc2009-05-16 07:39:55 +00004461 // FIXME: We don't have any representation for explicit instantiations of
4462 // member classes. Such a representation is not needed for compilation, but it
4463 // should be available for clients that want to see all of the declarations in
4464 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004465 return TagD;
4466}
4467
Douglas Gregord5a423b2009-09-25 18:43:00 +00004468Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4469 SourceLocation ExternLoc,
4470 SourceLocation TemplateLoc,
4471 Declarator &D) {
4472 // Explicit instantiations always require a name.
4473 DeclarationName Name = GetNameForDeclarator(D);
4474 if (!Name) {
4475 if (!D.isInvalidType())
4476 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4477 diag::err_explicit_instantiation_requires_name)
4478 << D.getDeclSpec().getSourceRange()
4479 << D.getSourceRange();
4480
4481 return true;
4482 }
4483
4484 // The scope passed in may not be a decl scope. Zip up the scope tree until
4485 // we find one that is.
4486 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4487 (S->getFlags() & Scope::TemplateParamScope) != 0)
4488 S = S->getParent();
4489
4490 // Determine the type of the declaration.
4491 QualType R = GetTypeForDeclarator(D, S, 0);
4492 if (R.isNull())
4493 return true;
4494
4495 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4496 // Cannot explicitly instantiate a typedef.
4497 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4498 << Name;
4499 return true;
4500 }
4501
Douglas Gregor663b5a02009-10-14 20:14:33 +00004502 // C++0x [temp.explicit]p1:
4503 // [...] An explicit instantiation of a function template shall not use the
4504 // inline or constexpr specifiers.
4505 // Presumably, this also applies to member functions of class templates as
4506 // well.
4507 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4508 Diag(D.getDeclSpec().getInlineSpecLoc(),
4509 diag::err_explicit_instantiation_inline)
4510 << CodeModificationHint::CreateRemoval(
4511 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4512
4513 // FIXME: check for constexpr specifier.
4514
Douglas Gregor558c0322009-10-14 23:41:34 +00004515 // C++0x [temp.explicit]p2:
4516 // There are two forms of explicit instantiation: an explicit instantiation
4517 // definition and an explicit instantiation declaration. An explicit
4518 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004519 TemplateSpecializationKind TSK
4520 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4521 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004522
John McCalla24dc2e2009-11-17 02:14:36 +00004523 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4524 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004525
4526 if (!R->isFunctionType()) {
4527 // C++ [temp.explicit]p1:
4528 // A [...] static data member of a class template can be explicitly
4529 // instantiated from the member definition associated with its class
4530 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004531 if (Previous.isAmbiguous())
4532 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004533
John McCallf36e02d2009-10-09 21:13:30 +00004534 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4535 Previous.getAsSingleDecl(Context));
Douglas Gregord5a423b2009-09-25 18:43:00 +00004536 if (!Prev || !Prev->isStaticDataMember()) {
4537 // We expect to see a data data member here.
4538 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4539 << Name;
4540 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4541 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004542 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004543 return true;
4544 }
4545
4546 if (!Prev->getInstantiatedFromStaticDataMember()) {
4547 // FIXME: Check for explicit specialization?
4548 Diag(D.getIdentifierLoc(),
4549 diag::err_explicit_instantiation_data_member_not_instantiated)
4550 << Prev;
4551 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4552 // FIXME: Can we provide a note showing where this was declared?
4553 return true;
4554 }
4555
Douglas Gregor558c0322009-10-14 23:41:34 +00004556 // C++0x [temp.explicit]p2:
4557 // If the explicit instantiation is for a member function, a member class
4558 // or a static data member of a class template specialization, the name of
4559 // the class template specialization in the qualified-id for the member
4560 // name shall be a simple-template-id.
4561 //
4562 // C++98 has the same restriction, just worded differently.
4563 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4564 Diag(D.getIdentifierLoc(),
4565 diag::err_explicit_instantiation_without_qualified_id)
4566 << Prev << D.getCXXScopeSpec().getRange();
4567
4568 // Check the scope of this explicit instantiation.
4569 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4570
Douglas Gregor454885e2009-10-15 15:54:05 +00004571 // Verify that it is okay to explicitly instantiate here.
4572 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4573 assert(MSInfo && "Missing static data member specialization info?");
4574 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004575 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00004576 MSInfo->getTemplateSpecializationKind(),
4577 MSInfo->getPointOfInstantiation(),
4578 SuppressNew))
4579 return true;
4580 if (SuppressNew)
4581 return DeclPtrTy();
4582
Douglas Gregord5a423b2009-09-25 18:43:00 +00004583 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004584 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004585 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004586 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4587 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004588
4589 // FIXME: Create an ExplicitInstantiation node?
4590 return DeclPtrTy();
4591 }
4592
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004593 // If the declarator is a template-id, translate the parser's template
4594 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00004595 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004596 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004597 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4598 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00004599 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4600 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00004601 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4602 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00004603 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00004604 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00004605 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00004606 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00004607 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00004608
Douglas Gregord5a423b2009-09-25 18:43:00 +00004609 // C++ [temp.explicit]p1:
4610 // A [...] function [...] can be explicitly instantiated from its template.
4611 // A member function [...] of a class template can be explicitly
4612 // instantiated from the member definition associated with its class
4613 // template.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004614 llvm::SmallVector<FunctionDecl *, 8> Matches;
4615 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4616 P != PEnd; ++P) {
4617 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00004618 if (!HasExplicitTemplateArgs) {
4619 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4620 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4621 Matches.clear();
4622 Matches.push_back(Method);
4623 break;
4624 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00004625 }
4626 }
4627
4628 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4629 if (!FunTmpl)
4630 continue;
4631
4632 TemplateDeductionInfo Info(Context);
4633 FunctionDecl *Specialization = 0;
4634 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004635 = DeduceTemplateArguments(FunTmpl,
4636 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004637 R, Specialization, Info)) {
4638 // FIXME: Keep track of almost-matches?
4639 (void)TDK;
4640 continue;
4641 }
4642
4643 Matches.push_back(Specialization);
4644 }
4645
4646 // Find the most specialized function template specialization.
4647 FunctionDecl *Specialization
4648 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4649 D.getIdentifierLoc(),
4650 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4651 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4652 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4653
4654 if (!Specialization)
4655 return true;
4656
Douglas Gregor0a897e32009-10-15 17:21:20 +00004657 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00004658 Diag(D.getIdentifierLoc(),
4659 diag::err_explicit_instantiation_member_function_not_instantiated)
4660 << Specialization
4661 << (Specialization->getTemplateSpecializationKind() ==
4662 TSK_ExplicitSpecialization);
4663 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4664 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00004665 }
Douglas Gregor558c0322009-10-14 23:41:34 +00004666
Douglas Gregor0a897e32009-10-15 17:21:20 +00004667 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00004668 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4669 PrevDecl = Specialization;
4670
Douglas Gregor0a897e32009-10-15 17:21:20 +00004671 if (PrevDecl) {
4672 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004673 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00004674 PrevDecl,
4675 PrevDecl->getTemplateSpecializationKind(),
4676 PrevDecl->getPointOfInstantiation(),
4677 SuppressNew))
4678 return true;
4679
4680 // FIXME: We may still want to build some representation of this
4681 // explicit specialization.
4682 if (SuppressNew)
4683 return DeclPtrTy();
4684 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00004685
4686 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00004687
4688 if (TSK == TSK_ExplicitInstantiationDefinition)
4689 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4690 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00004691
Douglas Gregor558c0322009-10-14 23:41:34 +00004692 // C++0x [temp.explicit]p2:
4693 // If the explicit instantiation is for a member function, a member class
4694 // or a static data member of a class template specialization, the name of
4695 // the class template specialization in the qualified-id for the member
4696 // name shall be a simple-template-id.
4697 //
4698 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00004699 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004700 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00004701 D.getCXXScopeSpec().isSet() &&
4702 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4703 Diag(D.getIdentifierLoc(),
4704 diag::err_explicit_instantiation_without_qualified_id)
4705 << Specialization << D.getCXXScopeSpec().getRange();
4706
4707 CheckExplicitInstantiationScope(*this,
4708 FunTmpl? (NamedDecl *)FunTmpl
4709 : Specialization->getInstantiatedFromMemberFunction(),
4710 D.getIdentifierLoc(),
4711 D.getCXXScopeSpec().isSet());
4712
Douglas Gregord5a423b2009-09-25 18:43:00 +00004713 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4714 return DeclPtrTy();
4715}
4716
Douglas Gregord57959a2009-03-27 23:10:48 +00004717Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00004718Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4719 const CXXScopeSpec &SS, IdentifierInfo *Name,
4720 SourceLocation TagLoc, SourceLocation NameLoc) {
4721 // This has to hold, because SS is expected to be defined.
4722 assert(Name && "Expected a name in a dependent tag");
4723
4724 NestedNameSpecifier *NNS
4725 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4726 if (!NNS)
4727 return true;
4728
4729 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4730 if (T.isNull())
4731 return true;
4732
4733 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4734 QualType ElabType = Context.getElaboratedType(T, TagKind);
4735
4736 return ElabType.getAsOpaquePtr();
4737}
4738
4739Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00004740Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4741 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004742 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00004743 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4744 if (!NNS)
4745 return true;
4746
4747 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregor31a19b62009-04-01 21:51:26 +00004748 if (T.isNull())
4749 return true;
Douglas Gregord57959a2009-03-27 23:10:48 +00004750 return T.getAsOpaquePtr();
4751}
4752
Douglas Gregor17343172009-04-01 00:28:59 +00004753Sema::TypeResult
4754Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4755 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00004756 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004757 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00004758 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00004759 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00004760 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00004761 assert(TemplateId && "Expected a template specialization type");
4762
Douglas Gregor6946baf2009-09-02 13:05:45 +00004763 if (computeDeclContext(SS, false)) {
4764 // If we can compute a declaration context, then the "typename"
4765 // keyword was superfluous. Just build a QualifiedNameType to keep
4766 // track of the nested-name-specifier.
Mike Stump1eb44332009-09-09 15:08:12 +00004767
Douglas Gregor6946baf2009-09-02 13:05:45 +00004768 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4769 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4770 }
Mike Stump1eb44332009-09-09 15:08:12 +00004771
Douglas Gregor6946baf2009-09-02 13:05:45 +00004772 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00004773}
4774
Douglas Gregord57959a2009-03-27 23:10:48 +00004775/// \brief Build the type that describes a C++ typename specifier,
4776/// e.g., "typename T::type".
4777QualType
4778Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4779 SourceRange Range) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00004780 CXXRecordDecl *CurrentInstantiation = 0;
4781 if (NNS->isDependent()) {
4782 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregord57959a2009-03-27 23:10:48 +00004783
Douglas Gregor42af25f2009-05-11 19:58:34 +00004784 // If the nested-name-specifier does not refer to the current
4785 // instantiation, then build a typename type.
4786 if (!CurrentInstantiation)
4787 return Context.getTypenameType(NNS, &II);
Mike Stump1eb44332009-09-09 15:08:12 +00004788
Douglas Gregorde18d122009-09-02 13:12:51 +00004789 // The nested-name-specifier refers to the current instantiation, so the
4790 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump1eb44332009-09-09 15:08:12 +00004791 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorde18d122009-09-02 13:12:51 +00004792 // extraneous "typename" keywords, and we retroactively apply this DR to
4793 // C++03 code.
Douglas Gregor42af25f2009-05-11 19:58:34 +00004794 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004795
Douglas Gregor42af25f2009-05-11 19:58:34 +00004796 DeclContext *Ctx = 0;
4797
4798 if (CurrentInstantiation)
4799 Ctx = CurrentInstantiation;
4800 else {
4801 CXXScopeSpec SS;
4802 SS.setScopeRep(NNS);
4803 SS.setRange(Range);
4804 if (RequireCompleteDeclContext(SS))
4805 return QualType();
4806
4807 Ctx = computeDeclContext(SS);
4808 }
Douglas Gregord57959a2009-03-27 23:10:48 +00004809 assert(Ctx && "No declaration context?");
4810
4811 DeclarationName Name(&II);
John McCalla24dc2e2009-11-17 02:14:36 +00004812 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4813 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00004814 unsigned DiagID = 0;
4815 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004816 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004817 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00004818 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00004819 break;
4820
4821 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00004822 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregord57959a2009-03-27 23:10:48 +00004823 // We found a type. Build a QualifiedNameType, since the
4824 // typename-specifier was just sugar. FIXME: Tell
4825 // QualifiedNameType that it has a "typename" prefix.
4826 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4827 }
4828
4829 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00004830 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00004831 break;
4832
John McCall7ba107a2009-11-18 02:36:19 +00004833 case LookupResult::FoundUnresolvedValue:
4834 llvm::llvm_unreachable("unresolved using decl in non-dependent context");
4835 return QualType();
4836
Douglas Gregord57959a2009-03-27 23:10:48 +00004837 case LookupResult::FoundOverloaded:
4838 DiagID = diag::err_typename_nested_not_type;
4839 Referenced = *Result.begin();
4840 break;
4841
John McCall6e247262009-10-10 05:48:19 +00004842 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00004843 return QualType();
4844 }
4845
4846 // If we get here, it's because name lookup did not find a
4847 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor3f093272009-10-13 21:16:44 +00004848 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00004849 if (Referenced)
4850 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4851 << Name;
4852 return QualType();
4853}
Douglas Gregor4a959d82009-08-06 16:20:37 +00004854
4855namespace {
4856 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump1eb44332009-09-09 15:08:12 +00004857 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4858 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00004859 SourceLocation Loc;
4860 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00004861
Douglas Gregor4a959d82009-08-06 16:20:37 +00004862 public:
Mike Stump1eb44332009-09-09 15:08:12 +00004863 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00004864 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004865 DeclarationName Entity)
4866 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00004867 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00004868
4869 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00004870 /// transformed.
4871 ///
4872 /// For the purposes of type reconstruction, a type has already been
4873 /// transformed if it is NULL or if it is not dependent.
4874 bool AlreadyTransformed(QualType T) {
4875 return T.isNull() || !T->isDependentType();
4876 }
Mike Stump1eb44332009-09-09 15:08:12 +00004877
4878 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00004879 /// rebuilt.
4880 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00004881
Douglas Gregor4a959d82009-08-06 16:20:37 +00004882 /// \brief Returns the name of the entity whose type is being rebuilt.
4883 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00004884
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004885 /// \brief Sets the "base" location and entity when that
4886 /// information is known based on another transformation.
4887 void setBase(SourceLocation Loc, DeclarationName Entity) {
4888 this->Loc = Loc;
4889 this->Entity = Entity;
4890 }
4891
Douglas Gregor4a959d82009-08-06 16:20:37 +00004892 /// \brief Transforms an expression by returning the expression itself
4893 /// (an identity function).
4894 ///
4895 /// FIXME: This is completely unsafe; we will need to actually clone the
4896 /// expressions.
4897 Sema::OwningExprResult TransformExpr(Expr *E) {
4898 return getSema().Owned(E);
4899 }
Mike Stump1eb44332009-09-09 15:08:12 +00004900
Douglas Gregor4a959d82009-08-06 16:20:37 +00004901 /// \brief Transforms a typename type by determining whether the type now
4902 /// refers to a member of the current instantiation, and then
4903 /// type-checking and building a QualifiedNameType (when possible).
John McCalla2becad2009-10-21 00:40:46 +00004904 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor4a959d82009-08-06 16:20:37 +00004905 };
4906}
4907
Mike Stump1eb44332009-09-09 15:08:12 +00004908QualType
John McCalla2becad2009-10-21 00:40:46 +00004909CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4910 TypenameTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00004911 TypenameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00004912
Douglas Gregor4a959d82009-08-06 16:20:37 +00004913 NestedNameSpecifier *NNS
4914 = TransformNestedNameSpecifier(T->getQualifier(),
4915 /*FIXME:*/SourceRange(getBaseLocation()));
4916 if (!NNS)
4917 return QualType();
4918
4919 // If the nested-name-specifier did not change, and we cannot compute the
4920 // context corresponding to the nested-name-specifier, then this
4921 // typename type will not change; exit early.
4922 CXXScopeSpec SS;
4923 SS.setRange(SourceRange(getBaseLocation()));
4924 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00004925
4926 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004927 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00004928 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004929
4930 // Rebuild the typename type, which will probably turn into a
Douglas Gregor4a959d82009-08-06 16:20:37 +00004931 // QualifiedNameType.
John McCall833ca992009-10-29 08:12:44 +00004932 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004933 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00004934 = TransformType(QualType(TemplateId, 0));
4935 if (NewTemplateId.isNull())
4936 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004937
Douglas Gregor4a959d82009-08-06 16:20:37 +00004938 if (NNS == T->getQualifier() &&
4939 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00004940 Result = QualType(T, 0);
4941 else
4942 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4943 } else
4944 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4945 SourceRange(TL.getNameLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +00004946
John McCall833ca992009-10-29 08:12:44 +00004947 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4948 NewTL.setNameLoc(TL.getNameLoc());
4949 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00004950}
4951
4952/// \brief Rebuilds a type within the context of the current instantiation.
4953///
Mike Stump1eb44332009-09-09 15:08:12 +00004954/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00004955/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00004956/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00004957/// partial specialization thereof). This routine will rebuild that type now
4958/// that we have entered the declarator's scope, which may produce different
4959/// canonical types, e.g.,
4960///
4961/// \code
4962/// template<typename T>
4963/// struct X {
4964/// typedef T* pointer;
4965/// pointer data();
4966/// };
4967///
4968/// template<typename T>
4969/// typename X<T>::pointer X<T>::data() { ... }
4970/// \endcode
4971///
4972/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4973/// since we do not know that we can look into X<T> when we parsed the type.
4974/// This function will rebuild the type, performing the lookup of "pointer"
4975/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4976/// as the canonical type of T*, allowing the return types of the out-of-line
4977/// definition and the declaration to match.
4978QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4979 DeclarationName Name) {
4980 if (T.isNull() || !T->isDependentType())
4981 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00004982
Douglas Gregor4a959d82009-08-06 16:20:37 +00004983 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4984 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00004985}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004986
4987/// \brief Produces a formatted string that describes the binding of
4988/// template parameters to template arguments.
4989std::string
4990Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4991 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00004992 // FIXME: For variadic templates, we'll need to get the structured list.
4993 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4994 Args.flat_size());
4995}
4996
4997std::string
4998Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4999 const TemplateArgument *Args,
5000 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005001 std::string Result;
5002
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005003 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005004 return Result;
5005
5006 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005007 if (I >= NumArgs)
5008 break;
5009
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005010 if (I == 0)
5011 Result += "[with ";
5012 else
5013 Result += ", ";
5014
5015 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5016 Result += Id->getName();
5017 } else {
5018 Result += '$';
5019 Result += llvm::utostr(I);
5020 }
5021
5022 Result += " = ";
5023
5024 switch (Args[I].getKind()) {
5025 case TemplateArgument::Null:
5026 Result += "<no value>";
5027 break;
5028
5029 case TemplateArgument::Type: {
5030 std::string TypeStr;
5031 Args[I].getAsType().getAsStringInternal(TypeStr,
5032 Context.PrintingPolicy);
5033 Result += TypeStr;
5034 break;
5035 }
5036
5037 case TemplateArgument::Declaration: {
5038 bool Unnamed = true;
5039 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5040 if (ND->getDeclName()) {
5041 Unnamed = false;
5042 Result += ND->getNameAsString();
5043 }
5044 }
5045
5046 if (Unnamed) {
5047 Result += "<anonymous>";
5048 }
5049 break;
5050 }
5051
Douglas Gregor788cd062009-11-11 01:00:40 +00005052 case TemplateArgument::Template: {
5053 std::string Str;
5054 llvm::raw_string_ostream OS(Str);
5055 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5056 Result += OS.str();
5057 break;
5058 }
5059
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005060 case TemplateArgument::Integral: {
5061 Result += Args[I].getAsIntegral()->toString(10);
5062 break;
5063 }
5064
5065 case TemplateArgument::Expression: {
5066 assert(false && "No expressions in deduced template arguments!");
5067 Result += "<expression>";
5068 break;
5069 }
5070
5071 case TemplateArgument::Pack:
5072 // FIXME: Format template argument packs
5073 Result += "<template argument pack>";
5074 break;
5075 }
5076 }
5077
5078 Result += ']';
5079 return Result;
5080}