blob: 4efecea935123875089ee74a11922ae9fa1293cf [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000023#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-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 Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
63 if (!Ovl)
64 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000065
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000077
Douglas Gregorb7bfe792009-09-02 22:59:36 +000078 if (F != FEnd) {
79 // Build an overloaded function decl containing only the
80 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000081 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-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 Stump11289f42009-09-09 15:08:12 +000091
Douglas Gregorb7bfe792009-09-02 22:59:36 +000092 return OvlTemplate;
93 }
94
95 return FuncTmpl;
96 }
97 }
Mike Stump11289f42009-09-09 15:08:12 +000098
Douglas Gregorb7bfe792009-09-02 22:59:36 +000099 return 0;
100}
101
John McCalle66edc12009-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 Gregorb7bfe792009-09-02 22:59:36 +0000115TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000116 const CXXScopeSpec &SS,
117 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000118 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000119 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000120 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-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
133 default:
134 return TNK_Non_template;
135 }
Mike Stump11289f42009-09-09 15:08:12 +0000136
John McCalle66edc12009-11-24 19:00:30 +0000137 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000138
John McCalle66edc12009-11-24 19:00:30 +0000139 LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName);
140 R.suppressDiagnostics();
141 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
142 if (R.empty())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000143 return TNK_Non_template;
144
John McCalle66edc12009-11-24 19:00:30 +0000145 NamedDecl *Template = R.getAsSingleDecl(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000146
Douglas Gregor3cf81312009-11-03 23:16:33 +0000147 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000148 NestedNameSpecifier *Qualifier
Douglas Gregor3cf81312009-11-03 23:16:33 +0000149 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000150 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000151 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000152 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000153 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
154 Ovl));
155 else
Mike Stump11289f42009-09-09 15:08:12 +0000156 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000157 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000158 cast<TemplateDecl>(Template)));
159 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000160 = dyn_cast<OverloadedFunctionDecl>(Template)) {
161 TemplateResult = TemplateTy::make(TemplateName(Ovl));
162 } else {
163 TemplateResult = TemplateTy::make(
164 TemplateName(cast<TemplateDecl>(Template)));
165 }
Mike Stump11289f42009-09-09 15:08:12 +0000166
167 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000168 isa<TemplateTemplateParmDecl>(Template))
169 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000170
171 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000172 isa<OverloadedFunctionDecl>(Template)) &&
173 "Unhandled template kind in Sema::isTemplateName");
John McCalle66edc12009-11-24 19:00:30 +0000174 return TNK_Function_template;
175}
176
177void Sema::LookupTemplateName(LookupResult &Found,
178 Scope *S, const CXXScopeSpec &SS,
179 QualType ObjectType,
180 bool EnteringContext) {
181 // Determine where to perform name lookup
182 DeclContext *LookupCtx = 0;
183 bool isDependent = false;
184 if (!ObjectType.isNull()) {
185 // This nested-name-specifier occurs in a member access expression, e.g.,
186 // x->B::f, and we are looking into the type of the object.
187 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
188 LookupCtx = computeDeclContext(ObjectType);
189 isDependent = ObjectType->isDependentType();
190 assert((isDependent || !ObjectType->isIncompleteType()) &&
191 "Caller should have completed object type");
192 } else if (SS.isSet()) {
193 // This nested-name-specifier occurs after another nested-name-specifier,
194 // so long into the context associated with the prior nested-name-specifier.
195 LookupCtx = computeDeclContext(SS, EnteringContext);
196 isDependent = isDependentScopeSpecifier(SS);
197
198 // The declaration context must be complete.
199 if (LookupCtx && RequireCompleteDeclContext(SS))
200 return;
201 }
202
203 bool ObjectTypeSearchedInScope = false;
204 if (LookupCtx) {
205 // Perform "qualified" name lookup into the declaration context we
206 // computed, which is either the type of the base of a member access
207 // expression or the declaration context associated with a prior
208 // nested-name-specifier.
209 LookupQualifiedName(Found, LookupCtx);
210
211 if (!ObjectType.isNull() && Found.empty()) {
212 // C++ [basic.lookup.classref]p1:
213 // In a class member access expression (5.2.5), if the . or -> token is
214 // immediately followed by an identifier followed by a <, the
215 // identifier must be looked up to determine whether the < is the
216 // beginning of a template argument list (14.2) or a less-than operator.
217 // The identifier is first looked up in the class of the object
218 // expression. If the identifier is not found, it is then looked up in
219 // the context of the entire postfix-expression and shall name a class
220 // or function template.
221 //
222 // FIXME: When we're instantiating a template, do we actually have to
223 // look in the scope of the template? Seems fishy...
224 if (S) LookupName(Found, S);
225 ObjectTypeSearchedInScope = true;
226 }
227 } else if (isDependent) {
228 // We cannot look into a dependent object type or
229 return;
230 } else {
231 // Perform unqualified name lookup in the current scope.
232 LookupName(Found, S);
233 }
234
235 // FIXME: Cope with ambiguous name-lookup results.
236 assert(!Found.isAmbiguous() &&
237 "Cannot handle template name-lookup ambiguities");
238
239 FilterAcceptableTemplateNames(Context, Found);
240 if (Found.empty())
241 return;
242
243 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
244 // C++ [basic.lookup.classref]p1:
245 // [...] If the lookup in the class of the object expression finds a
246 // template, the name is also looked up in the context of the entire
247 // postfix-expression and [...]
248 //
249 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
250 LookupOrdinaryName);
251 LookupName(FoundOuter, S);
252 FilterAcceptableTemplateNames(Context, FoundOuter);
253 // FIXME: Handle ambiguities in this lookup better
254
255 if (FoundOuter.empty()) {
256 // - if the name is not found, the name found in the class of the
257 // object expression is used, otherwise
258 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
259 // - if the name is found in the context of the entire
260 // postfix-expression and does not name a class template, the name
261 // found in the class of the object expression is used, otherwise
262 } else {
263 // - if the name found is a class template, it must refer to the same
264 // entity as the one found in the class of the object expression,
265 // otherwise the program is ill-formed.
266 if (!Found.isSingleResult() ||
267 Found.getFoundDecl()->getCanonicalDecl()
268 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
269 Diag(Found.getNameLoc(),
270 diag::err_nested_name_member_ref_lookup_ambiguous)
271 << Found.getLookupName();
272 Diag(Found.getRepresentativeDecl()->getLocation(),
273 diag::note_ambig_member_ref_object_type)
274 << ObjectType;
275 Diag(FoundOuter.getFoundDecl()->getLocation(),
276 diag::note_ambig_member_ref_scope);
277
278 // Recover by taking the template that we found in the object
279 // expression's type.
280 }
281 }
282 }
283}
284
285/// Constructs a full type for the given nested-name-specifier.
286static QualType GetTypeForQualifier(ASTContext &Context,
287 NestedNameSpecifier *Qualifier) {
288 // Three possibilities:
289
290 // 1. A namespace (global or not).
291 assert(!Qualifier->getAsNamespace() && "can't construct type for namespace");
292
293 // 2. A type (templated or not).
294 Type *Ty = Qualifier->getAsType();
295 if (Ty) return QualType(Ty, 0);
296
297 // 3. A dependent identifier.
298 assert(Qualifier->getAsIdentifier());
299 return Context.getTypenameType(Qualifier->getPrefix(),
300 Qualifier->getAsIdentifier());
301}
302
303static bool HasDependentTypeAsBase(ASTContext &Context,
304 CXXRecordDecl *Record,
305 CanQualType T) {
306 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
307 E = Record->bases_end(); I != E; ++I) {
308 CanQualType BaseT = Context.getCanonicalType((*I).getType());
309 if (BaseT == T)
310 return true;
311
312 // We have to recurse here to cover some really bizarre cases.
313 // Obviously, we can only have the dependent type as an indirect
314 // base class through a dependent base class, and usually it's
315 // impossible to know which instantiation a dependent base class
316 // will have. But! If we're actually *inside* the dependent base
317 // class, then we know its instantiation and can therefore be
318 // reasonably expected to look into it.
319
320 // template <class T> class A : Base<T> {
321 // class Inner : A<T> {
322 // void foo() {
323 // Base<T>::foo(); // statically known to be an implicit member
324 // reference
325 // }
326 // };
327 // };
328
329 CanQual<RecordType> RT = BaseT->getAs<RecordType>();
John McCall45b1a472009-11-24 20:33:45 +0000330
331 // Base might be a dependent member type, in which case we
332 // obviously can't look into it.
333 if (!RT) continue;
334
John McCalle66edc12009-11-24 19:00:30 +0000335 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(RT->getDecl());
336 if (BaseRecord->isDefinition() &&
337 HasDependentTypeAsBase(Context, BaseRecord, T))
338 return true;
339 }
340
341 return false;
342}
343
344/// Checks whether the given dependent nested-name specifier
345/// introduces an implicit member reference. This is only true if the
346/// nested-name specifier names a type identical to one of the current
347/// instance method's context's (possibly indirect) base classes.
348static bool IsImplicitDependentMemberReference(Sema &SemaRef,
349 NestedNameSpecifier *Qualifier,
350 QualType &ThisType) {
351 // If the context isn't a C++ method, then it isn't an implicit
352 // member reference.
353 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext);
354 if (!MD || MD->isStatic())
355 return false;
356
357 ASTContext &Context = SemaRef.Context;
358
359 // We want to check whether the method's context is known to inherit
360 // from the type named by the nested name specifier. The trivial
361 // case here is:
362 // template <class T> class Base { ... };
363 // template <class T> class Derived : Base<T> {
364 // void foo() {
365 // Base<T>::foo();
366 // }
367 // };
368
369 QualType QT = GetTypeForQualifier(Context, Qualifier);
370 CanQualType T = Context.getCanonicalType(QT);
John McCall45b1a472009-11-24 20:33:45 +0000371
John McCalle66edc12009-11-24 19:00:30 +0000372 // And now, just walk the non-dependent type hierarchy, trying to
373 // find the given type as a literal base class.
374 CXXRecordDecl *Record = cast<CXXRecordDecl>(MD->getParent());
John McCall45b1a472009-11-24 20:33:45 +0000375 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T ||
376 HasDependentTypeAsBase(Context, Record, T)) {
377 ThisType = MD->getThisType(Context);
John McCalle66edc12009-11-24 19:00:30 +0000378 return true;
John McCall45b1a472009-11-24 20:33:45 +0000379 }
John McCalle66edc12009-11-24 19:00:30 +0000380
John McCall45b1a472009-11-24 20:33:45 +0000381 return false;
John McCalle66edc12009-11-24 19:00:30 +0000382}
383
384/// ActOnDependentIdExpression - Handle a dependent declaration name
385/// that was just parsed.
386Sema::OwningExprResult
387Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
388 DeclarationName Name,
389 SourceLocation NameLoc,
390 bool CheckForImplicitMember,
391 const TemplateArgumentListInfo *TemplateArgs) {
392 NestedNameSpecifier *Qualifier
393 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
394
395 QualType ThisType;
396 if (CheckForImplicitMember &&
397 IsImplicitDependentMemberReference(*this, Qualifier, ThisType)) {
398 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
399
400 // Since the 'this' expression is synthesized, we don't need to
401 // perform the double-lookup check.
402 NamedDecl *FirstQualifierInScope = 0;
403
404 return Owned(CXXDependentScopeMemberExpr::Create(Context, This, true,
405 /*Op*/ SourceLocation(),
406 Qualifier, SS.getRange(),
407 FirstQualifierInScope,
408 Name, NameLoc,
409 TemplateArgs));
410 }
411
412 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
413}
414
415Sema::OwningExprResult
416Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
417 DeclarationName Name,
418 SourceLocation NameLoc,
419 const TemplateArgumentListInfo *TemplateArgs) {
420 return Owned(DependentScopeDeclRefExpr::Create(Context,
421 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
422 SS.getRange(),
423 Name, NameLoc,
424 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000425}
426
Douglas Gregor5101c242008-12-05 18:15:24 +0000427/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
428/// that the template parameter 'PrevDecl' is being shadowed by a new
429/// declaration at location Loc. Returns true to indicate that this is
430/// an error, and false otherwise.
431bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000432 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000433
434 // Microsoft Visual C++ permits template parameters to be shadowed.
435 if (getLangOptions().Microsoft)
436 return false;
437
438 // C++ [temp.local]p4:
439 // A template-parameter shall not be redeclared within its
440 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000441 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000442 << cast<NamedDecl>(PrevDecl)->getDeclName();
443 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
444 return true;
445}
446
Douglas Gregor463421d2009-03-03 04:44:36 +0000447/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000448/// the parameter D to reference the templated declaration and return a pointer
449/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000450TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000451 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000452 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000453 return Temp;
454 }
455 return 0;
456}
457
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000458static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
459 const ParsedTemplateArgument &Arg) {
460
461 switch (Arg.getKind()) {
462 case ParsedTemplateArgument::Type: {
463 DeclaratorInfo *DI;
464 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
465 if (!DI)
466 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
467 return TemplateArgumentLoc(TemplateArgument(T), DI);
468 }
469
470 case ParsedTemplateArgument::NonType: {
471 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
472 return TemplateArgumentLoc(TemplateArgument(E), E);
473 }
474
475 case ParsedTemplateArgument::Template: {
476 TemplateName Template
477 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
478 return TemplateArgumentLoc(TemplateArgument(Template),
479 Arg.getScopeSpec().getRange(),
480 Arg.getLocation());
481 }
482 }
483
484 llvm::llvm_unreachable("Unhandled parsed template argument");
485 return TemplateArgumentLoc();
486}
487
488/// \brief Translates template arguments as provided by the parser
489/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000490void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
491 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000492 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000493 TemplateArgs.addArgument(translateTemplateArgument(*this,
494 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000495}
496
Douglas Gregor5101c242008-12-05 18:15:24 +0000497/// ActOnTypeParameter - Called when a C++ template type parameter
498/// (e.g., "typename T") has been parsed. Typename specifies whether
499/// the keyword "typename" was used to declare the type parameter
500/// (otherwise, "class" was used), and KeyLoc is the location of the
501/// "class" or "typename" keyword. ParamName is the name of the
502/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000503/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000504/// If the type parameter has a default argument, it will be added
505/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000506Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000507 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000508 SourceLocation KeyLoc,
509 IdentifierInfo *ParamName,
510 SourceLocation ParamNameLoc,
511 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000512 assert(S->isTemplateParamScope() &&
513 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000514 bool Invalid = false;
515
516 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000517 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000518 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000519 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000520 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000521 }
522
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000523 SourceLocation Loc = ParamNameLoc;
524 if (!ParamName)
525 Loc = KeyLoc;
526
Douglas Gregor5101c242008-12-05 18:15:24 +0000527 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000528 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
529 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000530 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000531 if (Invalid)
532 Param->setInvalidDecl();
533
534 if (ParamName) {
535 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000536 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000537 IdResolver.AddDecl(Param);
538 }
539
Chris Lattner83f095c2009-03-28 19:18:32 +0000540 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000541}
542
Douglas Gregordba32632009-02-10 19:49:53 +0000543/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000544/// Default) to the given template type parameter (TypeParam).
545void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000546 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000547 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000548 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000549 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000550 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000551
552 DeclaratorInfo *DefaultDInfo;
553 GetTypeFromParser(DefaultT, &DefaultDInfo);
554
555 assert(DefaultDInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000556
Anders Carlssond3824352009-06-12 22:30:13 +0000557 // C++0x [temp.param]p9:
558 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000559 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000560 if (Parm->isParameterPack()) {
561 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000562 return;
563 }
Mike Stump11289f42009-09-09 15:08:12 +0000564
Douglas Gregordba32632009-02-10 19:49:53 +0000565 // C++ [temp.param]p14:
566 // A template-parameter shall not be used in its own default argument.
567 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000568
Douglas Gregordba32632009-02-10 19:49:53 +0000569 // Check the template argument itself.
John McCall0ad16662009-10-29 08:12:44 +0000570 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000571 Parm->setInvalidDecl();
572 return;
573 }
574
John McCall0ad16662009-10-29 08:12:44 +0000575 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000576}
577
Douglas Gregor463421d2009-03-03 04:44:36 +0000578/// \brief Check that the type of a non-type template parameter is
579/// well-formed.
580///
581/// \returns the (possibly-promoted) parameter type if valid;
582/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000583QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000584Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
585 // C++ [temp.param]p4:
586 //
587 // A non-type template-parameter shall have one of the following
588 // (optionally cv-qualified) types:
589 //
590 // -- integral or enumeration type,
591 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000592 // -- pointer to object or pointer to function,
593 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000594 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
595 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000596 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000597 T->isReferenceType() ||
598 // -- pointer to member.
599 T->isMemberPointerType() ||
600 // If T is a dependent type, we can't do the check now, so we
601 // assume that it is well-formed.
602 T->isDependentType())
603 return T;
604 // C++ [temp.param]p8:
605 //
606 // A non-type template-parameter of type "array of T" or
607 // "function returning T" is adjusted to be of type "pointer to
608 // T" or "pointer to function returning T", respectively.
609 else if (T->isArrayType())
610 // FIXME: Keep the type prior to promotion?
611 return Context.getArrayDecayedType(T);
612 else if (T->isFunctionType())
613 // FIXME: Keep the type prior to promotion?
614 return Context.getPointerType(T);
615
616 Diag(Loc, diag::err_template_nontype_parm_bad_type)
617 << T;
618
619 return QualType();
620}
621
Douglas Gregor5101c242008-12-05 18:15:24 +0000622/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
623/// template parameter (e.g., "int Size" in "template<int Size>
624/// class Array") has been parsed. S is the current scope and D is
625/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000626Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000627 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000628 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000629 DeclaratorInfo *DInfo = 0;
630 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000631
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000632 assert(S->isTemplateParamScope() &&
633 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000634 bool Invalid = false;
635
636 IdentifierInfo *ParamName = D.getIdentifier();
637 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000638 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000639 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000640 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000641 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000642 }
643
Douglas Gregor463421d2009-03-03 04:44:36 +0000644 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000645 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000646 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000647 Invalid = true;
648 }
Douglas Gregor81338792009-02-10 17:43:50 +0000649
Douglas Gregor5101c242008-12-05 18:15:24 +0000650 NonTypeTemplateParmDecl *Param
651 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000652 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000653 if (Invalid)
654 Param->setInvalidDecl();
655
656 if (D.getIdentifier()) {
657 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000658 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000659 IdResolver.AddDecl(Param);
660 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000661 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000662}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000663
Douglas Gregordba32632009-02-10 19:49:53 +0000664/// \brief Adds a default argument to the given non-type template
665/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000666void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000667 SourceLocation EqualLoc,
668 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000669 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000670 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000671 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000672
Douglas Gregordba32632009-02-10 19:49:53 +0000673 // C++ [temp.param]p14:
674 // A template-parameter shall not be used in its own default argument.
675 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000676
Douglas Gregordba32632009-02-10 19:49:53 +0000677 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000678 TemplateArgument Converted;
679 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
680 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000681 TemplateParm->setInvalidDecl();
682 return;
683 }
684
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000685 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000686}
687
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000688
689/// ActOnTemplateTemplateParameter - Called when a C++ template template
690/// parameter (e.g. T in template <template <typename> class T> class array)
691/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000692Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
693 SourceLocation TmpLoc,
694 TemplateParamsTy *Params,
695 IdentifierInfo *Name,
696 SourceLocation NameLoc,
697 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000698 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000699 assert(S->isTemplateParamScope() &&
700 "Template template parameter not in template parameter scope!");
701
702 // Construct the parameter object.
703 TemplateTemplateParmDecl *Param =
704 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
705 Position, Name,
706 (TemplateParameterList*)Params);
707
708 // Make sure the parameter is valid.
709 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
710 // do anything yet. However, if the template parameter list or (eventual)
711 // default value is ever invalidated, that will propagate here.
712 bool Invalid = false;
713 if (Invalid) {
714 Param->setInvalidDecl();
715 }
716
717 // If the tt-param has a name, then link the identifier into the scope
718 // and lookup mechanisms.
719 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000720 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000721 IdResolver.AddDecl(Param);
722 }
723
Chris Lattner83f095c2009-03-28 19:18:32 +0000724 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000725}
726
Douglas Gregordba32632009-02-10 19:49:53 +0000727/// \brief Adds a default argument to the given template template
728/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000729void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000730 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000731 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000732 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000733 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000734
Douglas Gregordba32632009-02-10 19:49:53 +0000735 // C++ [temp.param]p14:
736 // A template-parameter shall not be used in its own default argument.
737 // FIXME: Implement this check! Needs a recursive walk over the types.
738
Douglas Gregore62e6a02009-11-11 19:13:48 +0000739 // Check only that we have a template template argument. We don't want to
740 // try to check well-formedness now, because our template template parameter
741 // might have dependent types in its template parameters, which we wouldn't
742 // be able to match now.
743 //
744 // If none of the template template parameter's template arguments mention
745 // other template parameters, we could actually perform more checking here.
746 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000747 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000748 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
749 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
750 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000751 return;
752 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000753
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000754 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000755}
756
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000757/// ActOnTemplateParameterList - Builds a TemplateParameterList that
758/// contains the template parameters in Params/NumParams.
759Sema::TemplateParamsTy *
760Sema::ActOnTemplateParameterList(unsigned Depth,
761 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000762 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000763 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000764 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000765 SourceLocation RAngleLoc) {
766 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000767 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000768
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000769 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000770 (NamedDecl**)Params, NumParams,
771 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000772}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000773
Douglas Gregorc08f4892009-03-25 00:13:59 +0000774Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000775Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000776 SourceLocation KWLoc, const CXXScopeSpec &SS,
777 IdentifierInfo *Name, SourceLocation NameLoc,
778 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000779 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000780 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000781 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000782 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000783 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000784 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000785
786 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000787 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000788 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000789
John McCall27b5c252009-09-14 21:59:20 +0000790 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
791 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000792
793 // There is no such thing as an unnamed class template.
794 if (!Name) {
795 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000796 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000797 }
798
799 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000800 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000801 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000802 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000803 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000804 if (RequireCompleteDeclContext(SS))
805 return true;
806
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000807 SemanticContext = computeDeclContext(SS, true);
808 if (!SemanticContext) {
809 // FIXME: Produce a reasonable diagnostic here
810 return true;
811 }
Mike Stump11289f42009-09-09 15:08:12 +0000812
John McCall27b18f82009-11-17 02:14:36 +0000813 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000814 } else {
815 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000816 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000817 }
Mike Stump11289f42009-09-09 15:08:12 +0000818
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000819 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
820 NamedDecl *PrevDecl = 0;
821 if (Previous.begin() != Previous.end())
822 PrevDecl = *Previous.begin();
823
Douglas Gregor9acb6902009-09-26 07:05:09 +0000824 if (PrevDecl && TUK == TUK_Friend) {
825 // C++ [namespace.memdef]p3:
826 // [...] When looking for a prior declaration of a class or a function
827 // declared as a friend, and when the name of the friend class or
828 // function is neither a qualified name nor a template-id, scopes outside
829 // the innermost enclosing namespace scope are not considered.
830 DeclContext *OutermostContext = CurContext;
831 while (!OutermostContext->isFileContext())
832 OutermostContext = OutermostContext->getLookupParent();
833
834 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
835 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
836 SemanticContext = PrevDecl->getDeclContext();
837 } else {
838 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000839 // context we computed is the semantic context for our new
Douglas Gregor9acb6902009-09-26 07:05:09 +0000840 // declaration.
841 PrevDecl = 0;
842 SemanticContext = OutermostContext;
843 }
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000844
845 if (CurContext->isDependentContext()) {
846 // If this is a dependent context, we don't want to link the friend
847 // class template to the template in scope, because that would perform
848 // checking of the template parameter lists that can't be performed
849 // until the outer context is instantiated.
850 PrevDecl = 0;
851 }
Douglas Gregor9acb6902009-09-26 07:05:09 +0000852 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000853 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000854
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000855 // If there is a previous declaration with the same name, check
856 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000857 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000858 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000859
860 // We may have found the injected-class-name of a class template,
861 // class template partial specialization, or class template specialization.
862 // In these cases, grab the template that is being defined or specialized.
863 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
864 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
865 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
866 PrevClassTemplate
867 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
868 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
869 PrevClassTemplate
870 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
871 ->getSpecializedTemplate();
872 }
873 }
874
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000875 if (PrevClassTemplate) {
876 // Ensure that the template parameter lists are compatible.
877 if (!TemplateParameterListsAreEqual(TemplateParams,
878 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000879 /*Complain=*/true,
880 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000881 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000882
883 // C++ [temp.class]p4:
884 // In a redeclaration, partial specialization, explicit
885 // specialization or explicit instantiation of a class template,
886 // the class-key shall agree in kind with the original class
887 // template declaration (7.1.5.3).
888 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000889 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000890 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000891 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000892 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000893 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000894 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000895 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000896 }
897
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000898 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000899 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000900 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
901 Diag(NameLoc, diag::err_redefinition) << Name;
902 Diag(Def->getLocation(), diag::note_previous_definition);
903 // FIXME: Would it make sense to try to "forget" the previous
904 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000905 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000906 }
907 }
908 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
909 // Maybe we will complain about the shadowed template parameter.
910 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
911 // Just pretend that we didn't see the previous declaration.
912 PrevDecl = 0;
913 } else if (PrevDecl) {
914 // C++ [temp]p5:
915 // A class template shall not have the same name as any other
916 // template, class, function, object, enumeration, enumerator,
917 // namespace, or type in the same scope (3.3), except as specified
918 // in (14.5.4).
919 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
920 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000921 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000922 }
923
Douglas Gregordba32632009-02-10 19:49:53 +0000924 // Check the template parameter list of this declaration, possibly
925 // merging in the template parameter list from the previous class
926 // template declaration.
927 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000928 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
929 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000930 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000931
Douglas Gregore362cea2009-05-10 22:57:19 +0000932 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000933 // declaration!
934
Mike Stump11289f42009-09-09 15:08:12 +0000935 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000936 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000937 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000938 PrevClassTemplate->getTemplatedDecl() : 0,
939 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000940
941 ClassTemplateDecl *NewTemplate
942 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
943 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000944 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000945 NewClass->setDescribedClassTemplate(NewTemplate);
946
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000947 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000948 QualType T =
949 Context.getTypeDeclType(NewClass,
950 PrevClassTemplate?
951 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000952 assert(T->isDependentType() && "Class template type is not dependent?");
953 (void)T;
954
Douglas Gregorcf915552009-10-13 16:30:37 +0000955 // If we are providing an explicit specialization of a member that is a
956 // class template, make a note of that.
957 if (PrevClassTemplate &&
958 PrevClassTemplate->getInstantiatedFromMemberTemplate())
959 PrevClassTemplate->setMemberSpecialization();
960
Anders Carlsson137108d2009-03-26 01:24:28 +0000961 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000962 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000963 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000965 // Set the lexical context of these templates
966 NewClass->setLexicalDeclContext(CurContext);
967 NewTemplate->setLexicalDeclContext(CurContext);
968
John McCall9bb74a52009-07-31 02:45:11 +0000969 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000970 NewClass->startDefinition();
971
972 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000973 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000974
John McCall27b5c252009-09-14 21:59:20 +0000975 if (TUK != TUK_Friend)
976 PushOnScopeChains(NewTemplate, S);
977 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000978 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000979 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000980 NewClass->setAccess(PrevClassTemplate->getAccess());
981 }
John McCall27b5c252009-09-14 21:59:20 +0000982
Douglas Gregor3dad8422009-09-26 06:47:28 +0000983 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
984 PrevClassTemplate != NULL);
985
John McCall27b5c252009-09-14 21:59:20 +0000986 // Friend templates are visible in fairly strange ways.
987 if (!CurContext->isDependentContext()) {
988 DeclContext *DC = SemanticContext->getLookupContext();
989 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
990 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
991 PushOnScopeChains(NewTemplate, EnclosingScope,
992 /* AddToContext = */ false);
993 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000994
995 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
996 NewClass->getLocation(),
997 NewTemplate,
998 /*FIXME:*/NewClass->getLocation());
999 Friend->setAccess(AS_public);
1000 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001001 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001002
Douglas Gregordba32632009-02-10 19:49:53 +00001003 if (Invalid) {
1004 NewTemplate->setInvalidDecl();
1005 NewClass->setInvalidDecl();
1006 }
Chris Lattner83f095c2009-03-28 19:18:32 +00001007 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001008}
1009
Douglas Gregored5731f2009-11-25 17:50:39 +00001010/// \brief Diagnose the presence of a default template argument on a
1011/// template parameter, which is ill-formed in certain contexts.
1012///
1013/// \returns true if the default template argument should be dropped.
1014static bool DiagnoseDefaultTemplateArgument(Sema &S,
1015 Sema::TemplateParamListContext TPC,
1016 SourceLocation ParamLoc,
1017 SourceRange DefArgRange) {
1018 switch (TPC) {
1019 case Sema::TPC_ClassTemplate:
1020 return false;
1021
1022 case Sema::TPC_FunctionTemplate:
1023 // C++ [temp.param]p9:
1024 // A default template-argument shall not be specified in a
1025 // function template declaration or a function template
1026 // definition [...]
1027 // (This sentence is not in C++0x, per DR226).
1028 if (!S.getLangOptions().CPlusPlus0x)
1029 S.Diag(ParamLoc,
1030 diag::err_template_parameter_default_in_function_template)
1031 << DefArgRange;
1032 return false;
1033
1034 case Sema::TPC_ClassTemplateMember:
1035 // C++0x [temp.param]p9:
1036 // A default template-argument shall not be specified in the
1037 // template-parameter-lists of the definition of a member of a
1038 // class template that appears outside of the member's class.
1039 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1040 << DefArgRange;
1041 return true;
1042
1043 case Sema::TPC_FriendFunctionTemplate:
1044 // C++ [temp.param]p9:
1045 // A default template-argument shall not be specified in a
1046 // friend template declaration.
1047 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1048 << DefArgRange;
1049 return true;
1050
1051 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1052 // for friend function templates if there is only a single
1053 // declaration (and it is a definition). Strange!
1054 }
1055
1056 return false;
1057}
1058
Douglas Gregordba32632009-02-10 19:49:53 +00001059/// \brief Checks the validity of a template parameter list, possibly
1060/// considering the template parameter list from a previous
1061/// declaration.
1062///
1063/// If an "old" template parameter list is provided, it must be
1064/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1065/// template parameter list.
1066///
1067/// \param NewParams Template parameter list for a new template
1068/// declaration. This template parameter list will be updated with any
1069/// default arguments that are carried through from the previous
1070/// template parameter list.
1071///
1072/// \param OldParams If provided, template parameter list from a
1073/// previous declaration of the same template. Default template
1074/// arguments will be merged from the old template parameter list to
1075/// the new template parameter list.
1076///
Douglas Gregored5731f2009-11-25 17:50:39 +00001077/// \param TPC Describes the context in which we are checking the given
1078/// template parameter list.
1079///
Douglas Gregordba32632009-02-10 19:49:53 +00001080/// \returns true if an error occurred, false otherwise.
1081bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001082 TemplateParameterList *OldParams,
1083 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001084 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001085
Douglas Gregordba32632009-02-10 19:49:53 +00001086 // C++ [temp.param]p10:
1087 // The set of default template-arguments available for use with a
1088 // template declaration or definition is obtained by merging the
1089 // default arguments from the definition (if in scope) and all
1090 // declarations in scope in the same way default function
1091 // arguments are (8.3.6).
1092 bool SawDefaultArgument = false;
1093 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001094
Anders Carlsson327865d2009-06-12 23:20:15 +00001095 bool SawParameterPack = false;
1096 SourceLocation ParameterPackLoc;
1097
Mike Stumpc89c8e32009-02-11 23:03:27 +00001098 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001099 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001100 if (OldParams)
1101 OldParam = OldParams->begin();
1102
1103 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1104 NewParamEnd = NewParams->end();
1105 NewParam != NewParamEnd; ++NewParam) {
1106 // Variables used to diagnose redundant default arguments
1107 bool RedundantDefaultArg = false;
1108 SourceLocation OldDefaultLoc;
1109 SourceLocation NewDefaultLoc;
1110
1111 // Variables used to diagnose missing default arguments
1112 bool MissingDefaultArg = false;
1113
Anders Carlsson327865d2009-06-12 23:20:15 +00001114 // C++0x [temp.param]p11:
1115 // If a template parameter of a class template is a template parameter pack,
1116 // it must be the last template parameter.
1117 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001118 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001119 diag::err_template_param_pack_must_be_last_template_parameter);
1120 Invalid = true;
1121 }
1122
Douglas Gregordba32632009-02-10 19:49:53 +00001123 if (TemplateTypeParmDecl *NewTypeParm
1124 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001125 // Check the presence of a default argument here.
1126 if (NewTypeParm->hasDefaultArgument() &&
1127 DiagnoseDefaultTemplateArgument(*this, TPC,
1128 NewTypeParm->getLocation(),
1129 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1130 .getFullSourceRange()))
1131 NewTypeParm->removeDefaultArgument();
1132
1133 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001134 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001135 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001136
Anders Carlsson327865d2009-06-12 23:20:15 +00001137 if (NewTypeParm->isParameterPack()) {
1138 assert(!NewTypeParm->hasDefaultArgument() &&
1139 "Parameter packs can't have a default argument!");
1140 SawParameterPack = true;
1141 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001142 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001143 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001144 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1145 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1146 SawDefaultArgument = true;
1147 RedundantDefaultArg = true;
1148 PreviousDefaultArgLoc = NewDefaultLoc;
1149 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1150 // Merge the default argument from the old declaration to the
1151 // new declaration.
1152 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001153 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001154 true);
1155 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1156 } else if (NewTypeParm->hasDefaultArgument()) {
1157 SawDefaultArgument = true;
1158 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1159 } else if (SawDefaultArgument)
1160 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001161 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001162 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001163 // Check the presence of a default argument here.
1164 if (NewNonTypeParm->hasDefaultArgument() &&
1165 DiagnoseDefaultTemplateArgument(*this, TPC,
1166 NewNonTypeParm->getLocation(),
1167 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1168 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1169 NewNonTypeParm->setDefaultArgument(0);
1170 }
1171
Mike Stump12b8ce12009-08-04 21:02:39 +00001172 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001173 NonTypeTemplateParmDecl *OldNonTypeParm
1174 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001175 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001176 NewNonTypeParm->hasDefaultArgument()) {
1177 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1178 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1179 SawDefaultArgument = true;
1180 RedundantDefaultArg = true;
1181 PreviousDefaultArgLoc = NewDefaultLoc;
1182 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1183 // Merge the default argument from the old declaration to the
1184 // new declaration.
1185 SawDefaultArgument = true;
1186 // FIXME: We need to create a new kind of "default argument"
1187 // expression that points to a previous template template
1188 // parameter.
1189 NewNonTypeParm->setDefaultArgument(
1190 OldNonTypeParm->getDefaultArgument());
1191 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1192 } else if (NewNonTypeParm->hasDefaultArgument()) {
1193 SawDefaultArgument = true;
1194 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1195 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001196 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001197 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001198 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001199 TemplateTemplateParmDecl *NewTemplateParm
1200 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001201 if (NewTemplateParm->hasDefaultArgument() &&
1202 DiagnoseDefaultTemplateArgument(*this, TPC,
1203 NewTemplateParm->getLocation(),
1204 NewTemplateParm->getDefaultArgument().getSourceRange()))
1205 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1206
1207 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001208 TemplateTemplateParmDecl *OldTemplateParm
1209 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001210 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001211 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001212 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1213 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001214 SawDefaultArgument = true;
1215 RedundantDefaultArg = true;
1216 PreviousDefaultArgLoc = NewDefaultLoc;
1217 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1218 // Merge the default argument from the old declaration to the
1219 // new declaration.
1220 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001221 // FIXME: We need to create a new kind of "default argument" expression
1222 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001223 NewTemplateParm->setDefaultArgument(
1224 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001225 PreviousDefaultArgLoc
1226 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001227 } else if (NewTemplateParm->hasDefaultArgument()) {
1228 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001229 PreviousDefaultArgLoc
1230 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001231 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001232 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001233 }
1234
1235 if (RedundantDefaultArg) {
1236 // C++ [temp.param]p12:
1237 // A template-parameter shall not be given default arguments
1238 // by two different declarations in the same scope.
1239 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1240 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1241 Invalid = true;
1242 } else if (MissingDefaultArg) {
1243 // C++ [temp.param]p11:
1244 // If a template-parameter has a default template-argument,
1245 // all subsequent template-parameters shall have a default
1246 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001247 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001248 diag::err_template_param_default_arg_missing);
1249 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1250 Invalid = true;
1251 }
1252
1253 // If we have an old template parameter list that we're merging
1254 // in, move on to the next parameter.
1255 if (OldParams)
1256 ++OldParam;
1257 }
1258
1259 return Invalid;
1260}
Douglas Gregord32e0282009-02-09 23:23:08 +00001261
Mike Stump11289f42009-09-09 15:08:12 +00001262/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001263/// specifier, returning the template parameter list that applies to the
1264/// name.
1265///
1266/// \param DeclStartLoc the start of the declaration that has a scope
1267/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001268///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001269/// \param SS the scope specifier that will be matched to the given template
1270/// parameter lists. This scope specifier precedes a qualified name that is
1271/// being declared.
1272///
1273/// \param ParamLists the template parameter lists, from the outermost to the
1274/// innermost template parameter lists.
1275///
1276/// \param NumParamLists the number of template parameter lists in ParamLists.
1277///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001278/// \param IsExplicitSpecialization will be set true if the entity being
1279/// declared is an explicit specialization, false otherwise.
1280///
Mike Stump11289f42009-09-09 15:08:12 +00001281/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001282/// name that is preceded by the scope specifier @p SS. This template
1283/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001284/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001285/// template specialization), or may be NULL (if we were's declaring isn't
1286/// itself a template).
1287TemplateParameterList *
1288Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1289 const CXXScopeSpec &SS,
1290 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001291 unsigned NumParamLists,
1292 bool &IsExplicitSpecialization) {
1293 IsExplicitSpecialization = false;
1294
Douglas Gregord8d297c2009-07-21 23:53:31 +00001295 // Find the template-ids that occur within the nested-name-specifier. These
1296 // template-ids will match up with the template parameter lists.
1297 llvm::SmallVector<const TemplateSpecializationType *, 4>
1298 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001299 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1300 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001301 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1302 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001303 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001304 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1305 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1306 if (!Template)
1307 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001308
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001309 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001310 ClassTemplateSpecializationDecl *SpecDecl
1311 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1312 // If the nested name specifier refers to an explicit specialization,
1313 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001314 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1315 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001316 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001317 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001318 }
Mike Stump11289f42009-09-09 15:08:12 +00001319
Douglas Gregord8d297c2009-07-21 23:53:31 +00001320 TemplateIdsInSpecifier.push_back(SpecType);
1321 }
1322 }
Mike Stump11289f42009-09-09 15:08:12 +00001323
Douglas Gregord8d297c2009-07-21 23:53:31 +00001324 // Reverse the list of template-ids in the scope specifier, so that we can
1325 // more easily match up the template-ids and the template parameter lists.
1326 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001327
Douglas Gregord8d297c2009-07-21 23:53:31 +00001328 SourceLocation FirstTemplateLoc = DeclStartLoc;
1329 if (NumParamLists)
1330 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001331
Douglas Gregord8d297c2009-07-21 23:53:31 +00001332 // Match the template-ids found in the specifier to the template parameter
1333 // lists.
1334 unsigned Idx = 0;
1335 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1336 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001337 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1338 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001339 if (Idx >= NumParamLists) {
1340 // We have a template-id without a corresponding template parameter
1341 // list.
1342 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001343 // FIXME: the location information here isn't great.
1344 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001345 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001346 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001347 << SS.getRange();
1348 } else {
1349 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1350 << SS.getRange()
1351 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1352 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001353 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001354 }
1355 return 0;
1356 }
Mike Stump11289f42009-09-09 15:08:12 +00001357
Douglas Gregord8d297c2009-07-21 23:53:31 +00001358 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001359 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001360 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001361 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1362
Mike Stump11289f42009-09-09 15:08:12 +00001363 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001364 = dyn_cast<ClassTemplateDecl>(Template)) {
1365 TemplateParameterList *ExpectedTemplateParams = 0;
1366 // Is this template-id naming the primary template?
1367 if (Context.hasSameType(TemplateId,
1368 ClassTemplate->getInjectedClassNameType(Context)))
1369 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1370 // ... or a partial specialization?
1371 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1372 = ClassTemplate->findPartialSpecialization(TemplateId))
1373 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1374
1375 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001376 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001377 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001378 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001379 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001380
1381 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001382 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001383 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001384 diag::err_template_param_list_matches_nontemplate)
1385 << TemplateId
1386 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001387 else
1388 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001389 }
Mike Stump11289f42009-09-09 15:08:12 +00001390
Douglas Gregord8d297c2009-07-21 23:53:31 +00001391 // If there were at least as many template-ids as there were template
1392 // parameter lists, then there are no template parameter lists remaining for
1393 // the declaration itself.
1394 if (Idx >= NumParamLists)
1395 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001396
Douglas Gregord8d297c2009-07-21 23:53:31 +00001397 // If there were too many template parameter lists, complain about that now.
1398 if (Idx != NumParamLists - 1) {
1399 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001400 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001401 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001402 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1403 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001404 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1405 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001406
1407 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1408 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1409 diag::note_explicit_template_spec_does_not_need_header)
1410 << ExplicitSpecializationsInSpecifier.back();
1411 ExplicitSpecializationsInSpecifier.pop_back();
1412 }
1413
Douglas Gregord8d297c2009-07-21 23:53:31 +00001414 ++Idx;
1415 }
1416 }
Mike Stump11289f42009-09-09 15:08:12 +00001417
Douglas Gregord8d297c2009-07-21 23:53:31 +00001418 // Return the last template parameter list, which corresponds to the
1419 // entity being declared.
1420 return ParamLists[NumParamLists - 1];
1421}
1422
Douglas Gregordc572a32009-03-30 22:58:21 +00001423QualType Sema::CheckTemplateIdType(TemplateName Name,
1424 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001425 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001426 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001427 if (!Template) {
1428 // The template name does not resolve to a template, so we just
1429 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001430 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001431 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001432
Douglas Gregorc40290e2009-03-09 23:48:35 +00001433 // Check that the template argument list is well-formed for this
1434 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001435 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001436 TemplateArgs.size());
1437 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001438 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001439 return QualType();
1440
Mike Stump11289f42009-09-09 15:08:12 +00001441 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001442 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001443 "Converted template argument list is too short!");
1444
1445 QualType CanonType;
1446
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001447 if (Name.isDependent() ||
1448 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001449 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001450 // This class template specialization is a dependent
1451 // type. Therefore, its canonical type is another class template
1452 // specialization type that contains all of the converted
1453 // arguments in canonical form. This ensures that, e.g., A<T> and
1454 // A<T, T> have identical types when A is declared as:
1455 //
1456 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001457 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001458 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001459 Converted.getFlatArguments(),
1460 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001461
Douglas Gregora8e02e72009-07-28 23:00:59 +00001462 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001463 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001464 // In the future, we need to teach getTemplateSpecializationType to only
1465 // build the canonical type and return that to us.
1466 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001467 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001468 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001469 // Find the class template specialization declaration that
1470 // corresponds to these arguments.
1471 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001472 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001473 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001474 Converted.flatSize(),
1475 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001476 void *InsertPos = 0;
1477 ClassTemplateSpecializationDecl *Decl
1478 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1479 if (!Decl) {
1480 // This is the first time we have referenced this class template
1481 // specialization. Create the canonical declaration and add it to
1482 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001483 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001484 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001485 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001486 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001487 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001488 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1489 Decl->setLexicalDeclContext(CurContext);
1490 }
1491
1492 CanonType = Context.getTypeDeclType(Decl);
1493 }
Mike Stump11289f42009-09-09 15:08:12 +00001494
Douglas Gregorc40290e2009-03-09 23:48:35 +00001495 // Build the fully-sugared type for this class template
1496 // specialization, which refers back to the class template
1497 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001498 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001499}
1500
Douglas Gregor67a65642009-02-17 23:15:12 +00001501Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001502Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001503 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001504 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001505 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001506 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001507
Douglas Gregorc40290e2009-03-09 23:48:35 +00001508 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001509 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001510 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001511
John McCall6b51f282009-11-23 01:53:49 +00001512 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001513 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001514
1515 if (Result.isNull())
1516 return true;
1517
John McCall0ad16662009-10-29 08:12:44 +00001518 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1519 TemplateSpecializationTypeLoc TL
1520 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1521 TL.setTemplateNameLoc(TemplateLoc);
1522 TL.setLAngleLoc(LAngleLoc);
1523 TL.setRAngleLoc(RAngleLoc);
1524 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1525 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1526
1527 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001528}
John McCall06f6fe8d2009-09-04 01:14:41 +00001529
John McCalld8fe9af2009-09-08 17:47:29 +00001530Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1531 TagUseKind TUK,
1532 DeclSpec::TST TagSpec,
1533 SourceLocation TagLoc) {
1534 if (TypeResult.isInvalid())
1535 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001536
John McCall0ad16662009-10-29 08:12:44 +00001537 // FIXME: preserve source info, ideally without copying the DI.
1538 DeclaratorInfo *DI;
1539 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001540
John McCalld8fe9af2009-09-08 17:47:29 +00001541 // Verify the tag specifier.
1542 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001543
John McCalld8fe9af2009-09-08 17:47:29 +00001544 if (const RecordType *RT = Type->getAs<RecordType>()) {
1545 RecordDecl *D = RT->getDecl();
1546
1547 IdentifierInfo *Id = D->getIdentifier();
1548 assert(Id && "templated class must have an identifier");
1549
1550 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1551 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001552 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001553 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1554 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001555 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001556 }
1557 }
1558
John McCalld8fe9af2009-09-08 17:47:29 +00001559 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1560
1561 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001562}
1563
John McCalle66edc12009-11-24 19:00:30 +00001564Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1565 LookupResult &R,
1566 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001567 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001568 // FIXME: Can we do any checking at this point? I guess we could check the
1569 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001570 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001571 // though.
John McCalle66edc12009-11-24 19:00:30 +00001572
1573 // These should be filtered out by our callers.
1574 assert(!R.empty() && "empty lookup results when building templateid");
1575 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1576
1577 NestedNameSpecifier *Qualifier = 0;
1578 SourceRange QualifierRange;
1579 if (SS.isSet()) {
1580 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1581 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001582 }
1583
John McCalle66edc12009-11-24 19:00:30 +00001584 bool Dependent
1585 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1586 &TemplateArgs);
1587 UnresolvedLookupExpr *ULE
1588 = UnresolvedLookupExpr::Create(Context, Dependent,
1589 Qualifier, QualifierRange,
1590 R.getLookupName(), R.getNameLoc(),
1591 RequiresADL, TemplateArgs);
1592 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1593 ULE->addDecl(*I);
1594
1595 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001596}
1597
John McCalle66edc12009-11-24 19:00:30 +00001598// We actually only call this from template instantiation.
1599Sema::OwningExprResult
1600Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1601 DeclarationName Name,
1602 SourceLocation NameLoc,
1603 const TemplateArgumentListInfo &TemplateArgs) {
1604 DeclContext *DC;
1605 if (!(DC = computeDeclContext(SS, false)) ||
1606 DC->isDependentContext() ||
1607 RequireCompleteDeclContext(SS))
1608 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001609
John McCalle66edc12009-11-24 19:00:30 +00001610 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1611 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001612
John McCalle66edc12009-11-24 19:00:30 +00001613 if (R.isAmbiguous())
1614 return ExprError();
1615
1616 if (R.empty()) {
1617 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1618 << Name << SS.getRange();
1619 return ExprError();
1620 }
1621
1622 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1623 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1624 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1625 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1626 return ExprError();
1627 }
1628
1629 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001630}
1631
Douglas Gregorb67535d2009-03-31 00:43:58 +00001632/// \brief Form a dependent template name.
1633///
1634/// This action forms a dependent template name given the template
1635/// name and its (presumably dependent) scope specifier. For
1636/// example, given "MetaFun::template apply", the scope specifier \p
1637/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1638/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001639Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001640Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001641 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001642 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001643 TypeTy *ObjectType,
1644 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001645 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001646 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001647 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001648 // C++0x [temp.names]p5:
1649 // If a name prefixed by the keyword template is not the name of
1650 // a template, the program is ill-formed. [Note: the keyword
1651 // template may not be applied to non-template members of class
1652 // templates. -end note ] [ Note: as is the case with the
1653 // typename prefix, the template prefix is allowed in cases
1654 // where it is not strictly necessary; i.e., when the
1655 // nested-name-specifier or the expression on the left of the ->
1656 // or . is not dependent on a template-parameter, or the use
1657 // does not appear in the scope of a template. -end note]
1658 //
1659 // Note: C++03 was more strict here, because it banned the use of
1660 // the "template" keyword prior to a template-name that was not a
1661 // dependent name. C++ DR468 relaxed this requirement (the
1662 // "template" keyword is now permitted). We follow the C++0x
1663 // rules, even in C++03 mode, retroactively applying the DR.
1664 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001665 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001666 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001667 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001668 Diag(Name.getSourceRange().getBegin(),
1669 diag::err_template_kw_refers_to_non_template)
1670 << GetNameFromUnqualifiedId(Name)
1671 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001672 return TemplateTy();
1673 }
1674
1675 return Template;
1676 }
1677
Mike Stump11289f42009-09-09 15:08:12 +00001678 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001679 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001680
1681 switch (Name.getKind()) {
1682 case UnqualifiedId::IK_Identifier:
1683 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1684 Name.Identifier));
1685
Douglas Gregor71395fa2009-11-04 00:56:37 +00001686 case UnqualifiedId::IK_OperatorFunctionId:
1687 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1688 Name.OperatorFunctionId.Operator));
1689
Douglas Gregor3cf81312009-11-03 23:16:33 +00001690 default:
1691 break;
1692 }
1693
1694 Diag(Name.getSourceRange().getBegin(),
1695 diag::err_template_kw_refers_to_non_template)
1696 << GetNameFromUnqualifiedId(Name)
1697 << Name.getSourceRange();
1698 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001699}
1700
Mike Stump11289f42009-09-09 15:08:12 +00001701bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001702 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001703 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001704 const TemplateArgument &Arg = AL.getArgument();
1705
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001706 // Check template type parameter.
1707 if (Arg.getKind() != TemplateArgument::Type) {
1708 // C++ [temp.arg.type]p1:
1709 // A template-argument for a template-parameter which is a
1710 // type shall be a type-id.
1711
1712 // We have a template type parameter but the template argument
1713 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001714 SourceRange SR = AL.getSourceRange();
1715 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001716 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001717
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001718 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001719 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001720
John McCall0ad16662009-10-29 08:12:44 +00001721 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001722 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001723
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001724 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001725 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001726 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001727 return false;
1728}
1729
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001730/// \brief Substitute template arguments into the default template argument for
1731/// the given template type parameter.
1732///
1733/// \param SemaRef the semantic analysis object for which we are performing
1734/// the substitution.
1735///
1736/// \param Template the template that we are synthesizing template arguments
1737/// for.
1738///
1739/// \param TemplateLoc the location of the template name that started the
1740/// template-id we are checking.
1741///
1742/// \param RAngleLoc the location of the right angle bracket ('>') that
1743/// terminates the template-id.
1744///
1745/// \param Param the template template parameter whose default we are
1746/// substituting into.
1747///
1748/// \param Converted the list of template arguments provided for template
1749/// parameters that precede \p Param in the template parameter list.
1750///
1751/// \returns the substituted template argument, or NULL if an error occurred.
1752static DeclaratorInfo *
1753SubstDefaultTemplateArgument(Sema &SemaRef,
1754 TemplateDecl *Template,
1755 SourceLocation TemplateLoc,
1756 SourceLocation RAngleLoc,
1757 TemplateTypeParmDecl *Param,
1758 TemplateArgumentListBuilder &Converted) {
1759 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1760
1761 // If the argument type is dependent, instantiate it now based
1762 // on the previously-computed template arguments.
1763 if (ArgType->getType()->isDependentType()) {
1764 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1765 /*TakeArgs=*/false);
1766
1767 MultiLevelTemplateArgumentList AllTemplateArgs
1768 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1769
1770 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1771 Template, Converted.getFlatArguments(),
1772 Converted.flatSize(),
1773 SourceRange(TemplateLoc, RAngleLoc));
1774
1775 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1776 Param->getDefaultArgumentLoc(),
1777 Param->getDeclName());
1778 }
1779
1780 return ArgType;
1781}
1782
1783/// \brief Substitute template arguments into the default template argument for
1784/// the given non-type template parameter.
1785///
1786/// \param SemaRef the semantic analysis object for which we are performing
1787/// the substitution.
1788///
1789/// \param Template the template that we are synthesizing template arguments
1790/// for.
1791///
1792/// \param TemplateLoc the location of the template name that started the
1793/// template-id we are checking.
1794///
1795/// \param RAngleLoc the location of the right angle bracket ('>') that
1796/// terminates the template-id.
1797///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001798/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001799/// substituting into.
1800///
1801/// \param Converted the list of template arguments provided for template
1802/// parameters that precede \p Param in the template parameter list.
1803///
1804/// \returns the substituted template argument, or NULL if an error occurred.
1805static Sema::OwningExprResult
1806SubstDefaultTemplateArgument(Sema &SemaRef,
1807 TemplateDecl *Template,
1808 SourceLocation TemplateLoc,
1809 SourceLocation RAngleLoc,
1810 NonTypeTemplateParmDecl *Param,
1811 TemplateArgumentListBuilder &Converted) {
1812 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1813 /*TakeArgs=*/false);
1814
1815 MultiLevelTemplateArgumentList AllTemplateArgs
1816 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1817
1818 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1819 Template, Converted.getFlatArguments(),
1820 Converted.flatSize(),
1821 SourceRange(TemplateLoc, RAngleLoc));
1822
1823 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1824}
1825
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001826/// \brief Substitute template arguments into the default template argument for
1827/// the given template template parameter.
1828///
1829/// \param SemaRef the semantic analysis object for which we are performing
1830/// the substitution.
1831///
1832/// \param Template the template that we are synthesizing template arguments
1833/// for.
1834///
1835/// \param TemplateLoc the location of the template name that started the
1836/// template-id we are checking.
1837///
1838/// \param RAngleLoc the location of the right angle bracket ('>') that
1839/// terminates the template-id.
1840///
1841/// \param Param the template template parameter whose default we are
1842/// substituting into.
1843///
1844/// \param Converted the list of template arguments provided for template
1845/// parameters that precede \p Param in the template parameter list.
1846///
1847/// \returns the substituted template argument, or NULL if an error occurred.
1848static TemplateName
1849SubstDefaultTemplateArgument(Sema &SemaRef,
1850 TemplateDecl *Template,
1851 SourceLocation TemplateLoc,
1852 SourceLocation RAngleLoc,
1853 TemplateTemplateParmDecl *Param,
1854 TemplateArgumentListBuilder &Converted) {
1855 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1856 /*TakeArgs=*/false);
1857
1858 MultiLevelTemplateArgumentList AllTemplateArgs
1859 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1860
1861 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1862 Template, Converted.getFlatArguments(),
1863 Converted.flatSize(),
1864 SourceRange(TemplateLoc, RAngleLoc));
1865
1866 return SemaRef.SubstTemplateName(
1867 Param->getDefaultArgument().getArgument().getAsTemplate(),
1868 Param->getDefaultArgument().getTemplateNameLoc(),
1869 AllTemplateArgs);
1870}
1871
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001872/// \brief If the given template parameter has a default template
1873/// argument, substitute into that default template argument and
1874/// return the corresponding template argument.
1875TemplateArgumentLoc
1876Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1877 SourceLocation TemplateLoc,
1878 SourceLocation RAngleLoc,
1879 Decl *Param,
1880 TemplateArgumentListBuilder &Converted) {
1881 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1882 if (!TypeParm->hasDefaultArgument())
1883 return TemplateArgumentLoc();
1884
1885 DeclaratorInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1886 TemplateLoc,
1887 RAngleLoc,
1888 TypeParm,
1889 Converted);
1890 if (DI)
1891 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1892
1893 return TemplateArgumentLoc();
1894 }
1895
1896 if (NonTypeTemplateParmDecl *NonTypeParm
1897 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1898 if (!NonTypeParm->hasDefaultArgument())
1899 return TemplateArgumentLoc();
1900
1901 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1902 TemplateLoc,
1903 RAngleLoc,
1904 NonTypeParm,
1905 Converted);
1906 if (Arg.isInvalid())
1907 return TemplateArgumentLoc();
1908
1909 Expr *ArgE = Arg.takeAs<Expr>();
1910 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1911 }
1912
1913 TemplateTemplateParmDecl *TempTempParm
1914 = cast<TemplateTemplateParmDecl>(Param);
1915 if (!TempTempParm->hasDefaultArgument())
1916 return TemplateArgumentLoc();
1917
1918 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1919 TemplateLoc,
1920 RAngleLoc,
1921 TempTempParm,
1922 Converted);
1923 if (TName.isNull())
1924 return TemplateArgumentLoc();
1925
1926 return TemplateArgumentLoc(TemplateArgument(TName),
1927 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1928 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1929}
1930
Douglas Gregorda0fb532009-11-11 19:31:23 +00001931/// \brief Check that the given template argument corresponds to the given
1932/// template parameter.
1933bool Sema::CheckTemplateArgument(NamedDecl *Param,
1934 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001935 TemplateDecl *Template,
1936 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001937 SourceLocation RAngleLoc,
1938 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001939 // Check template type parameters.
1940 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001941 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001942
Douglas Gregoreebed722009-11-11 19:41:09 +00001943 // Check non-type template parameters.
1944 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001945 // Do substitution on the type of the non-type template parameter
1946 // with the template arguments we've seen thus far.
1947 QualType NTTPType = NTTP->getType();
1948 if (NTTPType->isDependentType()) {
1949 // Do substitution on the type of the non-type template parameter.
1950 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1951 NTTP, Converted.getFlatArguments(),
1952 Converted.flatSize(),
1953 SourceRange(TemplateLoc, RAngleLoc));
1954
1955 TemplateArgumentList TemplateArgs(Context, Converted,
1956 /*TakeArgs=*/false);
1957 NTTPType = SubstType(NTTPType,
1958 MultiLevelTemplateArgumentList(TemplateArgs),
1959 NTTP->getLocation(),
1960 NTTP->getDeclName());
1961 // If that worked, check the non-type template parameter type
1962 // for validity.
1963 if (!NTTPType.isNull())
1964 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1965 NTTP->getLocation());
1966 if (NTTPType.isNull())
1967 return true;
1968 }
1969
1970 switch (Arg.getArgument().getKind()) {
1971 case TemplateArgument::Null:
1972 assert(false && "Should never see a NULL template argument here");
1973 return true;
1974
1975 case TemplateArgument::Expression: {
1976 Expr *E = Arg.getArgument().getAsExpr();
1977 TemplateArgument Result;
1978 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1979 return true;
1980
1981 Converted.Append(Result);
1982 break;
1983 }
1984
1985 case TemplateArgument::Declaration:
1986 case TemplateArgument::Integral:
1987 // We've already checked this template argument, so just copy
1988 // it to the list of converted arguments.
1989 Converted.Append(Arg.getArgument());
1990 break;
1991
1992 case TemplateArgument::Template:
1993 // We were given a template template argument. It may not be ill-formed;
1994 // see below.
1995 if (DependentTemplateName *DTN
1996 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1997 // We have a template argument such as \c T::template X, which we
1998 // parsed as a template template argument. However, since we now
1999 // know that we need a non-type template argument, convert this
2000 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00002001 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2002 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002003 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002004 DTN->getIdentifier(),
2005 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002006
2007 TemplateArgument Result;
2008 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2009 return true;
2010
2011 Converted.Append(Result);
2012 break;
2013 }
2014
2015 // We have a template argument that actually does refer to a class
2016 // template, template alias, or template template parameter, and
2017 // therefore cannot be a non-type template argument.
2018 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2019 << Arg.getSourceRange();
2020
2021 Diag(Param->getLocation(), diag::note_template_param_here);
2022 return true;
2023
2024 case TemplateArgument::Type: {
2025 // We have a non-type template parameter but the template
2026 // argument is a type.
2027
2028 // C++ [temp.arg]p2:
2029 // In a template-argument, an ambiguity between a type-id and
2030 // an expression is resolved to a type-id, regardless of the
2031 // form of the corresponding template-parameter.
2032 //
2033 // We warn specifically about this case, since it can be rather
2034 // confusing for users.
2035 QualType T = Arg.getArgument().getAsType();
2036 SourceRange SR = Arg.getSourceRange();
2037 if (T->isFunctionType())
2038 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2039 else
2040 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2041 Diag(Param->getLocation(), diag::note_template_param_here);
2042 return true;
2043 }
2044
2045 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00002046 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002047 break;
2048 }
2049
2050 return false;
2051 }
2052
2053
2054 // Check template template parameters.
2055 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2056
2057 // Substitute into the template parameter list of the template
2058 // template parameter, since previously-supplied template arguments
2059 // may appear within the template template parameter.
2060 {
2061 // Set up a template instantiation context.
2062 LocalInstantiationScope Scope(*this);
2063 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2064 TempParm, Converted.getFlatArguments(),
2065 Converted.flatSize(),
2066 SourceRange(TemplateLoc, RAngleLoc));
2067
2068 TemplateArgumentList TemplateArgs(Context, Converted,
2069 /*TakeArgs=*/false);
2070 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2071 SubstDecl(TempParm, CurContext,
2072 MultiLevelTemplateArgumentList(TemplateArgs)));
2073 if (!TempParm)
2074 return true;
2075
2076 // FIXME: TempParam is leaked.
2077 }
2078
2079 switch (Arg.getArgument().getKind()) {
2080 case TemplateArgument::Null:
2081 assert(false && "Should never see a NULL template argument here");
2082 return true;
2083
2084 case TemplateArgument::Template:
2085 if (CheckTemplateArgument(TempParm, Arg))
2086 return true;
2087
2088 Converted.Append(Arg.getArgument());
2089 break;
2090
2091 case TemplateArgument::Expression:
2092 case TemplateArgument::Type:
2093 // We have a template template parameter but the template
2094 // argument does not refer to a template.
2095 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2096 return true;
2097
2098 case TemplateArgument::Declaration:
2099 llvm::llvm_unreachable(
2100 "Declaration argument with template template parameter");
2101 break;
2102 case TemplateArgument::Integral:
2103 llvm::llvm_unreachable(
2104 "Integral argument with template template parameter");
2105 break;
2106
2107 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00002108 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002109 break;
2110 }
2111
2112 return false;
2113}
2114
Douglas Gregord32e0282009-02-09 23:23:08 +00002115/// \brief Check that the given template argument list is well-formed
2116/// for specializing the given template.
2117bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2118 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002119 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002120 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002121 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002122 TemplateParameterList *Params = Template->getTemplateParameters();
2123 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002124 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002125 bool Invalid = false;
2126
John McCall6b51f282009-11-23 01:53:49 +00002127 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2128
Mike Stump11289f42009-09-09 15:08:12 +00002129 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002130 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002131
Anders Carlsson15201f12009-06-13 02:08:00 +00002132 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002133 (NumArgs < Params->getMinRequiredArguments() &&
2134 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002135 // FIXME: point at either the first arg beyond what we can handle,
2136 // or the '>', depending on whether we have too many or too few
2137 // arguments.
2138 SourceRange Range;
2139 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002140 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002141 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2142 << (NumArgs > NumParams)
2143 << (isa<ClassTemplateDecl>(Template)? 0 :
2144 isa<FunctionTemplateDecl>(Template)? 1 :
2145 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2146 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002147 Diag(Template->getLocation(), diag::note_template_decl_here)
2148 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002149 Invalid = true;
2150 }
Mike Stump11289f42009-09-09 15:08:12 +00002151
2152 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002153 // [...] The type and form of each template-argument specified in
2154 // a template-id shall match the type and form specified for the
2155 // corresponding parameter declared by the template in its
2156 // template-parameter-list.
2157 unsigned ArgIdx = 0;
2158 for (TemplateParameterList::iterator Param = Params->begin(),
2159 ParamEnd = Params->end();
2160 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002161 if (ArgIdx > NumArgs && PartialTemplateArgs)
2162 break;
Mike Stump11289f42009-09-09 15:08:12 +00002163
Douglas Gregoreebed722009-11-11 19:41:09 +00002164 // If we have a template parameter pack, check every remaining template
2165 // argument against that template parameter pack.
2166 if ((*Param)->isTemplateParameterPack()) {
2167 Converted.BeginPack();
2168 for (; ArgIdx < NumArgs; ++ArgIdx) {
2169 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2170 TemplateLoc, RAngleLoc, Converted)) {
2171 Invalid = true;
2172 break;
2173 }
2174 }
2175 Converted.EndPack();
2176 continue;
2177 }
2178
Douglas Gregor84d49a22009-11-11 21:54:23 +00002179 if (ArgIdx < NumArgs) {
2180 // Check the template argument we were given.
2181 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2182 TemplateLoc, RAngleLoc, Converted))
2183 return true;
2184
2185 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002186 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002187
Douglas Gregor84d49a22009-11-11 21:54:23 +00002188 // We have a default template argument that we will use.
2189 TemplateArgumentLoc Arg;
2190
2191 // Retrieve the default template argument from the template
2192 // parameter. For each kind of template parameter, we substitute the
2193 // template arguments provided thus far and any "outer" template arguments
2194 // (when the template parameter was part of a nested template) into
2195 // the default argument.
2196 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2197 if (!TTP->hasDefaultArgument()) {
2198 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2199 break;
2200 }
2201
2202 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
2203 Template,
2204 TemplateLoc,
2205 RAngleLoc,
2206 TTP,
2207 Converted);
2208 if (!ArgType)
2209 return true;
2210
2211 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2212 ArgType);
2213 } else if (NonTypeTemplateParmDecl *NTTP
2214 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2215 if (!NTTP->hasDefaultArgument()) {
2216 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2217 break;
2218 }
2219
2220 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2221 TemplateLoc,
2222 RAngleLoc,
2223 NTTP,
2224 Converted);
2225 if (E.isInvalid())
2226 return true;
2227
2228 Expr *Ex = E.takeAs<Expr>();
2229 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2230 } else {
2231 TemplateTemplateParmDecl *TempParm
2232 = cast<TemplateTemplateParmDecl>(*Param);
2233
2234 if (!TempParm->hasDefaultArgument()) {
2235 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2236 break;
2237 }
2238
2239 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2240 TemplateLoc,
2241 RAngleLoc,
2242 TempParm,
2243 Converted);
2244 if (Name.isNull())
2245 return true;
2246
2247 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2248 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2249 TempParm->getDefaultArgument().getTemplateNameLoc());
2250 }
2251
2252 // Introduce an instantiation record that describes where we are using
2253 // the default template argument.
2254 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2255 Converted.getFlatArguments(),
2256 Converted.flatSize(),
2257 SourceRange(TemplateLoc, RAngleLoc));
2258
2259 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002260 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002261 RAngleLoc, Converted))
2262 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002263 }
2264
2265 return Invalid;
2266}
2267
2268/// \brief Check a template argument against its corresponding
2269/// template type parameter.
2270///
2271/// This routine implements the semantics of C++ [temp.arg.type]. It
2272/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002273bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00002274 DeclaratorInfo *ArgInfo) {
2275 assert(ArgInfo && "invalid DeclaratorInfo");
2276 QualType Arg = ArgInfo->getType();
2277
Douglas Gregord32e0282009-02-09 23:23:08 +00002278 // C++ [temp.arg.type]p2:
2279 // A local type, a type with no linkage, an unnamed type or a type
2280 // compounded from any of these types shall not be used as a
2281 // template-argument for a template type-parameter.
2282 //
2283 // FIXME: Perform the recursive and no-linkage type checks.
2284 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002285 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002286 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002287 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002288 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002289 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2290 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2291 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2292 << QualType(Tag, 0) << SR;
2293 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002294 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002295 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2296 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002297 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2298 return true;
2299 }
2300
2301 return false;
2302}
2303
Douglas Gregorccb07762009-02-11 19:52:55 +00002304/// \brief Checks whether the given template argument is the address
2305/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002306bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2307 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002308 bool Invalid = false;
2309
2310 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002311 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002312 Arg = Cast->getSubExpr();
2313
Sebastian Redl576fd422009-05-10 18:38:11 +00002314 // C++0x allows nullptr, and there's no further checking to be done for that.
2315 if (Arg->getType()->isNullPtrType())
2316 return false;
2317
Douglas Gregorccb07762009-02-11 19:52:55 +00002318 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002319 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002320 // A template-argument for a non-type, non-template
2321 // template-parameter shall be one of: [...]
2322 //
2323 // -- the address of an object or function with external
2324 // linkage, including function templates and function
2325 // template-ids but excluding non-static class members,
2326 // expressed as & id-expression where the & is optional if
2327 // the name refers to a function or array, or if the
2328 // corresponding template-parameter is a reference; or
2329 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002330
Douglas Gregorccb07762009-02-11 19:52:55 +00002331 // Ignore (and complain about) any excess parentheses.
2332 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2333 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002334 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002335 diag::err_template_arg_extra_parens)
2336 << Arg->getSourceRange();
2337 Invalid = true;
2338 }
2339
2340 Arg = Parens->getSubExpr();
2341 }
2342
2343 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2344 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2345 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2346 } else
2347 DRE = dyn_cast<DeclRefExpr>(Arg);
2348
2349 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002350 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002351 diag::err_template_arg_not_object_or_func_form)
2352 << Arg->getSourceRange();
2353
2354 // Cannot refer to non-static data members
2355 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2356 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2357 << Field << Arg->getSourceRange();
2358
2359 // Cannot refer to non-static member functions
2360 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2361 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002362 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002363 diag::err_template_arg_method)
2364 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002365
Douglas Gregorccb07762009-02-11 19:52:55 +00002366 // Functions must have external linkage.
2367 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2368 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00002369 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002370 diag::err_template_arg_function_not_extern)
2371 << Func << Arg->getSourceRange();
2372 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2373 << true;
2374 return true;
2375 }
2376
2377 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002378 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002379 return Invalid;
2380 }
2381
2382 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2383 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00002384 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002385 diag::err_template_arg_object_not_extern)
2386 << Var << Arg->getSourceRange();
2387 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2388 << true;
2389 return true;
2390 }
2391
2392 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002393 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002394 return Invalid;
2395 }
Mike Stump11289f42009-09-09 15:08:12 +00002396
Douglas Gregorccb07762009-02-11 19:52:55 +00002397 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002398 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002399 diag::err_template_arg_not_object_or_func)
2400 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002401 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002402 diag::note_template_arg_refers_here);
2403 return true;
2404}
2405
2406/// \brief Checks whether the given template argument is a pointer to
2407/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002408bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2409 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002410 bool Invalid = false;
2411
2412 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002413 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002414 Arg = Cast->getSubExpr();
2415
Sebastian Redl576fd422009-05-10 18:38:11 +00002416 // C++0x allows nullptr, and there's no further checking to be done for that.
2417 if (Arg->getType()->isNullPtrType())
2418 return false;
2419
Douglas Gregorccb07762009-02-11 19:52:55 +00002420 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002421 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002422 // A template-argument for a non-type, non-template
2423 // template-parameter shall be one of: [...]
2424 //
2425 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002426 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002427
2428 // Ignore (and complain about) any excess parentheses.
2429 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2430 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002431 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002432 diag::err_template_arg_extra_parens)
2433 << Arg->getSourceRange();
2434 Invalid = true;
2435 }
2436
2437 Arg = Parens->getSubExpr();
2438 }
2439
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002440 // A pointer-to-member constant written &Class::member.
2441 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002442 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2443 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2444 if (DRE && !DRE->getQualifier())
2445 DRE = 0;
2446 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002447 }
2448 // A constant of pointer-to-member type.
2449 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2450 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2451 if (VD->getType()->isMemberPointerType()) {
2452 if (isa<NonTypeTemplateParmDecl>(VD) ||
2453 (isa<VarDecl>(VD) &&
2454 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2455 if (Arg->isTypeDependent() || Arg->isValueDependent())
2456 Converted = TemplateArgument(Arg->Retain());
2457 else
2458 Converted = TemplateArgument(VD->getCanonicalDecl());
2459 return Invalid;
2460 }
2461 }
2462 }
2463
2464 DRE = 0;
2465 }
2466
Douglas Gregorccb07762009-02-11 19:52:55 +00002467 if (!DRE)
2468 return Diag(Arg->getSourceRange().getBegin(),
2469 diag::err_template_arg_not_pointer_to_member_form)
2470 << Arg->getSourceRange();
2471
2472 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2473 assert((isa<FieldDecl>(DRE->getDecl()) ||
2474 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2475 "Only non-static member pointers can make it here");
2476
2477 // Okay: this is the address of a non-static member, and therefore
2478 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002479 if (Arg->isTypeDependent() || Arg->isValueDependent())
2480 Converted = TemplateArgument(Arg->Retain());
2481 else
2482 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002483 return Invalid;
2484 }
2485
2486 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002487 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002488 diag::err_template_arg_not_pointer_to_member_form)
2489 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002490 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002491 diag::note_template_arg_refers_here);
2492 return true;
2493}
2494
Douglas Gregord32e0282009-02-09 23:23:08 +00002495/// \brief Check a template argument against its corresponding
2496/// non-type template parameter.
2497///
Douglas Gregor463421d2009-03-03 04:44:36 +00002498/// This routine implements the semantics of C++ [temp.arg.nontype].
2499/// It returns true if an error occurred, and false otherwise. \p
2500/// InstantiatedParamType is the type of the non-type template
2501/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002502///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002503/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002504bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002505 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002506 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002507 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2508
Douglas Gregor86560402009-02-10 23:36:10 +00002509 // If either the parameter has a dependent type or the argument is
2510 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002511 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002512 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2513 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002514 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002515 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002516 }
Douglas Gregor86560402009-02-10 23:36:10 +00002517
2518 // C++ [temp.arg.nontype]p5:
2519 // The following conversions are performed on each expression used
2520 // as a non-type template-argument. If a non-type
2521 // template-argument cannot be converted to the type of the
2522 // corresponding template-parameter then the program is
2523 // ill-formed.
2524 //
2525 // -- for a non-type template-parameter of integral or
2526 // enumeration type, integral promotions (4.5) and integral
2527 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002528 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002529 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002530 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002531 // C++ [temp.arg.nontype]p1:
2532 // A template-argument for a non-type, non-template
2533 // template-parameter shall be one of:
2534 //
2535 // -- an integral constant-expression of integral or enumeration
2536 // type; or
2537 // -- the name of a non-type template-parameter; or
2538 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002539 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002540 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002541 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002542 diag::err_template_arg_not_integral_or_enumeral)
2543 << ArgType << Arg->getSourceRange();
2544 Diag(Param->getLocation(), diag::note_template_param_here);
2545 return true;
2546 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002547 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002548 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2549 << ArgType << Arg->getSourceRange();
2550 return true;
2551 }
2552
2553 // FIXME: We need some way to more easily get the unqualified form
2554 // of the types without going all the way to the
2555 // canonical type.
2556 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2557 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2558 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2559 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2560
2561 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002562 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002563 // Okay: no conversion necessary
2564 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2565 !ParamType->isEnumeralType()) {
2566 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002567 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002568 } else {
2569 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002570 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002571 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002572 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002573 Diag(Param->getLocation(), diag::note_template_param_here);
2574 return true;
2575 }
2576
Douglas Gregor52aba872009-03-14 00:20:21 +00002577 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002578 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002579 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002580
2581 if (!Arg->isValueDependent()) {
2582 // Check that an unsigned parameter does not receive a negative
2583 // value.
2584 if (IntegerType->isUnsignedIntegerType()
2585 && (Value.isSigned() && Value.isNegative())) {
2586 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2587 << Value.toString(10) << Param->getType()
2588 << Arg->getSourceRange();
2589 Diag(Param->getLocation(), diag::note_template_param_here);
2590 return true;
2591 }
2592
2593 // Check that we don't overflow the template parameter type.
2594 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2595 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002596 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002597 diag::err_template_arg_too_large)
2598 << Value.toString(10) << Param->getType()
2599 << Arg->getSourceRange();
2600 Diag(Param->getLocation(), diag::note_template_param_here);
2601 return true;
2602 }
2603
2604 if (Value.getBitWidth() != AllowedBits)
2605 Value.extOrTrunc(AllowedBits);
2606 Value.setIsSigned(IntegerType->isSignedIntegerType());
2607 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002608
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002609 // Add the value of this argument to the list of converted
2610 // arguments. We use the bitwidth and signedness of the template
2611 // parameter.
2612 if (Arg->isValueDependent()) {
2613 // The argument is value-dependent. Create a new
2614 // TemplateArgument with the converted expression.
2615 Converted = TemplateArgument(Arg);
2616 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002617 }
2618
John McCall0ad16662009-10-29 08:12:44 +00002619 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002620 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002621 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002622 return false;
2623 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002624
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002625 // Handle pointer-to-function, reference-to-function, and
2626 // pointer-to-member-function all in (roughly) the same way.
2627 if (// -- For a non-type template-parameter of type pointer to
2628 // function, only the function-to-pointer conversion (4.3) is
2629 // applied. If the template-argument represents a set of
2630 // overloaded functions (or a pointer to such), the matching
2631 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002632 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002633 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002634 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002635 // -- For a non-type template-parameter of type reference to
2636 // function, no conversions apply. If the template-argument
2637 // represents a set of overloaded functions, the matching
2638 // function is selected from the set (13.4).
2639 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002640 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002641 // -- For a non-type template-parameter of type pointer to
2642 // member function, no conversions apply. If the
2643 // template-argument represents a set of overloaded member
2644 // functions, the matching member function is selected from
2645 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002646 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002647 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002648 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002649 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002650 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002651 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002652 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002653 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2654 ParamType->isMemberPointerType())) {
2655 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002656 if (ParamType->isMemberPointerType())
2657 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2658 else
2659 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002660 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002661 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002662 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002663 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002664 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002665 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2666 return true;
2667
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002668 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002669 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002670 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002671 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002672 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002673 }
2674 }
2675
Mike Stump11289f42009-09-09 15:08:12 +00002676 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002677 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002678 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002679 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002680 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002681 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002682 Diag(Param->getLocation(), diag::note_template_param_here);
2683 return true;
2684 }
Mike Stump11289f42009-09-09 15:08:12 +00002685
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002686 if (ParamType->isMemberPointerType())
2687 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002689 NamedDecl *Entity = 0;
2690 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2691 return true;
2692
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002693 if (Entity)
2694 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002695 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002696 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002697 }
2698
Chris Lattner696197c2009-02-20 21:37:53 +00002699 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002700 // -- for a non-type template-parameter of type pointer to
2701 // object, qualification conversions (4.4) and the
2702 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002703 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002704 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002705 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002706
Sebastian Redl576fd422009-05-10 18:38:11 +00002707 if (ArgType->isNullPtrType()) {
2708 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002709 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002710 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002711 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002712 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002713 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002714
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002715 if (IsQualificationConversion(ArgType, ParamType)) {
2716 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002717 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002718 }
Mike Stump11289f42009-09-09 15:08:12 +00002719
Douglas Gregor1515f762009-02-11 18:22:40 +00002720 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002721 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002722 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002723 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002724 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002725 Diag(Param->getLocation(), diag::note_template_param_here);
2726 return true;
2727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002729 NamedDecl *Entity = 0;
2730 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2731 return true;
2732
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002733 if (Entity)
2734 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002735 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002736 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002737 }
Mike Stump11289f42009-09-09 15:08:12 +00002738
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002739 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002740 // -- For a non-type template-parameter of type reference to
2741 // object, no conversions apply. The type referred to by the
2742 // reference may be more cv-qualified than the (otherwise
2743 // identical) type of the template-argument. The
2744 // template-parameter is bound directly to the
2745 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002746 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002747 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002748
Douglas Gregor1515f762009-02-11 18:22:40 +00002749 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002750 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002751 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002752 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002753 << Arg->getSourceRange();
2754 Diag(Param->getLocation(), diag::note_template_param_here);
2755 return true;
2756 }
2757
Mike Stump11289f42009-09-09 15:08:12 +00002758 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002759 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2760 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002761
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002762 if ((ParamQuals | ArgQuals) != ParamQuals) {
2763 Diag(Arg->getSourceRange().getBegin(),
2764 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002765 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002766 << Arg->getSourceRange();
2767 Diag(Param->getLocation(), diag::note_template_param_here);
2768 return true;
2769 }
Mike Stump11289f42009-09-09 15:08:12 +00002770
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002771 NamedDecl *Entity = 0;
2772 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2773 return true;
2774
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002775 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002776 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002777 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002778 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002779
2780 // -- For a non-type template-parameter of type pointer to data
2781 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002782 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002783 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2784
Douglas Gregor1515f762009-02-11 18:22:40 +00002785 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002786 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002787 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002788 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002789 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002790 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002791 } else {
2792 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002793 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002794 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002795 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002796 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002797 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002798 }
2799
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002800 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002801}
2802
2803/// \brief Check a template argument against its corresponding
2804/// template template parameter.
2805///
2806/// This routine implements the semantics of C++ [temp.arg.template].
2807/// It returns true if an error occurred, and false otherwise.
2808bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002809 const TemplateArgumentLoc &Arg) {
2810 TemplateName Name = Arg.getArgument().getAsTemplate();
2811 TemplateDecl *Template = Name.getAsTemplateDecl();
2812 if (!Template) {
2813 // Any dependent template name is fine.
2814 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2815 return false;
2816 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002817
2818 // C++ [temp.arg.template]p1:
2819 // A template-argument for a template template-parameter shall be
2820 // the name of a class template, expressed as id-expression. Only
2821 // primary class templates are considered when matching the
2822 // template template argument with the corresponding parameter;
2823 // partial specializations are not considered even if their
2824 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002825 //
2826 // Note that we also allow template template parameters here, which
2827 // will happen when we are dealing with, e.g., class template
2828 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002829 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002830 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002831 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002832 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002833 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002834 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002835 << Template;
2836 }
2837
2838 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2839 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002840 true,
2841 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002842 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002843}
2844
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002845/// \brief Determine whether the given template parameter lists are
2846/// equivalent.
2847///
Mike Stump11289f42009-09-09 15:08:12 +00002848/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002849/// source code as part of a new template declaration.
2850///
2851/// \param Old The old template parameter list, typically found via
2852/// name lookup of the template declared with this template parameter
2853/// list.
2854///
2855/// \param Complain If true, this routine will produce a diagnostic if
2856/// the template parameter lists are not equivalent.
2857///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002858/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002859///
2860/// \param TemplateArgLoc If this source location is valid, then we
2861/// are actually checking the template parameter list of a template
2862/// argument (New) against the template parameter list of its
2863/// corresponding template template parameter (Old). We produce
2864/// slightly different diagnostics in this scenario.
2865///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002866/// \returns True if the template parameter lists are equal, false
2867/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002868bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002869Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2870 TemplateParameterList *Old,
2871 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002872 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002873 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002874 if (Old->size() != New->size()) {
2875 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002876 unsigned NextDiag = diag::err_template_param_list_different_arity;
2877 if (TemplateArgLoc.isValid()) {
2878 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2879 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002880 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002881 Diag(New->getTemplateLoc(), NextDiag)
2882 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002883 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002884 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002885 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002886 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002887 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2888 }
2889
2890 return false;
2891 }
2892
2893 for (TemplateParameterList::iterator OldParm = Old->begin(),
2894 OldParmEnd = Old->end(), NewParm = New->begin();
2895 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2896 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002897 if (Complain) {
2898 unsigned NextDiag = diag::err_template_param_different_kind;
2899 if (TemplateArgLoc.isValid()) {
2900 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2901 NextDiag = diag::note_template_param_different_kind;
2902 }
2903 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002904 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002905 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002906 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002907 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002908 return false;
2909 }
2910
2911 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2912 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002913 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002914 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002915 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2916 // The types of non-type template parameters must agree.
2917 NonTypeTemplateParmDecl *NewNTTP
2918 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002919
2920 // If we are matching a template template argument to a template
2921 // template parameter and one of the non-type template parameter types
2922 // is dependent, then we must wait until template instantiation time
2923 // to actually compare the arguments.
2924 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2925 (OldNTTP->getType()->isDependentType() ||
2926 NewNTTP->getType()->isDependentType()))
2927 continue;
2928
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002929 if (Context.getCanonicalType(OldNTTP->getType()) !=
2930 Context.getCanonicalType(NewNTTP->getType())) {
2931 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002932 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2933 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002934 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002935 diag::err_template_arg_template_params_mismatch);
2936 NextDiag = diag::note_template_nontype_parm_different_type;
2937 }
2938 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002939 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002940 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002941 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002942 diag::note_template_nontype_parm_prev_declaration)
2943 << OldNTTP->getType();
2944 }
2945 return false;
2946 }
2947 } else {
2948 // The template parameter lists of template template
2949 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002950 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002951 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002952 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002953 = cast<TemplateTemplateParmDecl>(*OldParm);
2954 TemplateTemplateParmDecl *NewTTP
2955 = cast<TemplateTemplateParmDecl>(*NewParm);
2956 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2957 OldTTP->getTemplateParameters(),
2958 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002959 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002960 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002961 return false;
2962 }
2963 }
2964
2965 return true;
2966}
2967
2968/// \brief Check whether a template can be declared within this scope.
2969///
2970/// If the template declaration is valid in this scope, returns
2971/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002972bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002973Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002974 // Find the nearest enclosing declaration scope.
2975 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2976 (S->getFlags() & Scope::TemplateParamScope) != 0)
2977 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002978
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002979 // C++ [temp]p2:
2980 // A template-declaration can appear only as a namespace scope or
2981 // class scope declaration.
2982 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002983 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2984 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002985 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002986 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002987
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002988 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002989 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002990
2991 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2992 return false;
2993
Mike Stump11289f42009-09-09 15:08:12 +00002994 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002995 diag::err_template_outside_namespace_or_class_scope)
2996 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002997}
Douglas Gregor67a65642009-02-17 23:15:12 +00002998
Douglas Gregor54888652009-10-07 00:13:32 +00002999/// \brief Determine what kind of template specialization the given declaration
3000/// is.
3001static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3002 if (!D)
3003 return TSK_Undeclared;
3004
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003005 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3006 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003007 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3008 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003009 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3010 return Var->getTemplateSpecializationKind();
3011
Douglas Gregor54888652009-10-07 00:13:32 +00003012 return TSK_Undeclared;
3013}
3014
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003015/// \brief Check whether a specialization is well-formed in the current
3016/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003017///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003018/// This routine determines whether a template specialization can be declared
3019/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003020///
3021/// \param S the semantic analysis object for which this check is being
3022/// performed.
3023///
3024/// \param Specialized the entity being specialized or instantiated, which
3025/// may be a kind of template (class template, function template, etc.) or
3026/// a member of a class template (member function, static data member,
3027/// member class).
3028///
3029/// \param PrevDecl the previous declaration of this entity, if any.
3030///
3031/// \param Loc the location of the explicit specialization or instantiation of
3032/// this entity.
3033///
3034/// \param IsPartialSpecialization whether this is a partial specialization of
3035/// a class template.
3036///
Douglas Gregor54888652009-10-07 00:13:32 +00003037/// \returns true if there was an error that we cannot recover from, false
3038/// otherwise.
3039static bool CheckTemplateSpecializationScope(Sema &S,
3040 NamedDecl *Specialized,
3041 NamedDecl *PrevDecl,
3042 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003043 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003044 // Keep these "kind" numbers in sync with the %select statements in the
3045 // various diagnostics emitted by this routine.
3046 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003047 bool isTemplateSpecialization = false;
3048 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003049 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003050 isTemplateSpecialization = true;
3051 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003052 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003053 isTemplateSpecialization = true;
3054 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003055 EntityKind = 3;
3056 else if (isa<VarDecl>(Specialized))
3057 EntityKind = 4;
3058 else if (isa<RecordDecl>(Specialized))
3059 EntityKind = 5;
3060 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003061 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3062 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003063 return true;
3064 }
3065
Douglas Gregorf47b9112009-02-25 22:02:03 +00003066 // C++ [temp.expl.spec]p2:
3067 // An explicit specialization shall be declared in the namespace
3068 // of which the template is a member, or, for member templates, in
3069 // the namespace of which the enclosing class or enclosing class
3070 // template is a member. An explicit specialization of a member
3071 // function, member class or static data member of a class
3072 // template shall be declared in the namespace of which the class
3073 // template is a member. Such a declaration may also be a
3074 // definition. If the declaration is not a definition, the
3075 // specialization may be defined later in the name- space in which
3076 // the explicit specialization was declared, or in a namespace
3077 // that encloses the one in which the explicit specialization was
3078 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003079 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3080 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003081 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003082 return true;
3083 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003084
Douglas Gregor40fb7442009-10-07 17:30:37 +00003085 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3086 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003087 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003088 return true;
3089 }
3090
Douglas Gregore4b05162009-10-07 17:21:34 +00003091 // C++ [temp.class.spec]p6:
3092 // A class template partial specialization may be declared or redeclared
3093 // in any namespace scope in which its definition may be defined (14.5.1
3094 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003095 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003096 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003097 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003098 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003099 if ((!PrevDecl ||
3100 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3101 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3102 // There is no prior declaration of this entity, so this
3103 // specialization must be in the same context as the template
3104 // itself.
3105 if (!DC->Equals(SpecializedContext)) {
3106 if (isa<TranslationUnitDecl>(SpecializedContext))
3107 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3108 << EntityKind << Specialized;
3109 else if (isa<NamespaceDecl>(SpecializedContext))
3110 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3111 << EntityKind << Specialized
3112 << cast<NamedDecl>(SpecializedContext);
3113
3114 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3115 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003116 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003117 }
Douglas Gregor54888652009-10-07 00:13:32 +00003118
3119 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003120 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003121 // Note that HandleDeclarator() performs this check for explicit
3122 // specializations of function templates, static data members, and member
3123 // functions, so we skip the check here for those kinds of entities.
3124 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003125 // Should we refactor that check, so that it occurs later?
3126 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003127 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3128 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003129 if (isa<TranslationUnitDecl>(SpecializedContext))
3130 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3131 << EntityKind << Specialized;
3132 else if (isa<NamespaceDecl>(SpecializedContext))
3133 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3134 << EntityKind << Specialized
3135 << cast<NamedDecl>(SpecializedContext);
3136
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003137 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003138 }
Douglas Gregor54888652009-10-07 00:13:32 +00003139
3140 // FIXME: check for specialization-after-instantiation errors and such.
3141
Douglas Gregorf47b9112009-02-25 22:02:03 +00003142 return false;
3143}
Douglas Gregor54888652009-10-07 00:13:32 +00003144
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003145/// \brief Check the non-type template arguments of a class template
3146/// partial specialization according to C++ [temp.class.spec]p9.
3147///
Douglas Gregor09a30232009-06-12 22:08:06 +00003148/// \param TemplateParams the template parameters of the primary class
3149/// template.
3150///
3151/// \param TemplateArg the template arguments of the class template
3152/// partial specialization.
3153///
3154/// \param MirrorsPrimaryTemplate will be set true if the class
3155/// template partial specialization arguments are identical to the
3156/// implicit template arguments of the primary template. This is not
3157/// necessarily an error (C++0x), and it is left to the caller to diagnose
3158/// this condition when it is an error.
3159///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003160/// \returns true if there was an error, false otherwise.
3161bool Sema::CheckClassTemplatePartialSpecializationArgs(
3162 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003163 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003164 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003165 // FIXME: the interface to this function will have to change to
3166 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003167 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003168
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003169 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003170
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003171 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003172 // Determine whether the template argument list of the partial
3173 // specialization is identical to the implicit argument list of
3174 // the primary template. The caller may need to diagnostic this as
3175 // an error per C++ [temp.class.spec]p9b3.
3176 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003177 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003178 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3179 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003180 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003181 MirrorsPrimaryTemplate = false;
3182 } else if (TemplateTemplateParmDecl *TTP
3183 = dyn_cast<TemplateTemplateParmDecl>(
3184 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003185 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003186 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003187 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003188 if (!ArgDecl ||
3189 ArgDecl->getIndex() != TTP->getIndex() ||
3190 ArgDecl->getDepth() != TTP->getDepth())
3191 MirrorsPrimaryTemplate = false;
3192 }
3193 }
3194
Mike Stump11289f42009-09-09 15:08:12 +00003195 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003196 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003197 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003198 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003199 }
3200
Anders Carlsson40c1d492009-06-13 18:20:51 +00003201 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003202 if (!ArgExpr) {
3203 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003204 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003205 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003206
3207 // C++ [temp.class.spec]p8:
3208 // A non-type argument is non-specialized if it is the name of a
3209 // non-type parameter. All other non-type arguments are
3210 // specialized.
3211 //
3212 // Below, we check the two conditions that only apply to
3213 // specialized non-type arguments, so skip any non-specialized
3214 // arguments.
3215 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003216 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003217 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003218 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003219 (Param->getIndex() != NTTP->getIndex() ||
3220 Param->getDepth() != NTTP->getDepth()))
3221 MirrorsPrimaryTemplate = false;
3222
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003223 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003224 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003225
3226 // C++ [temp.class.spec]p9:
3227 // Within the argument list of a class template partial
3228 // specialization, the following restrictions apply:
3229 // -- A partially specialized non-type argument expression
3230 // shall not involve a template parameter of the partial
3231 // specialization except when the argument expression is a
3232 // simple identifier.
3233 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003234 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003235 diag::err_dependent_non_type_arg_in_partial_spec)
3236 << ArgExpr->getSourceRange();
3237 return true;
3238 }
3239
3240 // -- The type of a template parameter corresponding to a
3241 // specialized non-type argument shall not be dependent on a
3242 // parameter of the specialization.
3243 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003244 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003245 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3246 << Param->getType()
3247 << ArgExpr->getSourceRange();
3248 Diag(Param->getLocation(), diag::note_template_param_here);
3249 return true;
3250 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003251
3252 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003253 }
3254
3255 return false;
3256}
3257
Douglas Gregorc08f4892009-03-25 00:13:59 +00003258Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003259Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3260 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003261 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003262 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003263 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003264 SourceLocation TemplateNameLoc,
3265 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003266 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003267 SourceLocation RAngleLoc,
3268 AttributeList *Attr,
3269 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003270 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003271
Douglas Gregor67a65642009-02-17 23:15:12 +00003272 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003273 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003274 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003275 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3276
3277 if (!ClassTemplate) {
3278 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3279 << (Name.getAsTemplateDecl() &&
3280 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3281 return true;
3282 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003283
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003284 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003285 bool isPartialSpecialization = false;
3286
Douglas Gregorf47b9112009-02-25 22:02:03 +00003287 // Check the validity of the template headers that introduce this
3288 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003289 // FIXME: We probably shouldn't complain about these headers for
3290 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003291 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003292 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3293 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003294 TemplateParameterLists.size(),
3295 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003296 if (TemplateParams && TemplateParams->size() > 0) {
3297 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003298
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003299 // C++ [temp.class.spec]p10:
3300 // The template parameter list of a specialization shall not
3301 // contain default template argument values.
3302 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3303 Decl *Param = TemplateParams->getParam(I);
3304 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3305 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003306 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003307 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003308 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003309 }
3310 } else if (NonTypeTemplateParmDecl *NTTP
3311 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3312 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003313 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003314 diag::err_default_arg_in_partial_spec)
3315 << DefArg->getSourceRange();
3316 NTTP->setDefaultArgument(0);
3317 DefArg->Destroy(Context);
3318 }
3319 } else {
3320 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003321 if (TTP->hasDefaultArgument()) {
3322 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003323 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003324 << TTP->getDefaultArgument().getSourceRange();
3325 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003326 }
3327 }
3328 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003329 } else if (TemplateParams) {
3330 if (TUK == TUK_Friend)
3331 Diag(KWLoc, diag::err_template_spec_friend)
3332 << CodeModificationHint::CreateRemoval(
3333 SourceRange(TemplateParams->getTemplateLoc(),
3334 TemplateParams->getRAngleLoc()))
3335 << SourceRange(LAngleLoc, RAngleLoc);
3336 else
3337 isExplicitSpecialization = true;
3338 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003339 Diag(KWLoc, diag::err_template_spec_needs_header)
3340 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003341 isExplicitSpecialization = true;
3342 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003343
Douglas Gregor67a65642009-02-17 23:15:12 +00003344 // Check that the specialization uses the same tag kind as the
3345 // original template.
3346 TagDecl::TagKind Kind;
3347 switch (TagSpec) {
3348 default: assert(0 && "Unknown tag type!");
3349 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3350 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3351 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3352 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003353 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003354 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003355 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003356 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003357 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003358 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003359 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003360 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003361 diag::note_previous_use);
3362 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3363 }
3364
Douglas Gregorc40290e2009-03-09 23:48:35 +00003365 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003366 TemplateArgumentListInfo TemplateArgs;
3367 TemplateArgs.setLAngleLoc(LAngleLoc);
3368 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003369 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003370
Douglas Gregor67a65642009-02-17 23:15:12 +00003371 // Check that the template argument list is well-formed for this
3372 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003373 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3374 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003375 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3376 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003377 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003378
Mike Stump11289f42009-09-09 15:08:12 +00003379 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003380 ClassTemplate->getTemplateParameters()->size()) &&
3381 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003382
Douglas Gregor2373c592009-05-31 09:31:02 +00003383 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003384 // corresponds to these arguments.
3385 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003386 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003387 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003388 if (CheckClassTemplatePartialSpecializationArgs(
3389 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003390 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003391 return true;
3392
Douglas Gregor09a30232009-06-12 22:08:06 +00003393 if (MirrorsPrimaryTemplate) {
3394 // C++ [temp.class.spec]p9b3:
3395 //
Mike Stump11289f42009-09-09 15:08:12 +00003396 // -- The argument list of the specialization shall not be identical
3397 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003398 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003399 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003400 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003401 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003402 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003403 ClassTemplate->getIdentifier(),
3404 TemplateNameLoc,
3405 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003406 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003407 AS_none);
3408 }
3409
Douglas Gregor2208a292009-09-26 20:57:03 +00003410 // FIXME: Diagnose friend partial specializations
3411
Douglas Gregor2373c592009-05-31 09:31:02 +00003412 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003413 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003414 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003415 Converted.flatSize(),
3416 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003417 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003418 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003419 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003420 Converted.flatSize(),
3421 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003422 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003423 ClassTemplateSpecializationDecl *PrevDecl = 0;
3424
3425 if (isPartialSpecialization)
3426 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003427 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003428 InsertPos);
3429 else
3430 PrevDecl
3431 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003432
3433 ClassTemplateSpecializationDecl *Specialization = 0;
3434
Douglas Gregorf47b9112009-02-25 22:02:03 +00003435 // Check whether we can declare a class template specialization in
3436 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003437 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003438 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003439 TemplateNameLoc,
3440 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003441 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003442
Douglas Gregor15301382009-07-30 17:40:51 +00003443 // The canonical type
3444 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003445 if (PrevDecl &&
3446 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3447 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003448 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003449 // arguments was referenced but not declared, or we're only
3450 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003451 // declaration node as our own, updating its source location to
3452 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003453 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003454 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003455 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003456 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003457 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003458 // Build the canonical type that describes the converted template
3459 // arguments of the class template partial specialization.
3460 CanonType = Context.getTemplateSpecializationType(
3461 TemplateName(ClassTemplate),
3462 Converted.getFlatArguments(),
3463 Converted.flatSize());
3464
Douglas Gregor2373c592009-05-31 09:31:02 +00003465 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003466 ClassTemplatePartialSpecializationDecl *PrevPartial
3467 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003468 ClassTemplatePartialSpecializationDecl *Partial
3469 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003470 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003471 TemplateNameLoc,
3472 TemplateParams,
3473 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003474 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003475 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003476 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003477
3478 if (PrevPartial) {
3479 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3480 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3481 } else {
3482 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3483 }
3484 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003485
Douglas Gregor21610382009-10-29 00:04:11 +00003486 // If we are providing an explicit specialization of a member class
3487 // template specialization, make a note of that.
3488 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3489 PrevPartial->setMemberSpecialization();
3490
Douglas Gregor91772d12009-06-13 00:26:55 +00003491 // Check that all of the template parameters of the class template
3492 // partial specialization are deducible from the template
3493 // arguments. If not, this class template partial specialization
3494 // will never be used.
3495 llvm::SmallVector<bool, 8> DeducibleParams;
3496 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003497 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003498 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003499 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003500 unsigned NumNonDeducible = 0;
3501 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3502 if (!DeducibleParams[I])
3503 ++NumNonDeducible;
3504
3505 if (NumNonDeducible) {
3506 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3507 << (NumNonDeducible > 1)
3508 << SourceRange(TemplateNameLoc, RAngleLoc);
3509 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3510 if (!DeducibleParams[I]) {
3511 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3512 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003513 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003514 diag::note_partial_spec_unused_parameter)
3515 << Param->getDeclName();
3516 else
Mike Stump11289f42009-09-09 15:08:12 +00003517 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003518 diag::note_partial_spec_unused_parameter)
3519 << std::string("<anonymous>");
3520 }
3521 }
3522 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003523 } else {
3524 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003525 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003526 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003527 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003528 ClassTemplate->getDeclContext(),
3529 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003530 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003531 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003532 PrevDecl);
3533
3534 if (PrevDecl) {
3535 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3536 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3537 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003538 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003539 InsertPos);
3540 }
Douglas Gregor15301382009-07-30 17:40:51 +00003541
3542 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003543 }
3544
Douglas Gregor06db9f52009-10-12 20:18:28 +00003545 // C++ [temp.expl.spec]p6:
3546 // If a template, a member template or the member of a class template is
3547 // explicitly specialized then that specialization shall be declared
3548 // before the first use of that specialization that would cause an implicit
3549 // instantiation to take place, in every translation unit in which such a
3550 // use occurs; no diagnostic is required.
3551 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3552 SourceRange Range(TemplateNameLoc, RAngleLoc);
3553 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3554 << Context.getTypeDeclType(Specialization) << Range;
3555
3556 Diag(PrevDecl->getPointOfInstantiation(),
3557 diag::note_instantiation_required_here)
3558 << (PrevDecl->getTemplateSpecializationKind()
3559 != TSK_ImplicitInstantiation);
3560 return true;
3561 }
3562
Douglas Gregor2208a292009-09-26 20:57:03 +00003563 // If this is not a friend, note that this is an explicit specialization.
3564 if (TUK != TUK_Friend)
3565 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003566
3567 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003568 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003569 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003570 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003571 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003572 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003573 Diag(Def->getLocation(), diag::note_previous_definition);
3574 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003575 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003576 }
3577 }
3578
Douglas Gregord56a91e2009-02-26 22:19:44 +00003579 // Build the fully-sugared type for this class template
3580 // specialization as the user wrote in the specialization
3581 // itself. This means that we'll pretty-print the type retrieved
3582 // from the specialization's declaration the way that the user
3583 // actually wrote the specialization, rather than formatting the
3584 // name based on the "canonical" representation used to store the
3585 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003586 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003587 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003588 if (TUK != TUK_Friend)
3589 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003590 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003591
Douglas Gregor1e249f82009-02-25 22:18:32 +00003592 // C++ [temp.expl.spec]p9:
3593 // A template explicit specialization is in the scope of the
3594 // namespace in which the template was defined.
3595 //
3596 // We actually implement this paragraph where we set the semantic
3597 // context (in the creation of the ClassTemplateSpecializationDecl),
3598 // but we also maintain the lexical context where the actual
3599 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003600 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003601
Douglas Gregor67a65642009-02-17 23:15:12 +00003602 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003603 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003604 Specialization->startDefinition();
3605
Douglas Gregor2208a292009-09-26 20:57:03 +00003606 if (TUK == TUK_Friend) {
3607 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3608 TemplateNameLoc,
3609 WrittenTy.getTypePtr(),
3610 /*FIXME:*/KWLoc);
3611 Friend->setAccess(AS_public);
3612 CurContext->addDecl(Friend);
3613 } else {
3614 // Add the specialization into its lexical context, so that it can
3615 // be seen when iterating through the list of declarations in that
3616 // context. However, specializations are not found by name lookup.
3617 CurContext->addDecl(Specialization);
3618 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003619 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003620}
Douglas Gregor333489b2009-03-27 23:10:48 +00003621
Mike Stump11289f42009-09-09 15:08:12 +00003622Sema::DeclPtrTy
3623Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003624 MultiTemplateParamsArg TemplateParameterLists,
3625 Declarator &D) {
3626 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3627}
3628
Mike Stump11289f42009-09-09 15:08:12 +00003629Sema::DeclPtrTy
3630Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003631 MultiTemplateParamsArg TemplateParameterLists,
3632 Declarator &D) {
3633 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3634 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3635 "Not a function declarator!");
3636 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003637
Douglas Gregor17a7c122009-06-24 00:54:41 +00003638 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003639 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003640 }
Mike Stump11289f42009-09-09 15:08:12 +00003641
Douglas Gregor17a7c122009-06-24 00:54:41 +00003642 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003643
3644 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003645 move(TemplateParameterLists),
3646 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003647 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003648 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003649 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003650 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003651 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3652 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003653 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003654}
3655
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003656/// \brief Diagnose cases where we have an explicit template specialization
3657/// before/after an explicit template instantiation, producing diagnostics
3658/// for those cases where they are required and determining whether the
3659/// new specialization/instantiation will have any effect.
3660///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003661/// \param NewLoc the location of the new explicit specialization or
3662/// instantiation.
3663///
3664/// \param NewTSK the kind of the new explicit specialization or instantiation.
3665///
3666/// \param PrevDecl the previous declaration of the entity.
3667///
3668/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3669///
3670/// \param PrevPointOfInstantiation if valid, indicates where the previus
3671/// declaration was instantiated (either implicitly or explicitly).
3672///
3673/// \param SuppressNew will be set to true to indicate that the new
3674/// specialization or instantiation has no effect and should be ignored.
3675///
3676/// \returns true if there was an error that should prevent the introduction of
3677/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003678bool
3679Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3680 TemplateSpecializationKind NewTSK,
3681 NamedDecl *PrevDecl,
3682 TemplateSpecializationKind PrevTSK,
3683 SourceLocation PrevPointOfInstantiation,
3684 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003685 SuppressNew = false;
3686
3687 switch (NewTSK) {
3688 case TSK_Undeclared:
3689 case TSK_ImplicitInstantiation:
3690 assert(false && "Don't check implicit instantiations here");
3691 return false;
3692
3693 case TSK_ExplicitSpecialization:
3694 switch (PrevTSK) {
3695 case TSK_Undeclared:
3696 case TSK_ExplicitSpecialization:
3697 // Okay, we're just specializing something that is either already
3698 // explicitly specialized or has merely been mentioned without any
3699 // instantiation.
3700 return false;
3701
3702 case TSK_ImplicitInstantiation:
3703 if (PrevPointOfInstantiation.isInvalid()) {
3704 // The declaration itself has not actually been instantiated, so it is
3705 // still okay to specialize it.
3706 return false;
3707 }
3708 // Fall through
3709
3710 case TSK_ExplicitInstantiationDeclaration:
3711 case TSK_ExplicitInstantiationDefinition:
3712 assert((PrevTSK == TSK_ImplicitInstantiation ||
3713 PrevPointOfInstantiation.isValid()) &&
3714 "Explicit instantiation without point of instantiation?");
3715
3716 // C++ [temp.expl.spec]p6:
3717 // If a template, a member template or the member of a class template
3718 // is explicitly specialized then that specialization shall be declared
3719 // before the first use of that specialization that would cause an
3720 // implicit instantiation to take place, in every translation unit in
3721 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003722 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003723 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003724 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003725 << (PrevTSK != TSK_ImplicitInstantiation);
3726
3727 return true;
3728 }
3729 break;
3730
3731 case TSK_ExplicitInstantiationDeclaration:
3732 switch (PrevTSK) {
3733 case TSK_ExplicitInstantiationDeclaration:
3734 // This explicit instantiation declaration is redundant (that's okay).
3735 SuppressNew = true;
3736 return false;
3737
3738 case TSK_Undeclared:
3739 case TSK_ImplicitInstantiation:
3740 // We're explicitly instantiating something that may have already been
3741 // implicitly instantiated; that's fine.
3742 return false;
3743
3744 case TSK_ExplicitSpecialization:
3745 // C++0x [temp.explicit]p4:
3746 // For a given set of template parameters, if an explicit instantiation
3747 // of a template appears after a declaration of an explicit
3748 // specialization for that template, the explicit instantiation has no
3749 // effect.
3750 return false;
3751
3752 case TSK_ExplicitInstantiationDefinition:
3753 // C++0x [temp.explicit]p10:
3754 // If an entity is the subject of both an explicit instantiation
3755 // declaration and an explicit instantiation definition in the same
3756 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003757 Diag(NewLoc,
3758 diag::err_explicit_instantiation_declaration_after_definition);
3759 Diag(PrevPointOfInstantiation,
3760 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003761 assert(PrevPointOfInstantiation.isValid() &&
3762 "Explicit instantiation without point of instantiation?");
3763 SuppressNew = true;
3764 return false;
3765 }
3766 break;
3767
3768 case TSK_ExplicitInstantiationDefinition:
3769 switch (PrevTSK) {
3770 case TSK_Undeclared:
3771 case TSK_ImplicitInstantiation:
3772 // We're explicitly instantiating something that may have already been
3773 // implicitly instantiated; that's fine.
3774 return false;
3775
3776 case TSK_ExplicitSpecialization:
3777 // C++ DR 259, C++0x [temp.explicit]p4:
3778 // For a given set of template parameters, if an explicit
3779 // instantiation of a template appears after a declaration of
3780 // an explicit specialization for that template, the explicit
3781 // instantiation has no effect.
3782 //
3783 // In C++98/03 mode, we only give an extension warning here, because it
3784 // is not not harmful to try to explicitly instantiate something that
3785 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003786 if (!getLangOptions().CPlusPlus0x) {
3787 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003788 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003789 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003790 diag::note_previous_template_specialization);
3791 }
3792 SuppressNew = true;
3793 return false;
3794
3795 case TSK_ExplicitInstantiationDeclaration:
3796 // We're explicity instantiating a definition for something for which we
3797 // were previously asked to suppress instantiations. That's fine.
3798 return false;
3799
3800 case TSK_ExplicitInstantiationDefinition:
3801 // C++0x [temp.spec]p5:
3802 // For a given template and a given set of template-arguments,
3803 // - an explicit instantiation definition shall appear at most once
3804 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003805 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003806 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003807 Diag(PrevPointOfInstantiation,
3808 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003809 SuppressNew = true;
3810 return false;
3811 }
3812 break;
3813 }
3814
3815 assert(false && "Missing specialization/instantiation case?");
3816
3817 return false;
3818}
3819
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003820/// \brief Perform semantic analysis for the given function template
3821/// specialization.
3822///
3823/// This routine performs all of the semantic analysis required for an
3824/// explicit function template specialization. On successful completion,
3825/// the function declaration \p FD will become a function template
3826/// specialization.
3827///
3828/// \param FD the function declaration, which will be updated to become a
3829/// function template specialization.
3830///
3831/// \param HasExplicitTemplateArgs whether any template arguments were
3832/// explicitly provided.
3833///
3834/// \param LAngleLoc the location of the left angle bracket ('<'), if
3835/// template arguments were explicitly provided.
3836///
3837/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3838/// if any.
3839///
3840/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3841/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3842/// true as in, e.g., \c void sort<>(char*, char*);
3843///
3844/// \param RAngleLoc the location of the right angle bracket ('>'), if
3845/// template arguments were explicitly provided.
3846///
3847/// \param PrevDecl the set of declarations that
3848bool
3849Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003850 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003851 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003852 // The set of function template specializations that could match this
3853 // explicit function template specialization.
3854 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3855 CandidateSet Candidates;
3856
3857 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003858 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3859 I != E; ++I) {
3860 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3861 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003862 // Only consider templates found within the same semantic lookup scope as
3863 // FD.
3864 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3865 continue;
3866
3867 // C++ [temp.expl.spec]p11:
3868 // A trailing template-argument can be left unspecified in the
3869 // template-id naming an explicit function template specialization
3870 // provided it can be deduced from the function argument type.
3871 // Perform template argument deduction to determine whether we may be
3872 // specializing this template.
3873 // FIXME: It is somewhat wasteful to build
3874 TemplateDeductionInfo Info(Context);
3875 FunctionDecl *Specialization = 0;
3876 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003877 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003878 FD->getType(),
3879 Specialization,
3880 Info)) {
3881 // FIXME: Template argument deduction failed; record why it failed, so
3882 // that we can provide nifty diagnostics.
3883 (void)TDK;
3884 continue;
3885 }
3886
3887 // Record this candidate.
3888 Candidates.push_back(Specialization);
3889 }
3890 }
3891
Douglas Gregor5de279c2009-09-26 03:41:46 +00003892 // Find the most specialized function template.
3893 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3894 Candidates.size(),
3895 TPOC_Other,
3896 FD->getLocation(),
3897 PartialDiagnostic(diag::err_function_template_spec_no_match)
3898 << FD->getDeclName(),
3899 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003900 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003901 PartialDiagnostic(diag::note_function_template_spec_matched));
3902 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003903 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003904
3905 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003906 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003907
Douglas Gregor54888652009-10-07 00:13:32 +00003908 // Check the scope of this explicit specialization.
3909 if (CheckTemplateSpecializationScope(*this,
3910 Specialization->getPrimaryTemplate(),
3911 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003912 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003913 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003914
3915 // C++ [temp.expl.spec]p6:
3916 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003917 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003918 // before the first use of that specialization that would cause an implicit
3919 // instantiation to take place, in every translation unit in which such a
3920 // use occurs; no diagnostic is required.
3921 FunctionTemplateSpecializationInfo *SpecInfo
3922 = Specialization->getTemplateSpecializationInfo();
3923 assert(SpecInfo && "Function template specialization info missing?");
3924 if (SpecInfo->getPointOfInstantiation().isValid()) {
3925 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3926 << FD;
3927 Diag(SpecInfo->getPointOfInstantiation(),
3928 diag::note_instantiation_required_here)
3929 << (Specialization->getTemplateSpecializationKind()
3930 != TSK_ImplicitInstantiation);
3931 return true;
3932 }
Douglas Gregor54888652009-10-07 00:13:32 +00003933
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003934 // Mark the prior declaration as an explicit specialization, so that later
3935 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003936 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003937
3938 // Turn the given function declaration into a function template
3939 // specialization, with the template arguments from the previous
3940 // specialization.
3941 FD->setFunctionTemplateSpecialization(Context,
3942 Specialization->getPrimaryTemplate(),
3943 new (Context) TemplateArgumentList(
3944 *Specialization->getTemplateSpecializationArgs()),
3945 /*InsertPos=*/0,
3946 TSK_ExplicitSpecialization);
3947
3948 // The "previous declaration" for this function template specialization is
3949 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003950 Previous.clear();
3951 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003952 return false;
3953}
3954
Douglas Gregor86d142a2009-10-08 07:24:58 +00003955/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003956/// specialization.
3957///
3958/// This routine performs all of the semantic analysis required for an
3959/// explicit member function specialization. On successful completion,
3960/// the function declaration \p FD will become a member function
3961/// specialization.
3962///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003963/// \param Member the member declaration, which will be updated to become a
3964/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003965///
John McCall1f82f242009-11-18 22:49:29 +00003966/// \param Previous the set of declarations, one of which may be specialized
3967/// by this function specialization; the set will be modified to contain the
3968/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003969bool
John McCall1f82f242009-11-18 22:49:29 +00003970Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003971 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3972
3973 // Try to find the member we are instantiating.
3974 NamedDecl *Instantiation = 0;
3975 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003976 MemberSpecializationInfo *MSInfo = 0;
3977
John McCall1f82f242009-11-18 22:49:29 +00003978 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003979 // Nowhere to look anyway.
3980 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003981 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3982 I != E; ++I) {
3983 NamedDecl *D = (*I)->getUnderlyingDecl();
3984 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003985 if (Context.hasSameType(Function->getType(), Method->getType())) {
3986 Instantiation = Method;
3987 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003988 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003989 break;
3990 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003991 }
3992 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003993 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003994 VarDecl *PrevVar;
3995 if (Previous.isSingleResult() &&
3996 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003997 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003998 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003999 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004000 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004001 }
4002 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004003 CXXRecordDecl *PrevRecord;
4004 if (Previous.isSingleResult() &&
4005 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4006 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004007 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004008 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004009 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004010 }
4011
4012 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004013 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004014 // specializations are always out-of-line, the caller will complain about
4015 // this mismatch later.
4016 return false;
4017 }
4018
Douglas Gregor86d142a2009-10-08 07:24:58 +00004019 // Make sure that this is a specialization of a member.
4020 if (!InstantiatedFrom) {
4021 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4022 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004023 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4024 return true;
4025 }
4026
Douglas Gregor06db9f52009-10-12 20:18:28 +00004027 // C++ [temp.expl.spec]p6:
4028 // If a template, a member template or the member of a class template is
4029 // explicitly specialized then that spe- cialization shall be declared
4030 // before the first use of that specialization that would cause an implicit
4031 // instantiation to take place, in every translation unit in which such a
4032 // use occurs; no diagnostic is required.
4033 assert(MSInfo && "Member specialization info missing?");
4034 if (MSInfo->getPointOfInstantiation().isValid()) {
4035 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
4036 << Member;
4037 Diag(MSInfo->getPointOfInstantiation(),
4038 diag::note_instantiation_required_here)
4039 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
4040 return true;
4041 }
4042
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004043 // Check the scope of this explicit specialization.
4044 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004045 InstantiatedFrom,
4046 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004047 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004048 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004049
Douglas Gregor86d142a2009-10-08 07:24:58 +00004050 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004051 // the original declaration to note that it is an explicit specialization
4052 // (if it was previously an implicit instantiation). This latter step
4053 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004054 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004055 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4056 if (InstantiationFunction->getTemplateSpecializationKind() ==
4057 TSK_ImplicitInstantiation) {
4058 InstantiationFunction->setTemplateSpecializationKind(
4059 TSK_ExplicitSpecialization);
4060 InstantiationFunction->setLocation(Member->getLocation());
4061 }
4062
Douglas Gregor86d142a2009-10-08 07:24:58 +00004063 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4064 cast<CXXMethodDecl>(InstantiatedFrom),
4065 TSK_ExplicitSpecialization);
4066 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004067 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4068 if (InstantiationVar->getTemplateSpecializationKind() ==
4069 TSK_ImplicitInstantiation) {
4070 InstantiationVar->setTemplateSpecializationKind(
4071 TSK_ExplicitSpecialization);
4072 InstantiationVar->setLocation(Member->getLocation());
4073 }
4074
Douglas Gregor86d142a2009-10-08 07:24:58 +00004075 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4076 cast<VarDecl>(InstantiatedFrom),
4077 TSK_ExplicitSpecialization);
4078 } else {
4079 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004080 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4081 if (InstantiationClass->getTemplateSpecializationKind() ==
4082 TSK_ImplicitInstantiation) {
4083 InstantiationClass->setTemplateSpecializationKind(
4084 TSK_ExplicitSpecialization);
4085 InstantiationClass->setLocation(Member->getLocation());
4086 }
4087
Douglas Gregor86d142a2009-10-08 07:24:58 +00004088 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004089 cast<CXXRecordDecl>(InstantiatedFrom),
4090 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004091 }
4092
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004093 // Save the caller the trouble of having to figure out which declaration
4094 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004095 Previous.clear();
4096 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004097 return false;
4098}
4099
Douglas Gregore47f5a72009-10-14 23:41:34 +00004100/// \brief Check the scope of an explicit instantiation.
4101static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4102 SourceLocation InstLoc,
4103 bool WasQualifiedName) {
4104 DeclContext *ExpectedContext
4105 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4106 DeclContext *CurContext = S.CurContext->getLookupContext();
4107
4108 // C++0x [temp.explicit]p2:
4109 // An explicit instantiation shall appear in an enclosing namespace of its
4110 // template.
4111 //
4112 // This is DR275, which we do not retroactively apply to C++98/03.
4113 if (S.getLangOptions().CPlusPlus0x &&
4114 !CurContext->Encloses(ExpectedContext)) {
4115 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4116 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4117 << D << NS;
4118 else
4119 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4120 << D;
4121 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4122 return;
4123 }
4124
4125 // C++0x [temp.explicit]p2:
4126 // If the name declared in the explicit instantiation is an unqualified
4127 // name, the explicit instantiation shall appear in the namespace where
4128 // its template is declared or, if that namespace is inline (7.3.1), any
4129 // namespace from its enclosing namespace set.
4130 if (WasQualifiedName)
4131 return;
4132
4133 if (CurContext->Equals(ExpectedContext))
4134 return;
4135
4136 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4137 << D << ExpectedContext;
4138 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4139}
4140
4141/// \brief Determine whether the given scope specifier has a template-id in it.
4142static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4143 if (!SS.isSet())
4144 return false;
4145
4146 // C++0x [temp.explicit]p2:
4147 // If the explicit instantiation is for a member function, a member class
4148 // or a static data member of a class template specialization, the name of
4149 // the class template specialization in the qualified-id for the member
4150 // name shall be a simple-template-id.
4151 //
4152 // C++98 has the same restriction, just worded differently.
4153 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4154 NNS; NNS = NNS->getPrefix())
4155 if (Type *T = NNS->getAsType())
4156 if (isa<TemplateSpecializationType>(T))
4157 return true;
4158
4159 return false;
4160}
4161
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004162// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004163// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004164Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004165Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004166 SourceLocation ExternLoc,
4167 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004168 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004169 SourceLocation KWLoc,
4170 const CXXScopeSpec &SS,
4171 TemplateTy TemplateD,
4172 SourceLocation TemplateNameLoc,
4173 SourceLocation LAngleLoc,
4174 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004175 SourceLocation RAngleLoc,
4176 AttributeList *Attr) {
4177 // Find the class template we're specializing
4178 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004179 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004180 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4181
4182 // Check that the specialization uses the same tag kind as the
4183 // original template.
4184 TagDecl::TagKind Kind;
4185 switch (TagSpec) {
4186 default: assert(0 && "Unknown tag type!");
4187 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4188 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4189 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4190 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004191 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004192 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004193 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004194 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004195 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004196 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004197 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004198 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004199 diag::note_previous_use);
4200 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4201 }
4202
Douglas Gregore47f5a72009-10-14 23:41:34 +00004203 // C++0x [temp.explicit]p2:
4204 // There are two forms of explicit instantiation: an explicit instantiation
4205 // definition and an explicit instantiation declaration. An explicit
4206 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004207 TemplateSpecializationKind TSK
4208 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4209 : TSK_ExplicitInstantiationDeclaration;
4210
Douglas Gregora1f49972009-05-13 00:25:59 +00004211 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004212 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004213 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004214
4215 // Check that the template argument list is well-formed for this
4216 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004217 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4218 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004219 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4220 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004221 return true;
4222
Mike Stump11289f42009-09-09 15:08:12 +00004223 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004224 ClassTemplate->getTemplateParameters()->size()) &&
4225 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004226
Douglas Gregora1f49972009-05-13 00:25:59 +00004227 // Find the class template specialization declaration that
4228 // corresponds to these arguments.
4229 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004230 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004231 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004232 Converted.flatSize(),
4233 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004234 void *InsertPos = 0;
4235 ClassTemplateSpecializationDecl *PrevDecl
4236 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4237
Douglas Gregor54888652009-10-07 00:13:32 +00004238 // C++0x [temp.explicit]p2:
4239 // [...] An explicit instantiation shall appear in an enclosing
4240 // namespace of its template. [...]
4241 //
4242 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004243 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4244 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004245
Douglas Gregora1f49972009-05-13 00:25:59 +00004246 ClassTemplateSpecializationDecl *Specialization = 0;
4247
Douglas Gregor0681a352009-11-25 06:01:46 +00004248 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004249 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004250 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004251 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004252 PrevDecl,
4253 PrevDecl->getSpecializationKind(),
4254 PrevDecl->getPointOfInstantiation(),
4255 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004256 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004257
Douglas Gregor12e49d32009-10-15 22:53:21 +00004258 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004259 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004260
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004261 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4262 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4263 // Since the only prior class template specialization with these
4264 // arguments was referenced but not declared, reuse that
4265 // declaration node as our own, updating its source location to
4266 // reflect our new declaration.
4267 Specialization = PrevDecl;
4268 Specialization->setLocation(TemplateNameLoc);
4269 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004270 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004271 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004272 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004273
4274 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004275 // Create a new class template specialization declaration node for
4276 // this explicit specialization.
4277 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004278 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004279 ClassTemplate->getDeclContext(),
4280 TemplateNameLoc,
4281 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004282 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004283
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004284 if (PrevDecl) {
4285 // Remove the previous declaration from the folding set, since we want
4286 // to introduce a new declaration.
4287 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4288 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4289 }
4290
4291 // Insert the new specialization.
4292 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004293 }
4294
4295 // Build the fully-sugared type for this explicit instantiation as
4296 // the user wrote in the explicit instantiation itself. This means
4297 // that we'll pretty-print the type retrieved from the
4298 // specialization's declaration the way that the user actually wrote
4299 // the explicit instantiation, rather than formatting the name based
4300 // on the "canonical" representation used to store the template
4301 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004302 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00004303 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004304 Context.getTypeDeclType(Specialization));
4305 Specialization->setTypeAsWritten(WrittenTy);
4306 TemplateArgsIn.release();
4307
Douglas Gregor0681a352009-11-25 06:01:46 +00004308 if (!ReusedDecl) {
4309 // Add the explicit instantiation into its lexical context. However,
4310 // since explicit instantiations are never found by name lookup, we
4311 // just put it into the declaration context directly.
4312 Specialization->setLexicalDeclContext(CurContext);
4313 CurContext->addDecl(Specialization);
4314 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004315
4316 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004317 // A definition of a class template or class member template
4318 // shall be in scope at the point of the explicit instantiation of
4319 // the class template or class member template.
4320 //
4321 // This check comes when we actually try to perform the
4322 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004323 ClassTemplateSpecializationDecl *Def
4324 = cast_or_null<ClassTemplateSpecializationDecl>(
4325 Specialization->getDefinition(Context));
4326 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004327 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004328
4329 // Instantiate the members of this class template specialization.
4330 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4331 Specialization->getDefinition(Context));
4332 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004333 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004334
4335 return DeclPtrTy::make(Specialization);
4336}
4337
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004338// Explicit instantiation of a member class of a class template.
4339Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004340Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004341 SourceLocation ExternLoc,
4342 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004343 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004344 SourceLocation KWLoc,
4345 const CXXScopeSpec &SS,
4346 IdentifierInfo *Name,
4347 SourceLocation NameLoc,
4348 AttributeList *Attr) {
4349
Douglas Gregord6ab8742009-05-28 23:31:59 +00004350 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004351 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004352 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004353 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004354 MultiTemplateParamsArg(*this, 0, 0),
4355 Owned, IsDependent);
4356 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4357
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004358 if (!TagD)
4359 return true;
4360
4361 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4362 if (Tag->isEnum()) {
4363 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4364 << Context.getTypeDeclType(Tag);
4365 return true;
4366 }
4367
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004368 if (Tag->isInvalidDecl())
4369 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004370
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004371 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4372 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4373 if (!Pattern) {
4374 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4375 << Context.getTypeDeclType(Record);
4376 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4377 return true;
4378 }
4379
Douglas Gregore47f5a72009-10-14 23:41:34 +00004380 // C++0x [temp.explicit]p2:
4381 // If the explicit instantiation is for a class or member class, the
4382 // elaborated-type-specifier in the declaration shall include a
4383 // simple-template-id.
4384 //
4385 // C++98 has the same restriction, just worded differently.
4386 if (!ScopeSpecifierHasTemplateId(SS))
4387 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4388 << Record << SS.getRange();
4389
4390 // C++0x [temp.explicit]p2:
4391 // There are two forms of explicit instantiation: an explicit instantiation
4392 // definition and an explicit instantiation declaration. An explicit
4393 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004394 TemplateSpecializationKind TSK
4395 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4396 : TSK_ExplicitInstantiationDeclaration;
4397
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004398 // C++0x [temp.explicit]p2:
4399 // [...] An explicit instantiation shall appear in an enclosing
4400 // namespace of its template. [...]
4401 //
4402 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004403 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004404
4405 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004406 CXXRecordDecl *PrevDecl
4407 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4408 if (!PrevDecl && Record->getDefinition(Context))
4409 PrevDecl = Record;
4410 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004411 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4412 bool SuppressNew = false;
4413 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004414 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004415 PrevDecl,
4416 MSInfo->getTemplateSpecializationKind(),
4417 MSInfo->getPointOfInstantiation(),
4418 SuppressNew))
4419 return true;
4420 if (SuppressNew)
4421 return TagD;
4422 }
4423
Douglas Gregor12e49d32009-10-15 22:53:21 +00004424 CXXRecordDecl *RecordDef
4425 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4426 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004427 // C++ [temp.explicit]p3:
4428 // A definition of a member class of a class template shall be in scope
4429 // at the point of an explicit instantiation of the member class.
4430 CXXRecordDecl *Def
4431 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4432 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004433 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4434 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004435 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4436 << Pattern;
4437 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004438 } else {
4439 if (InstantiateClass(NameLoc, Record, Def,
4440 getTemplateInstantiationArgs(Record),
4441 TSK))
4442 return true;
4443
4444 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4445 if (!RecordDef)
4446 return true;
4447 }
4448 }
4449
4450 // Instantiate all of the members of the class.
4451 InstantiateClassMembers(NameLoc, RecordDef,
4452 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004453
Mike Stump87c57ac2009-05-16 07:39:55 +00004454 // FIXME: We don't have any representation for explicit instantiations of
4455 // member classes. Such a representation is not needed for compilation, but it
4456 // should be available for clients that want to see all of the declarations in
4457 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004458 return TagD;
4459}
4460
Douglas Gregor450f00842009-09-25 18:43:00 +00004461Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4462 SourceLocation ExternLoc,
4463 SourceLocation TemplateLoc,
4464 Declarator &D) {
4465 // Explicit instantiations always require a name.
4466 DeclarationName Name = GetNameForDeclarator(D);
4467 if (!Name) {
4468 if (!D.isInvalidType())
4469 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4470 diag::err_explicit_instantiation_requires_name)
4471 << D.getDeclSpec().getSourceRange()
4472 << D.getSourceRange();
4473
4474 return true;
4475 }
4476
4477 // The scope passed in may not be a decl scope. Zip up the scope tree until
4478 // we find one that is.
4479 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4480 (S->getFlags() & Scope::TemplateParamScope) != 0)
4481 S = S->getParent();
4482
4483 // Determine the type of the declaration.
4484 QualType R = GetTypeForDeclarator(D, S, 0);
4485 if (R.isNull())
4486 return true;
4487
4488 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4489 // Cannot explicitly instantiate a typedef.
4490 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4491 << Name;
4492 return true;
4493 }
4494
Douglas Gregor3c74d412009-10-14 20:14:33 +00004495 // C++0x [temp.explicit]p1:
4496 // [...] An explicit instantiation of a function template shall not use the
4497 // inline or constexpr specifiers.
4498 // Presumably, this also applies to member functions of class templates as
4499 // well.
4500 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4501 Diag(D.getDeclSpec().getInlineSpecLoc(),
4502 diag::err_explicit_instantiation_inline)
4503 << CodeModificationHint::CreateRemoval(
4504 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4505
4506 // FIXME: check for constexpr specifier.
4507
Douglas Gregore47f5a72009-10-14 23:41:34 +00004508 // C++0x [temp.explicit]p2:
4509 // There are two forms of explicit instantiation: an explicit instantiation
4510 // definition and an explicit instantiation declaration. An explicit
4511 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004512 TemplateSpecializationKind TSK
4513 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4514 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004515
John McCall27b18f82009-11-17 02:14:36 +00004516 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4517 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004518
4519 if (!R->isFunctionType()) {
4520 // C++ [temp.explicit]p1:
4521 // A [...] static data member of a class template can be explicitly
4522 // instantiated from the member definition associated with its class
4523 // template.
John McCall27b18f82009-11-17 02:14:36 +00004524 if (Previous.isAmbiguous())
4525 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004526
John McCall9f3059a2009-10-09 21:13:30 +00004527 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4528 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004529 if (!Prev || !Prev->isStaticDataMember()) {
4530 // We expect to see a data data member here.
4531 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4532 << Name;
4533 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4534 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004535 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004536 return true;
4537 }
4538
4539 if (!Prev->getInstantiatedFromStaticDataMember()) {
4540 // FIXME: Check for explicit specialization?
4541 Diag(D.getIdentifierLoc(),
4542 diag::err_explicit_instantiation_data_member_not_instantiated)
4543 << Prev;
4544 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4545 // FIXME: Can we provide a note showing where this was declared?
4546 return true;
4547 }
4548
Douglas Gregore47f5a72009-10-14 23:41:34 +00004549 // C++0x [temp.explicit]p2:
4550 // If the explicit instantiation is for a member function, a member class
4551 // or a static data member of a class template specialization, the name of
4552 // the class template specialization in the qualified-id for the member
4553 // name shall be a simple-template-id.
4554 //
4555 // C++98 has the same restriction, just worded differently.
4556 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4557 Diag(D.getIdentifierLoc(),
4558 diag::err_explicit_instantiation_without_qualified_id)
4559 << Prev << D.getCXXScopeSpec().getRange();
4560
4561 // Check the scope of this explicit instantiation.
4562 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4563
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004564 // Verify that it is okay to explicitly instantiate here.
4565 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4566 assert(MSInfo && "Missing static data member specialization info?");
4567 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004568 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004569 MSInfo->getTemplateSpecializationKind(),
4570 MSInfo->getPointOfInstantiation(),
4571 SuppressNew))
4572 return true;
4573 if (SuppressNew)
4574 return DeclPtrTy();
4575
Douglas Gregor450f00842009-09-25 18:43:00 +00004576 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004577 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004578 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004579 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4580 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004581
4582 // FIXME: Create an ExplicitInstantiation node?
4583 return DeclPtrTy();
4584 }
4585
Douglas Gregor0e876e02009-09-25 23:53:26 +00004586 // If the declarator is a template-id, translate the parser's template
4587 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004588 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004589 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004590 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4591 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004592 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4593 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004594 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4595 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004596 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004597 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004598 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004599 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004600 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004601
Douglas Gregor450f00842009-09-25 18:43:00 +00004602 // C++ [temp.explicit]p1:
4603 // A [...] function [...] can be explicitly instantiated from its template.
4604 // A member function [...] of a class template can be explicitly
4605 // instantiated from the member definition associated with its class
4606 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004607 llvm::SmallVector<FunctionDecl *, 8> Matches;
4608 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4609 P != PEnd; ++P) {
4610 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004611 if (!HasExplicitTemplateArgs) {
4612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4613 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4614 Matches.clear();
4615 Matches.push_back(Method);
4616 break;
4617 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004618 }
4619 }
4620
4621 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4622 if (!FunTmpl)
4623 continue;
4624
4625 TemplateDeductionInfo Info(Context);
4626 FunctionDecl *Specialization = 0;
4627 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004628 = DeduceTemplateArguments(FunTmpl,
4629 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004630 R, Specialization, Info)) {
4631 // FIXME: Keep track of almost-matches?
4632 (void)TDK;
4633 continue;
4634 }
4635
4636 Matches.push_back(Specialization);
4637 }
4638
4639 // Find the most specialized function template specialization.
4640 FunctionDecl *Specialization
4641 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4642 D.getIdentifierLoc(),
4643 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4644 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4645 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4646
4647 if (!Specialization)
4648 return true;
4649
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004650 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004651 Diag(D.getIdentifierLoc(),
4652 diag::err_explicit_instantiation_member_function_not_instantiated)
4653 << Specialization
4654 << (Specialization->getTemplateSpecializationKind() ==
4655 TSK_ExplicitSpecialization);
4656 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4657 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004658 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004659
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004660 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004661 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4662 PrevDecl = Specialization;
4663
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004664 if (PrevDecl) {
4665 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004666 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004667 PrevDecl,
4668 PrevDecl->getTemplateSpecializationKind(),
4669 PrevDecl->getPointOfInstantiation(),
4670 SuppressNew))
4671 return true;
4672
4673 // FIXME: We may still want to build some representation of this
4674 // explicit specialization.
4675 if (SuppressNew)
4676 return DeclPtrTy();
4677 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004678
4679 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004680
4681 if (TSK == TSK_ExplicitInstantiationDefinition)
4682 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4683 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004684
Douglas Gregore47f5a72009-10-14 23:41:34 +00004685 // C++0x [temp.explicit]p2:
4686 // If the explicit instantiation is for a member function, a member class
4687 // or a static data member of a class template specialization, the name of
4688 // the class template specialization in the qualified-id for the member
4689 // name shall be a simple-template-id.
4690 //
4691 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004692 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004693 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004694 D.getCXXScopeSpec().isSet() &&
4695 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4696 Diag(D.getIdentifierLoc(),
4697 diag::err_explicit_instantiation_without_qualified_id)
4698 << Specialization << D.getCXXScopeSpec().getRange();
4699
4700 CheckExplicitInstantiationScope(*this,
4701 FunTmpl? (NamedDecl *)FunTmpl
4702 : Specialization->getInstantiatedFromMemberFunction(),
4703 D.getIdentifierLoc(),
4704 D.getCXXScopeSpec().isSet());
4705
Douglas Gregor450f00842009-09-25 18:43:00 +00004706 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4707 return DeclPtrTy();
4708}
4709
Douglas Gregor333489b2009-03-27 23:10:48 +00004710Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004711Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4712 const CXXScopeSpec &SS, IdentifierInfo *Name,
4713 SourceLocation TagLoc, SourceLocation NameLoc) {
4714 // This has to hold, because SS is expected to be defined.
4715 assert(Name && "Expected a name in a dependent tag");
4716
4717 NestedNameSpecifier *NNS
4718 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4719 if (!NNS)
4720 return true;
4721
4722 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4723 if (T.isNull())
4724 return true;
4725
4726 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4727 QualType ElabType = Context.getElaboratedType(T, TagKind);
4728
4729 return ElabType.getAsOpaquePtr();
4730}
4731
4732Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004733Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4734 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004735 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004736 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4737 if (!NNS)
4738 return true;
4739
4740 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004741 if (T.isNull())
4742 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004743 return T.getAsOpaquePtr();
4744}
4745
Douglas Gregordce2b622009-04-01 00:28:59 +00004746Sema::TypeResult
4747Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4748 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004749 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004750 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004751 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004752 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004753 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004754 assert(TemplateId && "Expected a template specialization type");
4755
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004756 if (computeDeclContext(SS, false)) {
4757 // If we can compute a declaration context, then the "typename"
4758 // keyword was superfluous. Just build a QualifiedNameType to keep
4759 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004760
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004761 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4762 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4763 }
Mike Stump11289f42009-09-09 15:08:12 +00004764
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004765 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004766}
4767
Douglas Gregor333489b2009-03-27 23:10:48 +00004768/// \brief Build the type that describes a C++ typename specifier,
4769/// e.g., "typename T::type".
4770QualType
4771Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4772 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004773 CXXRecordDecl *CurrentInstantiation = 0;
4774 if (NNS->isDependent()) {
4775 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004776
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004777 // If the nested-name-specifier does not refer to the current
4778 // instantiation, then build a typename type.
4779 if (!CurrentInstantiation)
4780 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004781
Douglas Gregorc707da62009-09-02 13:12:51 +00004782 // The nested-name-specifier refers to the current instantiation, so the
4783 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004784 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004785 // extraneous "typename" keywords, and we retroactively apply this DR to
4786 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004787 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004788
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004789 DeclContext *Ctx = 0;
4790
4791 if (CurrentInstantiation)
4792 Ctx = CurrentInstantiation;
4793 else {
4794 CXXScopeSpec SS;
4795 SS.setScopeRep(NNS);
4796 SS.setRange(Range);
4797 if (RequireCompleteDeclContext(SS))
4798 return QualType();
4799
4800 Ctx = computeDeclContext(SS);
4801 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004802 assert(Ctx && "No declaration context?");
4803
4804 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004805 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4806 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004807 unsigned DiagID = 0;
4808 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004809 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004810 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004811 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004812 break;
4813
4814 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004815 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004816 // We found a type. Build a QualifiedNameType, since the
4817 // typename-specifier was just sugar. FIXME: Tell
4818 // QualifiedNameType that it has a "typename" prefix.
4819 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4820 }
4821
4822 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004823 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004824 break;
4825
John McCalle61f2ba2009-11-18 02:36:19 +00004826 case LookupResult::FoundUnresolvedValue:
4827 llvm::llvm_unreachable("unresolved using decl in non-dependent context");
4828 return QualType();
4829
Douglas Gregor333489b2009-03-27 23:10:48 +00004830 case LookupResult::FoundOverloaded:
4831 DiagID = diag::err_typename_nested_not_type;
4832 Referenced = *Result.begin();
4833 break;
4834
John McCall6538c932009-10-10 05:48:19 +00004835 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004836 return QualType();
4837 }
4838
4839 // If we get here, it's because name lookup did not find a
4840 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004841 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004842 if (Referenced)
4843 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4844 << Name;
4845 return QualType();
4846}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004847
4848namespace {
4849 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004850 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4851 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004852 SourceLocation Loc;
4853 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004854
Douglas Gregor15acfb92009-08-06 16:20:37 +00004855 public:
Mike Stump11289f42009-09-09 15:08:12 +00004856 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004857 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004858 DeclarationName Entity)
4859 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004860 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004861
4862 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004863 /// transformed.
4864 ///
4865 /// For the purposes of type reconstruction, a type has already been
4866 /// transformed if it is NULL or if it is not dependent.
4867 bool AlreadyTransformed(QualType T) {
4868 return T.isNull() || !T->isDependentType();
4869 }
Mike Stump11289f42009-09-09 15:08:12 +00004870
4871 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004872 /// rebuilt.
4873 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004874
Douglas Gregor15acfb92009-08-06 16:20:37 +00004875 /// \brief Returns the name of the entity whose type is being rebuilt.
4876 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004877
Douglas Gregoref6ab412009-10-27 06:26:26 +00004878 /// \brief Sets the "base" location and entity when that
4879 /// information is known based on another transformation.
4880 void setBase(SourceLocation Loc, DeclarationName Entity) {
4881 this->Loc = Loc;
4882 this->Entity = Entity;
4883 }
4884
Douglas Gregor15acfb92009-08-06 16:20:37 +00004885 /// \brief Transforms an expression by returning the expression itself
4886 /// (an identity function).
4887 ///
4888 /// FIXME: This is completely unsafe; we will need to actually clone the
4889 /// expressions.
4890 Sema::OwningExprResult TransformExpr(Expr *E) {
4891 return getSema().Owned(E);
4892 }
Mike Stump11289f42009-09-09 15:08:12 +00004893
Douglas Gregor15acfb92009-08-06 16:20:37 +00004894 /// \brief Transforms a typename type by determining whether the type now
4895 /// refers to a member of the current instantiation, and then
4896 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004897 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004898 };
4899}
4900
Mike Stump11289f42009-09-09 15:08:12 +00004901QualType
John McCall550e0c22009-10-21 00:40:46 +00004902CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4903 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004904 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004905
Douglas Gregor15acfb92009-08-06 16:20:37 +00004906 NestedNameSpecifier *NNS
4907 = TransformNestedNameSpecifier(T->getQualifier(),
4908 /*FIXME:*/SourceRange(getBaseLocation()));
4909 if (!NNS)
4910 return QualType();
4911
4912 // If the nested-name-specifier did not change, and we cannot compute the
4913 // context corresponding to the nested-name-specifier, then this
4914 // typename type will not change; exit early.
4915 CXXScopeSpec SS;
4916 SS.setRange(SourceRange(getBaseLocation()));
4917 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004918
4919 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004920 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004921 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004922
4923 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004924 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004925 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004926 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004927 = TransformType(QualType(TemplateId, 0));
4928 if (NewTemplateId.isNull())
4929 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004930
Douglas Gregor15acfb92009-08-06 16:20:37 +00004931 if (NNS == T->getQualifier() &&
4932 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004933 Result = QualType(T, 0);
4934 else
4935 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4936 } else
4937 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4938 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004939
John McCall0ad16662009-10-29 08:12:44 +00004940 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4941 NewTL.setNameLoc(TL.getNameLoc());
4942 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004943}
4944
4945/// \brief Rebuilds a type within the context of the current instantiation.
4946///
Mike Stump11289f42009-09-09 15:08:12 +00004947/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004948/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004949/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004950/// partial specialization thereof). This routine will rebuild that type now
4951/// that we have entered the declarator's scope, which may produce different
4952/// canonical types, e.g.,
4953///
4954/// \code
4955/// template<typename T>
4956/// struct X {
4957/// typedef T* pointer;
4958/// pointer data();
4959/// };
4960///
4961/// template<typename T>
4962/// typename X<T>::pointer X<T>::data() { ... }
4963/// \endcode
4964///
4965/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4966/// since we do not know that we can look into X<T> when we parsed the type.
4967/// This function will rebuild the type, performing the lookup of "pointer"
4968/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4969/// as the canonical type of T*, allowing the return types of the out-of-line
4970/// definition and the declaration to match.
4971QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4972 DeclarationName Name) {
4973 if (T.isNull() || !T->isDependentType())
4974 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004975
Douglas Gregor15acfb92009-08-06 16:20:37 +00004976 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4977 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004978}
Douglas Gregorbe999392009-09-15 16:23:51 +00004979
4980/// \brief Produces a formatted string that describes the binding of
4981/// template parameters to template arguments.
4982std::string
4983Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4984 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004985 // FIXME: For variadic templates, we'll need to get the structured list.
4986 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4987 Args.flat_size());
4988}
4989
4990std::string
4991Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4992 const TemplateArgument *Args,
4993 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004994 std::string Result;
4995
Douglas Gregore62e6a02009-11-11 19:13:48 +00004996 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004997 return Result;
4998
4999 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005000 if (I >= NumArgs)
5001 break;
5002
Douglas Gregorbe999392009-09-15 16:23:51 +00005003 if (I == 0)
5004 Result += "[with ";
5005 else
5006 Result += ", ";
5007
5008 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5009 Result += Id->getName();
5010 } else {
5011 Result += '$';
5012 Result += llvm::utostr(I);
5013 }
5014
5015 Result += " = ";
5016
5017 switch (Args[I].getKind()) {
5018 case TemplateArgument::Null:
5019 Result += "<no value>";
5020 break;
5021
5022 case TemplateArgument::Type: {
5023 std::string TypeStr;
5024 Args[I].getAsType().getAsStringInternal(TypeStr,
5025 Context.PrintingPolicy);
5026 Result += TypeStr;
5027 break;
5028 }
5029
5030 case TemplateArgument::Declaration: {
5031 bool Unnamed = true;
5032 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5033 if (ND->getDeclName()) {
5034 Unnamed = false;
5035 Result += ND->getNameAsString();
5036 }
5037 }
5038
5039 if (Unnamed) {
5040 Result += "<anonymous>";
5041 }
5042 break;
5043 }
5044
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005045 case TemplateArgument::Template: {
5046 std::string Str;
5047 llvm::raw_string_ostream OS(Str);
5048 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5049 Result += OS.str();
5050 break;
5051 }
5052
Douglas Gregorbe999392009-09-15 16:23:51 +00005053 case TemplateArgument::Integral: {
5054 Result += Args[I].getAsIntegral()->toString(10);
5055 break;
5056 }
5057
5058 case TemplateArgument::Expression: {
5059 assert(false && "No expressions in deduced template arguments!");
5060 Result += "<expression>";
5061 break;
5062 }
5063
5064 case TemplateArgument::Pack:
5065 // FIXME: Format template argument packs
5066 Result += "<template argument pack>";
5067 break;
5068 }
5069 }
5070
5071 Result += ']';
5072 return Result;
5073}