blob: 9dad2f63c87abf077629e15c498b50986181691b [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 Gregorbe999392009-09-15 16:23:51 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000024using namespace clang;
25
Douglas Gregorb7bfe792009-09-02 22:59:36 +000026/// \brief Determine whether the declaration found is acceptable as the name
27/// of a template and, if so, return that template declaration. Otherwise,
28/// returns NULL.
29static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
30 if (!D)
31 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000032
Douglas Gregorb7bfe792009-09-02 22:59:36 +000033 if (isa<TemplateDecl>(D))
34 return D;
Mike Stump11289f42009-09-09 15:08:12 +000035
Douglas Gregorb7bfe792009-09-02 22:59:36 +000036 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
37 // C++ [temp.local]p1:
38 // Like normal (non-template) classes, class templates have an
39 // injected-class-name (Clause 9). The injected-class-name
40 // can be used with or without a template-argument-list. When
41 // it is used without a template-argument-list, it is
42 // equivalent to the injected-class-name followed by the
43 // template-parameters of the class template enclosed in
44 // <>. When it is used with a template-argument-list, it
45 // refers to the specified class template specialization,
46 // which could be the current specialization or another
47 // specialization.
48 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000049 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000050 if (Record->getDescribedClassTemplate())
51 return Record->getDescribedClassTemplate();
52
53 if (ClassTemplateSpecializationDecl *Spec
54 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
55 return Spec->getSpecializedTemplate();
56 }
Mike Stump11289f42009-09-09 15:08:12 +000057
Douglas Gregorb7bfe792009-09-02 22:59:36 +000058 return 0;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregorb7bfe792009-09-02 22:59:36 +000061 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
62 if (!Ovl)
63 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000064
Douglas Gregorb7bfe792009-09-02 22:59:36 +000065 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
66 FEnd = Ovl->function_end();
67 F != FEnd; ++F) {
68 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
69 // We've found a function template. Determine whether there are
70 // any other function templates we need to bundle together in an
71 // OverloadedFunctionDecl
72 for (++F; F != FEnd; ++F) {
73 if (isa<FunctionTemplateDecl>(*F))
74 break;
75 }
Mike Stump11289f42009-09-09 15:08:12 +000076
Douglas Gregorb7bfe792009-09-02 22:59:36 +000077 if (F != FEnd) {
78 // Build an overloaded function decl containing only the
79 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000080 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000081 = OverloadedFunctionDecl::Create(Context,
82 Ovl->getDeclContext(),
83 Ovl->getDeclName());
84 OvlTemplate->addOverload(FuncTmpl);
85 OvlTemplate->addOverload(*F);
86 for (++F; F != FEnd; ++F) {
87 if (isa<FunctionTemplateDecl>(*F))
88 OvlTemplate->addOverload(*F);
89 }
Mike Stump11289f42009-09-09 15:08:12 +000090
Douglas Gregorb7bfe792009-09-02 22:59:36 +000091 return OvlTemplate;
92 }
93
94 return FuncTmpl;
95 }
96 }
Mike Stump11289f42009-09-09 15:08:12 +000097
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098 return 0;
99}
100
John McCalle66edc12009-11-24 19:00:30 +0000101static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
102 LookupResult::Filter filter = R.makeFilter();
103 while (filter.hasNext()) {
104 NamedDecl *Orig = filter.next();
105 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
106 if (!Repl)
107 filter.erase();
108 else if (Repl != Orig)
109 filter.replace(Repl);
110 }
111 filter.done();
112}
113
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000114TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000115 const CXXScopeSpec &SS,
116 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000117 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000118 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000119 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000120 DeclarationName TName;
121
122 switch (Name.getKind()) {
123 case UnqualifiedId::IK_Identifier:
124 TName = DeclarationName(Name.Identifier);
125 break;
126
127 case UnqualifiedId::IK_OperatorFunctionId:
128 TName = Context.DeclarationNames.getCXXOperatorName(
129 Name.OperatorFunctionId.Operator);
130 break;
131
Alexis Hunted0530f2009-11-28 08:58:14 +0000132 case UnqualifiedId::IK_LiteralOperatorId:
133 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
134
135
Douglas Gregor3cf81312009-11-03 23:16:33 +0000136 default:
137 return TNK_Non_template;
138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
John McCalle66edc12009-11-24 19:00:30 +0000140 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000141
John McCalle66edc12009-11-24 19:00:30 +0000142 LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName);
143 R.suppressDiagnostics();
144 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
145 if (R.empty())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000146 return TNK_Non_template;
147
John McCalle66edc12009-11-24 19:00:30 +0000148 NamedDecl *Template = R.getAsSingleDecl(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000149
Douglas Gregor3cf81312009-11-03 23:16:33 +0000150 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000151 NestedNameSpecifier *Qualifier
Douglas Gregor3cf81312009-11-03 23:16:33 +0000152 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000153 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000154 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000155 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000156 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
157 Ovl));
158 else
Mike Stump11289f42009-09-09 15:08:12 +0000159 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000160 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000161 cast<TemplateDecl>(Template)));
162 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000163 = dyn_cast<OverloadedFunctionDecl>(Template)) {
164 TemplateResult = TemplateTy::make(TemplateName(Ovl));
165 } else {
166 TemplateResult = TemplateTy::make(
167 TemplateName(cast<TemplateDecl>(Template)));
168 }
Mike Stump11289f42009-09-09 15:08:12 +0000169
170 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000171 isa<TemplateTemplateParmDecl>(Template))
172 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000173
174 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000175 isa<OverloadedFunctionDecl>(Template)) &&
176 "Unhandled template kind in Sema::isTemplateName");
John McCalle66edc12009-11-24 19:00:30 +0000177 return TNK_Function_template;
178}
179
180void Sema::LookupTemplateName(LookupResult &Found,
181 Scope *S, const CXXScopeSpec &SS,
182 QualType ObjectType,
183 bool EnteringContext) {
184 // Determine where to perform name lookup
185 DeclContext *LookupCtx = 0;
186 bool isDependent = false;
187 if (!ObjectType.isNull()) {
188 // This nested-name-specifier occurs in a member access expression, e.g.,
189 // x->B::f, and we are looking into the type of the object.
190 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
191 LookupCtx = computeDeclContext(ObjectType);
192 isDependent = ObjectType->isDependentType();
193 assert((isDependent || !ObjectType->isIncompleteType()) &&
194 "Caller should have completed object type");
195 } else if (SS.isSet()) {
196 // This nested-name-specifier occurs after another nested-name-specifier,
197 // so long into the context associated with the prior nested-name-specifier.
198 LookupCtx = computeDeclContext(SS, EnteringContext);
199 isDependent = isDependentScopeSpecifier(SS);
200
201 // The declaration context must be complete.
202 if (LookupCtx && RequireCompleteDeclContext(SS))
203 return;
204 }
205
206 bool ObjectTypeSearchedInScope = false;
207 if (LookupCtx) {
208 // Perform "qualified" name lookup into the declaration context we
209 // computed, which is either the type of the base of a member access
210 // expression or the declaration context associated with a prior
211 // nested-name-specifier.
212 LookupQualifiedName(Found, LookupCtx);
213
214 if (!ObjectType.isNull() && Found.empty()) {
215 // C++ [basic.lookup.classref]p1:
216 // In a class member access expression (5.2.5), if the . or -> token is
217 // immediately followed by an identifier followed by a <, the
218 // identifier must be looked up to determine whether the < is the
219 // beginning of a template argument list (14.2) or a less-than operator.
220 // The identifier is first looked up in the class of the object
221 // expression. If the identifier is not found, it is then looked up in
222 // the context of the entire postfix-expression and shall name a class
223 // or function template.
224 //
225 // FIXME: When we're instantiating a template, do we actually have to
226 // look in the scope of the template? Seems fishy...
227 if (S) LookupName(Found, S);
228 ObjectTypeSearchedInScope = true;
229 }
230 } else if (isDependent) {
231 // We cannot look into a dependent object type or
232 return;
233 } else {
234 // Perform unqualified name lookup in the current scope.
235 LookupName(Found, S);
236 }
237
238 // FIXME: Cope with ambiguous name-lookup results.
239 assert(!Found.isAmbiguous() &&
240 "Cannot handle template name-lookup ambiguities");
241
242 FilterAcceptableTemplateNames(Context, Found);
243 if (Found.empty())
244 return;
245
246 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
247 // C++ [basic.lookup.classref]p1:
248 // [...] If the lookup in the class of the object expression finds a
249 // template, the name is also looked up in the context of the entire
250 // postfix-expression and [...]
251 //
252 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
253 LookupOrdinaryName);
254 LookupName(FoundOuter, S);
255 FilterAcceptableTemplateNames(Context, FoundOuter);
256 // FIXME: Handle ambiguities in this lookup better
257
258 if (FoundOuter.empty()) {
259 // - if the name is not found, the name found in the class of the
260 // object expression is used, otherwise
261 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
262 // - if the name is found in the context of the entire
263 // postfix-expression and does not name a class template, the name
264 // found in the class of the object expression is used, otherwise
265 } else {
266 // - if the name found is a class template, it must refer to the same
267 // entity as the one found in the class of the object expression,
268 // otherwise the program is ill-formed.
269 if (!Found.isSingleResult() ||
270 Found.getFoundDecl()->getCanonicalDecl()
271 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
272 Diag(Found.getNameLoc(),
273 diag::err_nested_name_member_ref_lookup_ambiguous)
274 << Found.getLookupName();
275 Diag(Found.getRepresentativeDecl()->getLocation(),
276 diag::note_ambig_member_ref_object_type)
277 << ObjectType;
278 Diag(FoundOuter.getFoundDecl()->getLocation(),
279 diag::note_ambig_member_ref_scope);
280
281 // Recover by taking the template that we found in the object
282 // expression's type.
283 }
284 }
285 }
286}
287
288/// Constructs a full type for the given nested-name-specifier.
289static QualType GetTypeForQualifier(ASTContext &Context,
290 NestedNameSpecifier *Qualifier) {
291 // Three possibilities:
292
293 // 1. A namespace (global or not).
294 assert(!Qualifier->getAsNamespace() && "can't construct type for namespace");
295
296 // 2. A type (templated or not).
297 Type *Ty = Qualifier->getAsType();
298 if (Ty) return QualType(Ty, 0);
299
300 // 3. A dependent identifier.
301 assert(Qualifier->getAsIdentifier());
302 return Context.getTypenameType(Qualifier->getPrefix(),
303 Qualifier->getAsIdentifier());
304}
305
306static bool HasDependentTypeAsBase(ASTContext &Context,
307 CXXRecordDecl *Record,
308 CanQualType T) {
309 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
310 E = Record->bases_end(); I != E; ++I) {
311 CanQualType BaseT = Context.getCanonicalType((*I).getType());
312 if (BaseT == T)
313 return true;
314
315 // We have to recurse here to cover some really bizarre cases.
316 // Obviously, we can only have the dependent type as an indirect
317 // base class through a dependent base class, and usually it's
318 // impossible to know which instantiation a dependent base class
319 // will have. But! If we're actually *inside* the dependent base
320 // class, then we know its instantiation and can therefore be
321 // reasonably expected to look into it.
322
323 // template <class T> class A : Base<T> {
324 // class Inner : A<T> {
325 // void foo() {
326 // Base<T>::foo(); // statically known to be an implicit member
327 // reference
328 // }
329 // };
330 // };
331
332 CanQual<RecordType> RT = BaseT->getAs<RecordType>();
John McCall45b1a472009-11-24 20:33:45 +0000333
334 // Base might be a dependent member type, in which case we
335 // obviously can't look into it.
336 if (!RT) continue;
337
John McCalle66edc12009-11-24 19:00:30 +0000338 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(RT->getDecl());
339 if (BaseRecord->isDefinition() &&
340 HasDependentTypeAsBase(Context, BaseRecord, T))
341 return true;
342 }
343
344 return false;
345}
346
347/// Checks whether the given dependent nested-name specifier
348/// introduces an implicit member reference. This is only true if the
349/// nested-name specifier names a type identical to one of the current
350/// instance method's context's (possibly indirect) base classes.
351static bool IsImplicitDependentMemberReference(Sema &SemaRef,
352 NestedNameSpecifier *Qualifier,
353 QualType &ThisType) {
354 // If the context isn't a C++ method, then it isn't an implicit
355 // member reference.
356 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext);
357 if (!MD || MD->isStatic())
358 return false;
359
360 ASTContext &Context = SemaRef.Context;
361
362 // We want to check whether the method's context is known to inherit
363 // from the type named by the nested name specifier. The trivial
364 // case here is:
365 // template <class T> class Base { ... };
366 // template <class T> class Derived : Base<T> {
367 // void foo() {
368 // Base<T>::foo();
369 // }
370 // };
371
372 QualType QT = GetTypeForQualifier(Context, Qualifier);
373 CanQualType T = Context.getCanonicalType(QT);
John McCall45b1a472009-11-24 20:33:45 +0000374
John McCalle66edc12009-11-24 19:00:30 +0000375 // And now, just walk the non-dependent type hierarchy, trying to
376 // find the given type as a literal base class.
377 CXXRecordDecl *Record = cast<CXXRecordDecl>(MD->getParent());
John McCall45b1a472009-11-24 20:33:45 +0000378 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T ||
379 HasDependentTypeAsBase(Context, Record, T)) {
380 ThisType = MD->getThisType(Context);
John McCalle66edc12009-11-24 19:00:30 +0000381 return true;
John McCall45b1a472009-11-24 20:33:45 +0000382 }
John McCalle66edc12009-11-24 19:00:30 +0000383
John McCall45b1a472009-11-24 20:33:45 +0000384 return false;
John McCalle66edc12009-11-24 19:00:30 +0000385}
386
387/// ActOnDependentIdExpression - Handle a dependent declaration name
388/// that was just parsed.
389Sema::OwningExprResult
390Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
391 DeclarationName Name,
392 SourceLocation NameLoc,
393 bool CheckForImplicitMember,
394 const TemplateArgumentListInfo *TemplateArgs) {
395 NestedNameSpecifier *Qualifier
396 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
397
398 QualType ThisType;
399 if (CheckForImplicitMember &&
400 IsImplicitDependentMemberReference(*this, Qualifier, ThisType)) {
401 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
402
403 // Since the 'this' expression is synthesized, we don't need to
404 // perform the double-lookup check.
405 NamedDecl *FirstQualifierInScope = 0;
406
407 return Owned(CXXDependentScopeMemberExpr::Create(Context, This, true,
408 /*Op*/ SourceLocation(),
409 Qualifier, SS.getRange(),
410 FirstQualifierInScope,
411 Name, NameLoc,
412 TemplateArgs));
413 }
414
415 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
416}
417
418Sema::OwningExprResult
419Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
420 DeclarationName Name,
421 SourceLocation NameLoc,
422 const TemplateArgumentListInfo *TemplateArgs) {
423 return Owned(DependentScopeDeclRefExpr::Create(Context,
424 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
425 SS.getRange(),
426 Name, NameLoc,
427 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000428}
429
Douglas Gregor5101c242008-12-05 18:15:24 +0000430/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
431/// that the template parameter 'PrevDecl' is being shadowed by a new
432/// declaration at location Loc. Returns true to indicate that this is
433/// an error, and false otherwise.
434bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000435 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000436
437 // Microsoft Visual C++ permits template parameters to be shadowed.
438 if (getLangOptions().Microsoft)
439 return false;
440
441 // C++ [temp.local]p4:
442 // A template-parameter shall not be redeclared within its
443 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000444 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000445 << cast<NamedDecl>(PrevDecl)->getDeclName();
446 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
447 return true;
448}
449
Douglas Gregor463421d2009-03-03 04:44:36 +0000450/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000451/// the parameter D to reference the templated declaration and return a pointer
452/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000453TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000454 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000455 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000456 return Temp;
457 }
458 return 0;
459}
460
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000461static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
462 const ParsedTemplateArgument &Arg) {
463
464 switch (Arg.getKind()) {
465 case ParsedTemplateArgument::Type: {
466 DeclaratorInfo *DI;
467 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
468 if (!DI)
469 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
470 return TemplateArgumentLoc(TemplateArgument(T), DI);
471 }
472
473 case ParsedTemplateArgument::NonType: {
474 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
475 return TemplateArgumentLoc(TemplateArgument(E), E);
476 }
477
478 case ParsedTemplateArgument::Template: {
479 TemplateName Template
480 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
481 return TemplateArgumentLoc(TemplateArgument(Template),
482 Arg.getScopeSpec().getRange(),
483 Arg.getLocation());
484 }
485 }
486
487 llvm::llvm_unreachable("Unhandled parsed template argument");
488 return TemplateArgumentLoc();
489}
490
491/// \brief Translates template arguments as provided by the parser
492/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000493void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
494 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000495 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000496 TemplateArgs.addArgument(translateTemplateArgument(*this,
497 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000498}
499
Douglas Gregor5101c242008-12-05 18:15:24 +0000500/// ActOnTypeParameter - Called when a C++ template type parameter
501/// (e.g., "typename T") has been parsed. Typename specifies whether
502/// the keyword "typename" was used to declare the type parameter
503/// (otherwise, "class" was used), and KeyLoc is the location of the
504/// "class" or "typename" keyword. ParamName is the name of the
505/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000506/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000507/// If the type parameter has a default argument, it will be added
508/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000509Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000510 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000511 SourceLocation KeyLoc,
512 IdentifierInfo *ParamName,
513 SourceLocation ParamNameLoc,
514 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000515 assert(S->isTemplateParamScope() &&
516 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000517 bool Invalid = false;
518
519 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000520 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000521 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000522 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000523 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000524 }
525
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000526 SourceLocation Loc = ParamNameLoc;
527 if (!ParamName)
528 Loc = KeyLoc;
529
Douglas Gregor5101c242008-12-05 18:15:24 +0000530 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000531 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
532 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000533 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000534 if (Invalid)
535 Param->setInvalidDecl();
536
537 if (ParamName) {
538 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000539 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000540 IdResolver.AddDecl(Param);
541 }
542
Chris Lattner83f095c2009-03-28 19:18:32 +0000543 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000544}
545
Douglas Gregordba32632009-02-10 19:49:53 +0000546/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000547/// Default) to the given template type parameter (TypeParam).
548void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000549 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000550 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000551 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000552 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000553 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000554
555 DeclaratorInfo *DefaultDInfo;
556 GetTypeFromParser(DefaultT, &DefaultDInfo);
557
558 assert(DefaultDInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000559
Anders Carlssond3824352009-06-12 22:30:13 +0000560 // C++0x [temp.param]p9:
561 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000562 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000563 if (Parm->isParameterPack()) {
564 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000565 return;
566 }
Mike Stump11289f42009-09-09 15:08:12 +0000567
Douglas Gregordba32632009-02-10 19:49:53 +0000568 // C++ [temp.param]p14:
569 // A template-parameter shall not be used in its own default argument.
570 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000571
Douglas Gregordba32632009-02-10 19:49:53 +0000572 // Check the template argument itself.
John McCall0ad16662009-10-29 08:12:44 +0000573 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000574 Parm->setInvalidDecl();
575 return;
576 }
577
John McCall0ad16662009-10-29 08:12:44 +0000578 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000579}
580
Douglas Gregor463421d2009-03-03 04:44:36 +0000581/// \brief Check that the type of a non-type template parameter is
582/// well-formed.
583///
584/// \returns the (possibly-promoted) parameter type if valid;
585/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000586QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000587Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
588 // C++ [temp.param]p4:
589 //
590 // A non-type template-parameter shall have one of the following
591 // (optionally cv-qualified) types:
592 //
593 // -- integral or enumeration type,
594 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000595 // -- pointer to object or pointer to function,
596 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000597 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
598 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000599 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000600 T->isReferenceType() ||
601 // -- pointer to member.
602 T->isMemberPointerType() ||
603 // If T is a dependent type, we can't do the check now, so we
604 // assume that it is well-formed.
605 T->isDependentType())
606 return T;
607 // C++ [temp.param]p8:
608 //
609 // A non-type template-parameter of type "array of T" or
610 // "function returning T" is adjusted to be of type "pointer to
611 // T" or "pointer to function returning T", respectively.
612 else if (T->isArrayType())
613 // FIXME: Keep the type prior to promotion?
614 return Context.getArrayDecayedType(T);
615 else if (T->isFunctionType())
616 // FIXME: Keep the type prior to promotion?
617 return Context.getPointerType(T);
618
619 Diag(Loc, diag::err_template_nontype_parm_bad_type)
620 << T;
621
622 return QualType();
623}
624
Douglas Gregor5101c242008-12-05 18:15:24 +0000625/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
626/// template parameter (e.g., "int Size" in "template<int Size>
627/// class Array") has been parsed. S is the current scope and D is
628/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000629Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000630 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000631 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000632 DeclaratorInfo *DInfo = 0;
633 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000634
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000635 assert(S->isTemplateParamScope() &&
636 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000637 bool Invalid = false;
638
639 IdentifierInfo *ParamName = D.getIdentifier();
640 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000641 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000642 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000643 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000644 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000645 }
646
Douglas Gregor463421d2009-03-03 04:44:36 +0000647 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000648 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000649 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000650 Invalid = true;
651 }
Douglas Gregor81338792009-02-10 17:43:50 +0000652
Douglas Gregor5101c242008-12-05 18:15:24 +0000653 NonTypeTemplateParmDecl *Param
654 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000655 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000656 if (Invalid)
657 Param->setInvalidDecl();
658
659 if (D.getIdentifier()) {
660 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000661 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000662 IdResolver.AddDecl(Param);
663 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000664 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000665}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000666
Douglas Gregordba32632009-02-10 19:49:53 +0000667/// \brief Adds a default argument to the given non-type template
668/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000669void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000670 SourceLocation EqualLoc,
671 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000672 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000673 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000674 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000675
Douglas Gregordba32632009-02-10 19:49:53 +0000676 // C++ [temp.param]p14:
677 // A template-parameter shall not be used in its own default argument.
678 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000679
Douglas Gregordba32632009-02-10 19:49:53 +0000680 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000681 TemplateArgument Converted;
682 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
683 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000684 TemplateParm->setInvalidDecl();
685 return;
686 }
687
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000688 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000689}
690
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000691
692/// ActOnTemplateTemplateParameter - Called when a C++ template template
693/// parameter (e.g. T in template <template <typename> class T> class array)
694/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000695Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
696 SourceLocation TmpLoc,
697 TemplateParamsTy *Params,
698 IdentifierInfo *Name,
699 SourceLocation NameLoc,
700 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000701 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000702 assert(S->isTemplateParamScope() &&
703 "Template template parameter not in template parameter scope!");
704
705 // Construct the parameter object.
706 TemplateTemplateParmDecl *Param =
707 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
708 Position, Name,
709 (TemplateParameterList*)Params);
710
711 // Make sure the parameter is valid.
712 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
713 // do anything yet. However, if the template parameter list or (eventual)
714 // default value is ever invalidated, that will propagate here.
715 bool Invalid = false;
716 if (Invalid) {
717 Param->setInvalidDecl();
718 }
719
720 // If the tt-param has a name, then link the identifier into the scope
721 // and lookup mechanisms.
722 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000723 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000724 IdResolver.AddDecl(Param);
725 }
726
Chris Lattner83f095c2009-03-28 19:18:32 +0000727 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000728}
729
Douglas Gregordba32632009-02-10 19:49:53 +0000730/// \brief Adds a default argument to the given template template
731/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000732void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000733 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000734 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000735 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000736 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000737
Douglas Gregordba32632009-02-10 19:49:53 +0000738 // C++ [temp.param]p14:
739 // A template-parameter shall not be used in its own default argument.
740 // FIXME: Implement this check! Needs a recursive walk over the types.
741
Douglas Gregore62e6a02009-11-11 19:13:48 +0000742 // Check only that we have a template template argument. We don't want to
743 // try to check well-formedness now, because our template template parameter
744 // might have dependent types in its template parameters, which we wouldn't
745 // be able to match now.
746 //
747 // If none of the template template parameter's template arguments mention
748 // other template parameters, we could actually perform more checking here.
749 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000750 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000751 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
752 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
753 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000754 return;
755 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000756
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000757 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000758}
759
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000760/// ActOnTemplateParameterList - Builds a TemplateParameterList that
761/// contains the template parameters in Params/NumParams.
762Sema::TemplateParamsTy *
763Sema::ActOnTemplateParameterList(unsigned Depth,
764 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000765 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000766 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000767 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000768 SourceLocation RAngleLoc) {
769 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000770 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000771
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000772 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000773 (NamedDecl**)Params, NumParams,
774 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000775}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000776
Douglas Gregorc08f4892009-03-25 00:13:59 +0000777Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000778Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000779 SourceLocation KWLoc, const CXXScopeSpec &SS,
780 IdentifierInfo *Name, SourceLocation NameLoc,
781 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000782 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000783 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000784 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000785 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000786 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000787 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000788
789 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000790 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000791 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000792
John McCall27b5c252009-09-14 21:59:20 +0000793 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
794 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000795
796 // There is no such thing as an unnamed class template.
797 if (!Name) {
798 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000799 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000800 }
801
802 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000803 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000804 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000805 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000806 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000807 if (RequireCompleteDeclContext(SS))
808 return true;
809
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000810 SemanticContext = computeDeclContext(SS, true);
811 if (!SemanticContext) {
812 // FIXME: Produce a reasonable diagnostic here
813 return true;
814 }
Mike Stump11289f42009-09-09 15:08:12 +0000815
John McCall27b18f82009-11-17 02:14:36 +0000816 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000817 } else {
818 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000819 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000820 }
Mike Stump11289f42009-09-09 15:08:12 +0000821
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000822 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
823 NamedDecl *PrevDecl = 0;
824 if (Previous.begin() != Previous.end())
825 PrevDecl = *Previous.begin();
826
Douglas Gregor9acb6902009-09-26 07:05:09 +0000827 if (PrevDecl && TUK == TUK_Friend) {
828 // C++ [namespace.memdef]p3:
829 // [...] When looking for a prior declaration of a class or a function
830 // declared as a friend, and when the name of the friend class or
831 // function is neither a qualified name nor a template-id, scopes outside
832 // the innermost enclosing namespace scope are not considered.
833 DeclContext *OutermostContext = CurContext;
834 while (!OutermostContext->isFileContext())
835 OutermostContext = OutermostContext->getLookupParent();
836
837 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
838 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
839 SemanticContext = PrevDecl->getDeclContext();
840 } else {
841 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000842 // context we computed is the semantic context for our new
Douglas Gregor9acb6902009-09-26 07:05:09 +0000843 // declaration.
844 PrevDecl = 0;
845 SemanticContext = OutermostContext;
846 }
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000847
848 if (CurContext->isDependentContext()) {
849 // If this is a dependent context, we don't want to link the friend
850 // class template to the template in scope, because that would perform
851 // checking of the template parameter lists that can't be performed
852 // until the outer context is instantiated.
853 PrevDecl = 0;
854 }
Douglas Gregor9acb6902009-09-26 07:05:09 +0000855 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000856 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000857
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000858 // If there is a previous declaration with the same name, check
859 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000860 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000861 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000862
863 // We may have found the injected-class-name of a class template,
864 // class template partial specialization, or class template specialization.
865 // In these cases, grab the template that is being defined or specialized.
866 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
867 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
868 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
869 PrevClassTemplate
870 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
871 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
872 PrevClassTemplate
873 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
874 ->getSpecializedTemplate();
875 }
876 }
877
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000878 if (PrevClassTemplate) {
879 // Ensure that the template parameter lists are compatible.
880 if (!TemplateParameterListsAreEqual(TemplateParams,
881 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000882 /*Complain=*/true,
883 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000884 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000885
886 // C++ [temp.class]p4:
887 // In a redeclaration, partial specialization, explicit
888 // specialization or explicit instantiation of a class template,
889 // the class-key shall agree in kind with the original class
890 // template declaration (7.1.5.3).
891 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000892 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000893 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000894 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000895 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000896 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000897 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000898 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000899 }
900
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000901 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000902 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000903 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
904 Diag(NameLoc, diag::err_redefinition) << Name;
905 Diag(Def->getLocation(), diag::note_previous_definition);
906 // FIXME: Would it make sense to try to "forget" the previous
907 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000908 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000909 }
910 }
911 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
912 // Maybe we will complain about the shadowed template parameter.
913 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
914 // Just pretend that we didn't see the previous declaration.
915 PrevDecl = 0;
916 } else if (PrevDecl) {
917 // C++ [temp]p5:
918 // A class template shall not have the same name as any other
919 // template, class, function, object, enumeration, enumerator,
920 // namespace, or type in the same scope (3.3), except as specified
921 // in (14.5.4).
922 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
923 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000924 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000925 }
926
Douglas Gregordba32632009-02-10 19:49:53 +0000927 // Check the template parameter list of this declaration, possibly
928 // merging in the template parameter list from the previous class
929 // template declaration.
930 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000931 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
932 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000933 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000934
Douglas Gregore362cea2009-05-10 22:57:19 +0000935 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000936 // declaration!
937
Mike Stump11289f42009-09-09 15:08:12 +0000938 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000939 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000940 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000941 PrevClassTemplate->getTemplatedDecl() : 0,
942 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000943
944 ClassTemplateDecl *NewTemplate
945 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
946 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000947 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000948 NewClass->setDescribedClassTemplate(NewTemplate);
949
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000950 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000951 QualType T =
952 Context.getTypeDeclType(NewClass,
953 PrevClassTemplate?
954 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000955 assert(T->isDependentType() && "Class template type is not dependent?");
956 (void)T;
957
Douglas Gregorcf915552009-10-13 16:30:37 +0000958 // If we are providing an explicit specialization of a member that is a
959 // class template, make a note of that.
960 if (PrevClassTemplate &&
961 PrevClassTemplate->getInstantiatedFromMemberTemplate())
962 PrevClassTemplate->setMemberSpecialization();
963
Anders Carlsson137108d2009-03-26 01:24:28 +0000964 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000965 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000966 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000968 // Set the lexical context of these templates
969 NewClass->setLexicalDeclContext(CurContext);
970 NewTemplate->setLexicalDeclContext(CurContext);
971
John McCall9bb74a52009-07-31 02:45:11 +0000972 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000973 NewClass->startDefinition();
974
975 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000976 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000977
John McCall27b5c252009-09-14 21:59:20 +0000978 if (TUK != TUK_Friend)
979 PushOnScopeChains(NewTemplate, S);
980 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000981 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000982 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000983 NewClass->setAccess(PrevClassTemplate->getAccess());
984 }
John McCall27b5c252009-09-14 21:59:20 +0000985
Douglas Gregor3dad8422009-09-26 06:47:28 +0000986 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
987 PrevClassTemplate != NULL);
988
John McCall27b5c252009-09-14 21:59:20 +0000989 // Friend templates are visible in fairly strange ways.
990 if (!CurContext->isDependentContext()) {
991 DeclContext *DC = SemanticContext->getLookupContext();
992 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
993 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
994 PushOnScopeChains(NewTemplate, EnclosingScope,
995 /* AddToContext = */ false);
996 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000997
998 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
999 NewClass->getLocation(),
1000 NewTemplate,
1001 /*FIXME:*/NewClass->getLocation());
1002 Friend->setAccess(AS_public);
1003 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001004 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001005
Douglas Gregordba32632009-02-10 19:49:53 +00001006 if (Invalid) {
1007 NewTemplate->setInvalidDecl();
1008 NewClass->setInvalidDecl();
1009 }
Chris Lattner83f095c2009-03-28 19:18:32 +00001010 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001011}
1012
Douglas Gregored5731f2009-11-25 17:50:39 +00001013/// \brief Diagnose the presence of a default template argument on a
1014/// template parameter, which is ill-formed in certain contexts.
1015///
1016/// \returns true if the default template argument should be dropped.
1017static bool DiagnoseDefaultTemplateArgument(Sema &S,
1018 Sema::TemplateParamListContext TPC,
1019 SourceLocation ParamLoc,
1020 SourceRange DefArgRange) {
1021 switch (TPC) {
1022 case Sema::TPC_ClassTemplate:
1023 return false;
1024
1025 case Sema::TPC_FunctionTemplate:
1026 // C++ [temp.param]p9:
1027 // A default template-argument shall not be specified in a
1028 // function template declaration or a function template
1029 // definition [...]
1030 // (This sentence is not in C++0x, per DR226).
1031 if (!S.getLangOptions().CPlusPlus0x)
1032 S.Diag(ParamLoc,
1033 diag::err_template_parameter_default_in_function_template)
1034 << DefArgRange;
1035 return false;
1036
1037 case Sema::TPC_ClassTemplateMember:
1038 // C++0x [temp.param]p9:
1039 // A default template-argument shall not be specified in the
1040 // template-parameter-lists of the definition of a member of a
1041 // class template that appears outside of the member's class.
1042 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1043 << DefArgRange;
1044 return true;
1045
1046 case Sema::TPC_FriendFunctionTemplate:
1047 // C++ [temp.param]p9:
1048 // A default template-argument shall not be specified in a
1049 // friend template declaration.
1050 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1051 << DefArgRange;
1052 return true;
1053
1054 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1055 // for friend function templates if there is only a single
1056 // declaration (and it is a definition). Strange!
1057 }
1058
1059 return false;
1060}
1061
Douglas Gregordba32632009-02-10 19:49:53 +00001062/// \brief Checks the validity of a template parameter list, possibly
1063/// considering the template parameter list from a previous
1064/// declaration.
1065///
1066/// If an "old" template parameter list is provided, it must be
1067/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1068/// template parameter list.
1069///
1070/// \param NewParams Template parameter list for a new template
1071/// declaration. This template parameter list will be updated with any
1072/// default arguments that are carried through from the previous
1073/// template parameter list.
1074///
1075/// \param OldParams If provided, template parameter list from a
1076/// previous declaration of the same template. Default template
1077/// arguments will be merged from the old template parameter list to
1078/// the new template parameter list.
1079///
Douglas Gregored5731f2009-11-25 17:50:39 +00001080/// \param TPC Describes the context in which we are checking the given
1081/// template parameter list.
1082///
Douglas Gregordba32632009-02-10 19:49:53 +00001083/// \returns true if an error occurred, false otherwise.
1084bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001085 TemplateParameterList *OldParams,
1086 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001087 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001088
Douglas Gregordba32632009-02-10 19:49:53 +00001089 // C++ [temp.param]p10:
1090 // The set of default template-arguments available for use with a
1091 // template declaration or definition is obtained by merging the
1092 // default arguments from the definition (if in scope) and all
1093 // declarations in scope in the same way default function
1094 // arguments are (8.3.6).
1095 bool SawDefaultArgument = false;
1096 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001097
Anders Carlsson327865d2009-06-12 23:20:15 +00001098 bool SawParameterPack = false;
1099 SourceLocation ParameterPackLoc;
1100
Mike Stumpc89c8e32009-02-11 23:03:27 +00001101 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001102 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001103 if (OldParams)
1104 OldParam = OldParams->begin();
1105
1106 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1107 NewParamEnd = NewParams->end();
1108 NewParam != NewParamEnd; ++NewParam) {
1109 // Variables used to diagnose redundant default arguments
1110 bool RedundantDefaultArg = false;
1111 SourceLocation OldDefaultLoc;
1112 SourceLocation NewDefaultLoc;
1113
1114 // Variables used to diagnose missing default arguments
1115 bool MissingDefaultArg = false;
1116
Anders Carlsson327865d2009-06-12 23:20:15 +00001117 // C++0x [temp.param]p11:
1118 // If a template parameter of a class template is a template parameter pack,
1119 // it must be the last template parameter.
1120 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001121 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001122 diag::err_template_param_pack_must_be_last_template_parameter);
1123 Invalid = true;
1124 }
1125
Douglas Gregordba32632009-02-10 19:49:53 +00001126 if (TemplateTypeParmDecl *NewTypeParm
1127 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001128 // Check the presence of a default argument here.
1129 if (NewTypeParm->hasDefaultArgument() &&
1130 DiagnoseDefaultTemplateArgument(*this, TPC,
1131 NewTypeParm->getLocation(),
1132 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1133 .getFullSourceRange()))
1134 NewTypeParm->removeDefaultArgument();
1135
1136 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001137 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001138 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001139
Anders Carlsson327865d2009-06-12 23:20:15 +00001140 if (NewTypeParm->isParameterPack()) {
1141 assert(!NewTypeParm->hasDefaultArgument() &&
1142 "Parameter packs can't have a default argument!");
1143 SawParameterPack = true;
1144 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001145 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001146 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001147 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1148 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1149 SawDefaultArgument = true;
1150 RedundantDefaultArg = true;
1151 PreviousDefaultArgLoc = NewDefaultLoc;
1152 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1153 // Merge the default argument from the old declaration to the
1154 // new declaration.
1155 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001156 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001157 true);
1158 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1159 } else if (NewTypeParm->hasDefaultArgument()) {
1160 SawDefaultArgument = true;
1161 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1162 } else if (SawDefaultArgument)
1163 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001164 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001165 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001166 // Check the presence of a default argument here.
1167 if (NewNonTypeParm->hasDefaultArgument() &&
1168 DiagnoseDefaultTemplateArgument(*this, TPC,
1169 NewNonTypeParm->getLocation(),
1170 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1171 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1172 NewNonTypeParm->setDefaultArgument(0);
1173 }
1174
Mike Stump12b8ce12009-08-04 21:02:39 +00001175 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001176 NonTypeTemplateParmDecl *OldNonTypeParm
1177 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001178 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001179 NewNonTypeParm->hasDefaultArgument()) {
1180 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1181 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1182 SawDefaultArgument = true;
1183 RedundantDefaultArg = true;
1184 PreviousDefaultArgLoc = NewDefaultLoc;
1185 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1186 // Merge the default argument from the old declaration to the
1187 // new declaration.
1188 SawDefaultArgument = true;
1189 // FIXME: We need to create a new kind of "default argument"
1190 // expression that points to a previous template template
1191 // parameter.
1192 NewNonTypeParm->setDefaultArgument(
1193 OldNonTypeParm->getDefaultArgument());
1194 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1195 } else if (NewNonTypeParm->hasDefaultArgument()) {
1196 SawDefaultArgument = true;
1197 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1198 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001199 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001200 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001201 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001202 TemplateTemplateParmDecl *NewTemplateParm
1203 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001204 if (NewTemplateParm->hasDefaultArgument() &&
1205 DiagnoseDefaultTemplateArgument(*this, TPC,
1206 NewTemplateParm->getLocation(),
1207 NewTemplateParm->getDefaultArgument().getSourceRange()))
1208 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1209
1210 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001211 TemplateTemplateParmDecl *OldTemplateParm
1212 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001213 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001214 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001215 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1216 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001217 SawDefaultArgument = true;
1218 RedundantDefaultArg = true;
1219 PreviousDefaultArgLoc = NewDefaultLoc;
1220 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1221 // Merge the default argument from the old declaration to the
1222 // new declaration.
1223 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001224 // FIXME: We need to create a new kind of "default argument" expression
1225 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001226 NewTemplateParm->setDefaultArgument(
1227 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001228 PreviousDefaultArgLoc
1229 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001230 } else if (NewTemplateParm->hasDefaultArgument()) {
1231 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001232 PreviousDefaultArgLoc
1233 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001234 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001235 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001236 }
1237
1238 if (RedundantDefaultArg) {
1239 // C++ [temp.param]p12:
1240 // A template-parameter shall not be given default arguments
1241 // by two different declarations in the same scope.
1242 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1243 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1244 Invalid = true;
1245 } else if (MissingDefaultArg) {
1246 // C++ [temp.param]p11:
1247 // If a template-parameter has a default template-argument,
1248 // all subsequent template-parameters shall have a default
1249 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001250 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001251 diag::err_template_param_default_arg_missing);
1252 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1253 Invalid = true;
1254 }
1255
1256 // If we have an old template parameter list that we're merging
1257 // in, move on to the next parameter.
1258 if (OldParams)
1259 ++OldParam;
1260 }
1261
1262 return Invalid;
1263}
Douglas Gregord32e0282009-02-09 23:23:08 +00001264
Mike Stump11289f42009-09-09 15:08:12 +00001265/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001266/// specifier, returning the template parameter list that applies to the
1267/// name.
1268///
1269/// \param DeclStartLoc the start of the declaration that has a scope
1270/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001271///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001272/// \param SS the scope specifier that will be matched to the given template
1273/// parameter lists. This scope specifier precedes a qualified name that is
1274/// being declared.
1275///
1276/// \param ParamLists the template parameter lists, from the outermost to the
1277/// innermost template parameter lists.
1278///
1279/// \param NumParamLists the number of template parameter lists in ParamLists.
1280///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001281/// \param IsExplicitSpecialization will be set true if the entity being
1282/// declared is an explicit specialization, false otherwise.
1283///
Mike Stump11289f42009-09-09 15:08:12 +00001284/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001285/// name that is preceded by the scope specifier @p SS. This template
1286/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001287/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001288/// template specialization), or may be NULL (if we were's declaring isn't
1289/// itself a template).
1290TemplateParameterList *
1291Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1292 const CXXScopeSpec &SS,
1293 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001294 unsigned NumParamLists,
1295 bool &IsExplicitSpecialization) {
1296 IsExplicitSpecialization = false;
1297
Douglas Gregord8d297c2009-07-21 23:53:31 +00001298 // Find the template-ids that occur within the nested-name-specifier. These
1299 // template-ids will match up with the template parameter lists.
1300 llvm::SmallVector<const TemplateSpecializationType *, 4>
1301 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001302 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1303 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001304 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1305 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001306 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001307 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1308 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1309 if (!Template)
1310 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001311
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001312 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001313 ClassTemplateSpecializationDecl *SpecDecl
1314 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1315 // If the nested name specifier refers to an explicit specialization,
1316 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001317 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1318 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001319 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001320 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Douglas Gregord8d297c2009-07-21 23:53:31 +00001323 TemplateIdsInSpecifier.push_back(SpecType);
1324 }
1325 }
Mike Stump11289f42009-09-09 15:08:12 +00001326
Douglas Gregord8d297c2009-07-21 23:53:31 +00001327 // Reverse the list of template-ids in the scope specifier, so that we can
1328 // more easily match up the template-ids and the template parameter lists.
1329 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001330
Douglas Gregord8d297c2009-07-21 23:53:31 +00001331 SourceLocation FirstTemplateLoc = DeclStartLoc;
1332 if (NumParamLists)
1333 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001334
Douglas Gregord8d297c2009-07-21 23:53:31 +00001335 // Match the template-ids found in the specifier to the template parameter
1336 // lists.
1337 unsigned Idx = 0;
1338 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1339 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001340 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1341 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001342 if (Idx >= NumParamLists) {
1343 // We have a template-id without a corresponding template parameter
1344 // list.
1345 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001346 // FIXME: the location information here isn't great.
1347 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001348 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001349 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001350 << SS.getRange();
1351 } else {
1352 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1353 << SS.getRange()
1354 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1355 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001356 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001357 }
1358 return 0;
1359 }
Mike Stump11289f42009-09-09 15:08:12 +00001360
Douglas Gregord8d297c2009-07-21 23:53:31 +00001361 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001362 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001363 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001364 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1365
Mike Stump11289f42009-09-09 15:08:12 +00001366 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001367 = dyn_cast<ClassTemplateDecl>(Template)) {
1368 TemplateParameterList *ExpectedTemplateParams = 0;
1369 // Is this template-id naming the primary template?
1370 if (Context.hasSameType(TemplateId,
1371 ClassTemplate->getInjectedClassNameType(Context)))
1372 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1373 // ... or a partial specialization?
1374 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1375 = ClassTemplate->findPartialSpecialization(TemplateId))
1376 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1377
1378 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001379 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001380 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001381 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001382 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001383
1384 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001385 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001386 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001387 diag::err_template_param_list_matches_nontemplate)
1388 << TemplateId
1389 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001390 else
1391 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001392 }
Mike Stump11289f42009-09-09 15:08:12 +00001393
Douglas Gregord8d297c2009-07-21 23:53:31 +00001394 // If there were at least as many template-ids as there were template
1395 // parameter lists, then there are no template parameter lists remaining for
1396 // the declaration itself.
1397 if (Idx >= NumParamLists)
1398 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001399
Douglas Gregord8d297c2009-07-21 23:53:31 +00001400 // If there were too many template parameter lists, complain about that now.
1401 if (Idx != NumParamLists - 1) {
1402 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001403 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001404 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001405 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1406 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001407 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1408 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001409
1410 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1411 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1412 diag::note_explicit_template_spec_does_not_need_header)
1413 << ExplicitSpecializationsInSpecifier.back();
1414 ExplicitSpecializationsInSpecifier.pop_back();
1415 }
1416
Douglas Gregord8d297c2009-07-21 23:53:31 +00001417 ++Idx;
1418 }
1419 }
Mike Stump11289f42009-09-09 15:08:12 +00001420
Douglas Gregord8d297c2009-07-21 23:53:31 +00001421 // Return the last template parameter list, which corresponds to the
1422 // entity being declared.
1423 return ParamLists[NumParamLists - 1];
1424}
1425
Douglas Gregordc572a32009-03-30 22:58:21 +00001426QualType Sema::CheckTemplateIdType(TemplateName Name,
1427 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001428 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001429 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001430 if (!Template) {
1431 // The template name does not resolve to a template, so we just
1432 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001433 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001434 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001435
Douglas Gregorc40290e2009-03-09 23:48:35 +00001436 // Check that the template argument list is well-formed for this
1437 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001438 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001439 TemplateArgs.size());
1440 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001441 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001442 return QualType();
1443
Mike Stump11289f42009-09-09 15:08:12 +00001444 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001445 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001446 "Converted template argument list is too short!");
1447
1448 QualType CanonType;
1449
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001450 if (Name.isDependent() ||
1451 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001452 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001453 // This class template specialization is a dependent
1454 // type. Therefore, its canonical type is another class template
1455 // specialization type that contains all of the converted
1456 // arguments in canonical form. This ensures that, e.g., A<T> and
1457 // A<T, T> have identical types when A is declared as:
1458 //
1459 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001460 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001461 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001462 Converted.getFlatArguments(),
1463 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001464
Douglas Gregora8e02e72009-07-28 23:00:59 +00001465 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001466 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001467 // In the future, we need to teach getTemplateSpecializationType to only
1468 // build the canonical type and return that to us.
1469 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001470 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001471 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001472 // Find the class template specialization declaration that
1473 // corresponds to these arguments.
1474 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001475 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001476 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001477 Converted.flatSize(),
1478 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001479 void *InsertPos = 0;
1480 ClassTemplateSpecializationDecl *Decl
1481 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1482 if (!Decl) {
1483 // This is the first time we have referenced this class template
1484 // specialization. Create the canonical declaration and add it to
1485 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001486 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001487 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001488 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001489 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001490 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001491 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1492 Decl->setLexicalDeclContext(CurContext);
1493 }
1494
1495 CanonType = Context.getTypeDeclType(Decl);
1496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
Douglas Gregorc40290e2009-03-09 23:48:35 +00001498 // Build the fully-sugared type for this class template
1499 // specialization, which refers back to the class template
1500 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001501 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001502}
1503
Douglas Gregor67a65642009-02-17 23:15:12 +00001504Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001505Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001506 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001507 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001508 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001509 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001510
Douglas Gregorc40290e2009-03-09 23:48:35 +00001511 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001512 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001513 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001514
John McCall6b51f282009-11-23 01:53:49 +00001515 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001516 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001517
1518 if (Result.isNull())
1519 return true;
1520
John McCall0ad16662009-10-29 08:12:44 +00001521 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1522 TemplateSpecializationTypeLoc TL
1523 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1524 TL.setTemplateNameLoc(TemplateLoc);
1525 TL.setLAngleLoc(LAngleLoc);
1526 TL.setRAngleLoc(RAngleLoc);
1527 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1528 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1529
1530 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001531}
John McCall06f6fe8d2009-09-04 01:14:41 +00001532
John McCalld8fe9af2009-09-08 17:47:29 +00001533Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1534 TagUseKind TUK,
1535 DeclSpec::TST TagSpec,
1536 SourceLocation TagLoc) {
1537 if (TypeResult.isInvalid())
1538 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001539
John McCall0ad16662009-10-29 08:12:44 +00001540 // FIXME: preserve source info, ideally without copying the DI.
1541 DeclaratorInfo *DI;
1542 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001543
John McCalld8fe9af2009-09-08 17:47:29 +00001544 // Verify the tag specifier.
1545 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001546
John McCalld8fe9af2009-09-08 17:47:29 +00001547 if (const RecordType *RT = Type->getAs<RecordType>()) {
1548 RecordDecl *D = RT->getDecl();
1549
1550 IdentifierInfo *Id = D->getIdentifier();
1551 assert(Id && "templated class must have an identifier");
1552
1553 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1554 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001555 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001556 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1557 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001558 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001559 }
1560 }
1561
John McCalld8fe9af2009-09-08 17:47:29 +00001562 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1563
1564 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001565}
1566
John McCalle66edc12009-11-24 19:00:30 +00001567Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1568 LookupResult &R,
1569 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001570 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001571 // FIXME: Can we do any checking at this point? I guess we could check the
1572 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001573 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001574 // though.
John McCalle66edc12009-11-24 19:00:30 +00001575
1576 // These should be filtered out by our callers.
1577 assert(!R.empty() && "empty lookup results when building templateid");
1578 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1579
1580 NestedNameSpecifier *Qualifier = 0;
1581 SourceRange QualifierRange;
1582 if (SS.isSet()) {
1583 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1584 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001585 }
1586
John McCalle66edc12009-11-24 19:00:30 +00001587 bool Dependent
1588 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1589 &TemplateArgs);
1590 UnresolvedLookupExpr *ULE
1591 = UnresolvedLookupExpr::Create(Context, Dependent,
1592 Qualifier, QualifierRange,
1593 R.getLookupName(), R.getNameLoc(),
1594 RequiresADL, TemplateArgs);
1595 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1596 ULE->addDecl(*I);
1597
1598 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001599}
1600
John McCalle66edc12009-11-24 19:00:30 +00001601// We actually only call this from template instantiation.
1602Sema::OwningExprResult
1603Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1604 DeclarationName Name,
1605 SourceLocation NameLoc,
1606 const TemplateArgumentListInfo &TemplateArgs) {
1607 DeclContext *DC;
1608 if (!(DC = computeDeclContext(SS, false)) ||
1609 DC->isDependentContext() ||
1610 RequireCompleteDeclContext(SS))
1611 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001612
John McCalle66edc12009-11-24 19:00:30 +00001613 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1614 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001615
John McCalle66edc12009-11-24 19:00:30 +00001616 if (R.isAmbiguous())
1617 return ExprError();
1618
1619 if (R.empty()) {
1620 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1621 << Name << SS.getRange();
1622 return ExprError();
1623 }
1624
1625 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1626 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1627 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1628 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1629 return ExprError();
1630 }
1631
1632 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001633}
1634
Douglas Gregorb67535d2009-03-31 00:43:58 +00001635/// \brief Form a dependent template name.
1636///
1637/// This action forms a dependent template name given the template
1638/// name and its (presumably dependent) scope specifier. For
1639/// example, given "MetaFun::template apply", the scope specifier \p
1640/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1641/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001642Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001643Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001644 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001645 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001646 TypeTy *ObjectType,
1647 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001648 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001649 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001650 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001651 // C++0x [temp.names]p5:
1652 // If a name prefixed by the keyword template is not the name of
1653 // a template, the program is ill-formed. [Note: the keyword
1654 // template may not be applied to non-template members of class
1655 // templates. -end note ] [ Note: as is the case with the
1656 // typename prefix, the template prefix is allowed in cases
1657 // where it is not strictly necessary; i.e., when the
1658 // nested-name-specifier or the expression on the left of the ->
1659 // or . is not dependent on a template-parameter, or the use
1660 // does not appear in the scope of a template. -end note]
1661 //
1662 // Note: C++03 was more strict here, because it banned the use of
1663 // the "template" keyword prior to a template-name that was not a
1664 // dependent name. C++ DR468 relaxed this requirement (the
1665 // "template" keyword is now permitted). We follow the C++0x
1666 // rules, even in C++03 mode, retroactively applying the DR.
1667 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001668 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001669 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001670 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001671 Diag(Name.getSourceRange().getBegin(),
1672 diag::err_template_kw_refers_to_non_template)
1673 << GetNameFromUnqualifiedId(Name)
1674 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001675 return TemplateTy();
1676 }
1677
1678 return Template;
1679 }
1680
Mike Stump11289f42009-09-09 15:08:12 +00001681 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001682 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001683
1684 switch (Name.getKind()) {
1685 case UnqualifiedId::IK_Identifier:
1686 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1687 Name.Identifier));
1688
Douglas Gregor71395fa2009-11-04 00:56:37 +00001689 case UnqualifiedId::IK_OperatorFunctionId:
1690 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1691 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001692
1693 case UnqualifiedId::IK_LiteralOperatorId:
1694 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1695
Douglas Gregor3cf81312009-11-03 23:16:33 +00001696 default:
1697 break;
1698 }
1699
1700 Diag(Name.getSourceRange().getBegin(),
1701 diag::err_template_kw_refers_to_non_template)
1702 << GetNameFromUnqualifiedId(Name)
1703 << Name.getSourceRange();
1704 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001705}
1706
Mike Stump11289f42009-09-09 15:08:12 +00001707bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001708 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001709 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001710 const TemplateArgument &Arg = AL.getArgument();
1711
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001712 // Check template type parameter.
1713 if (Arg.getKind() != TemplateArgument::Type) {
1714 // C++ [temp.arg.type]p1:
1715 // A template-argument for a template-parameter which is a
1716 // type shall be a type-id.
1717
1718 // We have a template type parameter but the template argument
1719 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001720 SourceRange SR = AL.getSourceRange();
1721 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001722 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001723
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001724 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001725 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001726
John McCall0ad16662009-10-29 08:12:44 +00001727 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001728 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001729
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001730 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001731 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001732 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001733 return false;
1734}
1735
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001736/// \brief Substitute template arguments into the default template argument for
1737/// the given template type parameter.
1738///
1739/// \param SemaRef the semantic analysis object for which we are performing
1740/// the substitution.
1741///
1742/// \param Template the template that we are synthesizing template arguments
1743/// for.
1744///
1745/// \param TemplateLoc the location of the template name that started the
1746/// template-id we are checking.
1747///
1748/// \param RAngleLoc the location of the right angle bracket ('>') that
1749/// terminates the template-id.
1750///
1751/// \param Param the template template parameter whose default we are
1752/// substituting into.
1753///
1754/// \param Converted the list of template arguments provided for template
1755/// parameters that precede \p Param in the template parameter list.
1756///
1757/// \returns the substituted template argument, or NULL if an error occurred.
1758static DeclaratorInfo *
1759SubstDefaultTemplateArgument(Sema &SemaRef,
1760 TemplateDecl *Template,
1761 SourceLocation TemplateLoc,
1762 SourceLocation RAngleLoc,
1763 TemplateTypeParmDecl *Param,
1764 TemplateArgumentListBuilder &Converted) {
1765 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1766
1767 // If the argument type is dependent, instantiate it now based
1768 // on the previously-computed template arguments.
1769 if (ArgType->getType()->isDependentType()) {
1770 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1771 /*TakeArgs=*/false);
1772
1773 MultiLevelTemplateArgumentList AllTemplateArgs
1774 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1775
1776 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1777 Template, Converted.getFlatArguments(),
1778 Converted.flatSize(),
1779 SourceRange(TemplateLoc, RAngleLoc));
1780
1781 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1782 Param->getDefaultArgumentLoc(),
1783 Param->getDeclName());
1784 }
1785
1786 return ArgType;
1787}
1788
1789/// \brief Substitute template arguments into the default template argument for
1790/// the given non-type template parameter.
1791///
1792/// \param SemaRef the semantic analysis object for which we are performing
1793/// the substitution.
1794///
1795/// \param Template the template that we are synthesizing template arguments
1796/// for.
1797///
1798/// \param TemplateLoc the location of the template name that started the
1799/// template-id we are checking.
1800///
1801/// \param RAngleLoc the location of the right angle bracket ('>') that
1802/// terminates the template-id.
1803///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001804/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001805/// substituting into.
1806///
1807/// \param Converted the list of template arguments provided for template
1808/// parameters that precede \p Param in the template parameter list.
1809///
1810/// \returns the substituted template argument, or NULL if an error occurred.
1811static Sema::OwningExprResult
1812SubstDefaultTemplateArgument(Sema &SemaRef,
1813 TemplateDecl *Template,
1814 SourceLocation TemplateLoc,
1815 SourceLocation RAngleLoc,
1816 NonTypeTemplateParmDecl *Param,
1817 TemplateArgumentListBuilder &Converted) {
1818 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1819 /*TakeArgs=*/false);
1820
1821 MultiLevelTemplateArgumentList AllTemplateArgs
1822 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1823
1824 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1825 Template, Converted.getFlatArguments(),
1826 Converted.flatSize(),
1827 SourceRange(TemplateLoc, RAngleLoc));
1828
1829 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1830}
1831
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001832/// \brief Substitute template arguments into the default template argument for
1833/// the given template template parameter.
1834///
1835/// \param SemaRef the semantic analysis object for which we are performing
1836/// the substitution.
1837///
1838/// \param Template the template that we are synthesizing template arguments
1839/// for.
1840///
1841/// \param TemplateLoc the location of the template name that started the
1842/// template-id we are checking.
1843///
1844/// \param RAngleLoc the location of the right angle bracket ('>') that
1845/// terminates the template-id.
1846///
1847/// \param Param the template template parameter whose default we are
1848/// substituting into.
1849///
1850/// \param Converted the list of template arguments provided for template
1851/// parameters that precede \p Param in the template parameter list.
1852///
1853/// \returns the substituted template argument, or NULL if an error occurred.
1854static TemplateName
1855SubstDefaultTemplateArgument(Sema &SemaRef,
1856 TemplateDecl *Template,
1857 SourceLocation TemplateLoc,
1858 SourceLocation RAngleLoc,
1859 TemplateTemplateParmDecl *Param,
1860 TemplateArgumentListBuilder &Converted) {
1861 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1862 /*TakeArgs=*/false);
1863
1864 MultiLevelTemplateArgumentList AllTemplateArgs
1865 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1866
1867 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1868 Template, Converted.getFlatArguments(),
1869 Converted.flatSize(),
1870 SourceRange(TemplateLoc, RAngleLoc));
1871
1872 return SemaRef.SubstTemplateName(
1873 Param->getDefaultArgument().getArgument().getAsTemplate(),
1874 Param->getDefaultArgument().getTemplateNameLoc(),
1875 AllTemplateArgs);
1876}
1877
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001878/// \brief If the given template parameter has a default template
1879/// argument, substitute into that default template argument and
1880/// return the corresponding template argument.
1881TemplateArgumentLoc
1882Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1883 SourceLocation TemplateLoc,
1884 SourceLocation RAngleLoc,
1885 Decl *Param,
1886 TemplateArgumentListBuilder &Converted) {
1887 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1888 if (!TypeParm->hasDefaultArgument())
1889 return TemplateArgumentLoc();
1890
1891 DeclaratorInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1892 TemplateLoc,
1893 RAngleLoc,
1894 TypeParm,
1895 Converted);
1896 if (DI)
1897 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1898
1899 return TemplateArgumentLoc();
1900 }
1901
1902 if (NonTypeTemplateParmDecl *NonTypeParm
1903 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1904 if (!NonTypeParm->hasDefaultArgument())
1905 return TemplateArgumentLoc();
1906
1907 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1908 TemplateLoc,
1909 RAngleLoc,
1910 NonTypeParm,
1911 Converted);
1912 if (Arg.isInvalid())
1913 return TemplateArgumentLoc();
1914
1915 Expr *ArgE = Arg.takeAs<Expr>();
1916 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1917 }
1918
1919 TemplateTemplateParmDecl *TempTempParm
1920 = cast<TemplateTemplateParmDecl>(Param);
1921 if (!TempTempParm->hasDefaultArgument())
1922 return TemplateArgumentLoc();
1923
1924 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1925 TemplateLoc,
1926 RAngleLoc,
1927 TempTempParm,
1928 Converted);
1929 if (TName.isNull())
1930 return TemplateArgumentLoc();
1931
1932 return TemplateArgumentLoc(TemplateArgument(TName),
1933 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1934 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1935}
1936
Douglas Gregorda0fb532009-11-11 19:31:23 +00001937/// \brief Check that the given template argument corresponds to the given
1938/// template parameter.
1939bool Sema::CheckTemplateArgument(NamedDecl *Param,
1940 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001941 TemplateDecl *Template,
1942 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001943 SourceLocation RAngleLoc,
1944 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001945 // Check template type parameters.
1946 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001947 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001948
Douglas Gregoreebed722009-11-11 19:41:09 +00001949 // Check non-type template parameters.
1950 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001951 // Do substitution on the type of the non-type template parameter
1952 // with the template arguments we've seen thus far.
1953 QualType NTTPType = NTTP->getType();
1954 if (NTTPType->isDependentType()) {
1955 // Do substitution on the type of the non-type template parameter.
1956 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1957 NTTP, Converted.getFlatArguments(),
1958 Converted.flatSize(),
1959 SourceRange(TemplateLoc, RAngleLoc));
1960
1961 TemplateArgumentList TemplateArgs(Context, Converted,
1962 /*TakeArgs=*/false);
1963 NTTPType = SubstType(NTTPType,
1964 MultiLevelTemplateArgumentList(TemplateArgs),
1965 NTTP->getLocation(),
1966 NTTP->getDeclName());
1967 // If that worked, check the non-type template parameter type
1968 // for validity.
1969 if (!NTTPType.isNull())
1970 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1971 NTTP->getLocation());
1972 if (NTTPType.isNull())
1973 return true;
1974 }
1975
1976 switch (Arg.getArgument().getKind()) {
1977 case TemplateArgument::Null:
1978 assert(false && "Should never see a NULL template argument here");
1979 return true;
1980
1981 case TemplateArgument::Expression: {
1982 Expr *E = Arg.getArgument().getAsExpr();
1983 TemplateArgument Result;
1984 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1985 return true;
1986
1987 Converted.Append(Result);
1988 break;
1989 }
1990
1991 case TemplateArgument::Declaration:
1992 case TemplateArgument::Integral:
1993 // We've already checked this template argument, so just copy
1994 // it to the list of converted arguments.
1995 Converted.Append(Arg.getArgument());
1996 break;
1997
1998 case TemplateArgument::Template:
1999 // We were given a template template argument. It may not be ill-formed;
2000 // see below.
2001 if (DependentTemplateName *DTN
2002 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2003 // We have a template argument such as \c T::template X, which we
2004 // parsed as a template template argument. However, since we now
2005 // know that we need a non-type template argument, convert this
2006 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00002007 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2008 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002009 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002010 DTN->getIdentifier(),
2011 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002012
2013 TemplateArgument Result;
2014 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2015 return true;
2016
2017 Converted.Append(Result);
2018 break;
2019 }
2020
2021 // We have a template argument that actually does refer to a class
2022 // template, template alias, or template template parameter, and
2023 // therefore cannot be a non-type template argument.
2024 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2025 << Arg.getSourceRange();
2026
2027 Diag(Param->getLocation(), diag::note_template_param_here);
2028 return true;
2029
2030 case TemplateArgument::Type: {
2031 // We have a non-type template parameter but the template
2032 // argument is a type.
2033
2034 // C++ [temp.arg]p2:
2035 // In a template-argument, an ambiguity between a type-id and
2036 // an expression is resolved to a type-id, regardless of the
2037 // form of the corresponding template-parameter.
2038 //
2039 // We warn specifically about this case, since it can be rather
2040 // confusing for users.
2041 QualType T = Arg.getArgument().getAsType();
2042 SourceRange SR = Arg.getSourceRange();
2043 if (T->isFunctionType())
2044 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2045 else
2046 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2047 Diag(Param->getLocation(), diag::note_template_param_here);
2048 return true;
2049 }
2050
2051 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00002052 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002053 break;
2054 }
2055
2056 return false;
2057 }
2058
2059
2060 // Check template template parameters.
2061 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2062
2063 // Substitute into the template parameter list of the template
2064 // template parameter, since previously-supplied template arguments
2065 // may appear within the template template parameter.
2066 {
2067 // Set up a template instantiation context.
2068 LocalInstantiationScope Scope(*this);
2069 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2070 TempParm, Converted.getFlatArguments(),
2071 Converted.flatSize(),
2072 SourceRange(TemplateLoc, RAngleLoc));
2073
2074 TemplateArgumentList TemplateArgs(Context, Converted,
2075 /*TakeArgs=*/false);
2076 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2077 SubstDecl(TempParm, CurContext,
2078 MultiLevelTemplateArgumentList(TemplateArgs)));
2079 if (!TempParm)
2080 return true;
2081
2082 // FIXME: TempParam is leaked.
2083 }
2084
2085 switch (Arg.getArgument().getKind()) {
2086 case TemplateArgument::Null:
2087 assert(false && "Should never see a NULL template argument here");
2088 return true;
2089
2090 case TemplateArgument::Template:
2091 if (CheckTemplateArgument(TempParm, Arg))
2092 return true;
2093
2094 Converted.Append(Arg.getArgument());
2095 break;
2096
2097 case TemplateArgument::Expression:
2098 case TemplateArgument::Type:
2099 // We have a template template parameter but the template
2100 // argument does not refer to a template.
2101 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2102 return true;
2103
2104 case TemplateArgument::Declaration:
2105 llvm::llvm_unreachable(
2106 "Declaration argument with template template parameter");
2107 break;
2108 case TemplateArgument::Integral:
2109 llvm::llvm_unreachable(
2110 "Integral argument with template template parameter");
2111 break;
2112
2113 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00002114 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002115 break;
2116 }
2117
2118 return false;
2119}
2120
Douglas Gregord32e0282009-02-09 23:23:08 +00002121/// \brief Check that the given template argument list is well-formed
2122/// for specializing the given template.
2123bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2124 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002125 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002126 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002127 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002128 TemplateParameterList *Params = Template->getTemplateParameters();
2129 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002130 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002131 bool Invalid = false;
2132
John McCall6b51f282009-11-23 01:53:49 +00002133 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2134
Mike Stump11289f42009-09-09 15:08:12 +00002135 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002136 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002137
Anders Carlsson15201f12009-06-13 02:08:00 +00002138 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002139 (NumArgs < Params->getMinRequiredArguments() &&
2140 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002141 // FIXME: point at either the first arg beyond what we can handle,
2142 // or the '>', depending on whether we have too many or too few
2143 // arguments.
2144 SourceRange Range;
2145 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002146 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002147 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2148 << (NumArgs > NumParams)
2149 << (isa<ClassTemplateDecl>(Template)? 0 :
2150 isa<FunctionTemplateDecl>(Template)? 1 :
2151 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2152 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002153 Diag(Template->getLocation(), diag::note_template_decl_here)
2154 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002155 Invalid = true;
2156 }
Mike Stump11289f42009-09-09 15:08:12 +00002157
2158 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002159 // [...] The type and form of each template-argument specified in
2160 // a template-id shall match the type and form specified for the
2161 // corresponding parameter declared by the template in its
2162 // template-parameter-list.
2163 unsigned ArgIdx = 0;
2164 for (TemplateParameterList::iterator Param = Params->begin(),
2165 ParamEnd = Params->end();
2166 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002167 if (ArgIdx > NumArgs && PartialTemplateArgs)
2168 break;
Mike Stump11289f42009-09-09 15:08:12 +00002169
Douglas Gregoreebed722009-11-11 19:41:09 +00002170 // If we have a template parameter pack, check every remaining template
2171 // argument against that template parameter pack.
2172 if ((*Param)->isTemplateParameterPack()) {
2173 Converted.BeginPack();
2174 for (; ArgIdx < NumArgs; ++ArgIdx) {
2175 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2176 TemplateLoc, RAngleLoc, Converted)) {
2177 Invalid = true;
2178 break;
2179 }
2180 }
2181 Converted.EndPack();
2182 continue;
2183 }
2184
Douglas Gregor84d49a22009-11-11 21:54:23 +00002185 if (ArgIdx < NumArgs) {
2186 // Check the template argument we were given.
2187 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2188 TemplateLoc, RAngleLoc, Converted))
2189 return true;
2190
2191 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002192 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002193
Douglas Gregor84d49a22009-11-11 21:54:23 +00002194 // We have a default template argument that we will use.
2195 TemplateArgumentLoc Arg;
2196
2197 // Retrieve the default template argument from the template
2198 // parameter. For each kind of template parameter, we substitute the
2199 // template arguments provided thus far and any "outer" template arguments
2200 // (when the template parameter was part of a nested template) into
2201 // the default argument.
2202 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2203 if (!TTP->hasDefaultArgument()) {
2204 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2205 break;
2206 }
2207
2208 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
2209 Template,
2210 TemplateLoc,
2211 RAngleLoc,
2212 TTP,
2213 Converted);
2214 if (!ArgType)
2215 return true;
2216
2217 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2218 ArgType);
2219 } else if (NonTypeTemplateParmDecl *NTTP
2220 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2221 if (!NTTP->hasDefaultArgument()) {
2222 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2223 break;
2224 }
2225
2226 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2227 TemplateLoc,
2228 RAngleLoc,
2229 NTTP,
2230 Converted);
2231 if (E.isInvalid())
2232 return true;
2233
2234 Expr *Ex = E.takeAs<Expr>();
2235 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2236 } else {
2237 TemplateTemplateParmDecl *TempParm
2238 = cast<TemplateTemplateParmDecl>(*Param);
2239
2240 if (!TempParm->hasDefaultArgument()) {
2241 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2242 break;
2243 }
2244
2245 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2246 TemplateLoc,
2247 RAngleLoc,
2248 TempParm,
2249 Converted);
2250 if (Name.isNull())
2251 return true;
2252
2253 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2254 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2255 TempParm->getDefaultArgument().getTemplateNameLoc());
2256 }
2257
2258 // Introduce an instantiation record that describes where we are using
2259 // the default template argument.
2260 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2261 Converted.getFlatArguments(),
2262 Converted.flatSize(),
2263 SourceRange(TemplateLoc, RAngleLoc));
2264
2265 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002266 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002267 RAngleLoc, Converted))
2268 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002269 }
2270
2271 return Invalid;
2272}
2273
2274/// \brief Check a template argument against its corresponding
2275/// template type parameter.
2276///
2277/// This routine implements the semantics of C++ [temp.arg.type]. It
2278/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002279bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00002280 DeclaratorInfo *ArgInfo) {
2281 assert(ArgInfo && "invalid DeclaratorInfo");
2282 QualType Arg = ArgInfo->getType();
2283
Douglas Gregord32e0282009-02-09 23:23:08 +00002284 // C++ [temp.arg.type]p2:
2285 // A local type, a type with no linkage, an unnamed type or a type
2286 // compounded from any of these types shall not be used as a
2287 // template-argument for a template type-parameter.
2288 //
2289 // FIXME: Perform the recursive and no-linkage type checks.
2290 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002291 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002292 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002293 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002294 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002295 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2296 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2297 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2298 << QualType(Tag, 0) << SR;
2299 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002300 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002301 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2302 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002303 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2304 return true;
2305 }
2306
2307 return false;
2308}
2309
Douglas Gregorccb07762009-02-11 19:52:55 +00002310/// \brief Checks whether the given template argument is the address
2311/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002312bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2313 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002314 bool Invalid = false;
2315
2316 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002317 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002318 Arg = Cast->getSubExpr();
2319
Sebastian Redl576fd422009-05-10 18:38:11 +00002320 // C++0x allows nullptr, and there's no further checking to be done for that.
2321 if (Arg->getType()->isNullPtrType())
2322 return false;
2323
Douglas Gregorccb07762009-02-11 19:52:55 +00002324 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002325 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002326 // A template-argument for a non-type, non-template
2327 // template-parameter shall be one of: [...]
2328 //
2329 // -- the address of an object or function with external
2330 // linkage, including function templates and function
2331 // template-ids but excluding non-static class members,
2332 // expressed as & id-expression where the & is optional if
2333 // the name refers to a function or array, or if the
2334 // corresponding template-parameter is a reference; or
2335 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002336
Douglas Gregorccb07762009-02-11 19:52:55 +00002337 // Ignore (and complain about) any excess parentheses.
2338 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2339 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002340 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002341 diag::err_template_arg_extra_parens)
2342 << Arg->getSourceRange();
2343 Invalid = true;
2344 }
2345
2346 Arg = Parens->getSubExpr();
2347 }
2348
2349 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2350 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2351 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2352 } else
2353 DRE = dyn_cast<DeclRefExpr>(Arg);
2354
2355 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002356 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002357 diag::err_template_arg_not_object_or_func_form)
2358 << Arg->getSourceRange();
2359
2360 // Cannot refer to non-static data members
2361 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2362 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2363 << Field << Arg->getSourceRange();
2364
2365 // Cannot refer to non-static member functions
2366 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2367 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002368 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002369 diag::err_template_arg_method)
2370 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002371
Douglas Gregorccb07762009-02-11 19:52:55 +00002372 // Functions must have external linkage.
2373 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002374 if (Func->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002375 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002376 diag::err_template_arg_function_not_extern)
2377 << Func << Arg->getSourceRange();
2378 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2379 << true;
2380 return true;
2381 }
2382
2383 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002384 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002385 return Invalid;
2386 }
2387
2388 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregorf73b2822009-11-25 22:24:25 +00002389 if (Var->getLinkage() != NamedDecl::ExternalLinkage) {
Mike Stump11289f42009-09-09 15:08:12 +00002390 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002391 diag::err_template_arg_object_not_extern)
2392 << Var << Arg->getSourceRange();
2393 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2394 << true;
2395 return true;
2396 }
2397
2398 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002399 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002400 return Invalid;
2401 }
Mike Stump11289f42009-09-09 15:08:12 +00002402
Douglas Gregorccb07762009-02-11 19:52:55 +00002403 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002404 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002405 diag::err_template_arg_not_object_or_func)
2406 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002407 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002408 diag::note_template_arg_refers_here);
2409 return true;
2410}
2411
2412/// \brief Checks whether the given template argument is a pointer to
2413/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002414bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2415 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002416 bool Invalid = false;
2417
2418 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002419 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002420 Arg = Cast->getSubExpr();
2421
Sebastian Redl576fd422009-05-10 18:38:11 +00002422 // C++0x allows nullptr, and there's no further checking to be done for that.
2423 if (Arg->getType()->isNullPtrType())
2424 return false;
2425
Douglas Gregorccb07762009-02-11 19:52:55 +00002426 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002427 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002428 // A template-argument for a non-type, non-template
2429 // template-parameter shall be one of: [...]
2430 //
2431 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002432 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002433
2434 // Ignore (and complain about) any excess parentheses.
2435 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2436 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002437 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002438 diag::err_template_arg_extra_parens)
2439 << Arg->getSourceRange();
2440 Invalid = true;
2441 }
2442
2443 Arg = Parens->getSubExpr();
2444 }
2445
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002446 // A pointer-to-member constant written &Class::member.
2447 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002448 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2449 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2450 if (DRE && !DRE->getQualifier())
2451 DRE = 0;
2452 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002453 }
2454 // A constant of pointer-to-member type.
2455 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2456 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2457 if (VD->getType()->isMemberPointerType()) {
2458 if (isa<NonTypeTemplateParmDecl>(VD) ||
2459 (isa<VarDecl>(VD) &&
2460 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2461 if (Arg->isTypeDependent() || Arg->isValueDependent())
2462 Converted = TemplateArgument(Arg->Retain());
2463 else
2464 Converted = TemplateArgument(VD->getCanonicalDecl());
2465 return Invalid;
2466 }
2467 }
2468 }
2469
2470 DRE = 0;
2471 }
2472
Douglas Gregorccb07762009-02-11 19:52:55 +00002473 if (!DRE)
2474 return Diag(Arg->getSourceRange().getBegin(),
2475 diag::err_template_arg_not_pointer_to_member_form)
2476 << Arg->getSourceRange();
2477
2478 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2479 assert((isa<FieldDecl>(DRE->getDecl()) ||
2480 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2481 "Only non-static member pointers can make it here");
2482
2483 // Okay: this is the address of a non-static member, and therefore
2484 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002485 if (Arg->isTypeDependent() || Arg->isValueDependent())
2486 Converted = TemplateArgument(Arg->Retain());
2487 else
2488 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002489 return Invalid;
2490 }
2491
2492 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002493 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002494 diag::err_template_arg_not_pointer_to_member_form)
2495 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002496 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002497 diag::note_template_arg_refers_here);
2498 return true;
2499}
2500
Douglas Gregord32e0282009-02-09 23:23:08 +00002501/// \brief Check a template argument against its corresponding
2502/// non-type template parameter.
2503///
Douglas Gregor463421d2009-03-03 04:44:36 +00002504/// This routine implements the semantics of C++ [temp.arg.nontype].
2505/// It returns true if an error occurred, and false otherwise. \p
2506/// InstantiatedParamType is the type of the non-type template
2507/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002508///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002509/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002510bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002511 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002512 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002513 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2514
Douglas Gregor86560402009-02-10 23:36:10 +00002515 // If either the parameter has a dependent type or the argument is
2516 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002517 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002518 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2519 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002520 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002521 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002522 }
Douglas Gregor86560402009-02-10 23:36:10 +00002523
2524 // C++ [temp.arg.nontype]p5:
2525 // The following conversions are performed on each expression used
2526 // as a non-type template-argument. If a non-type
2527 // template-argument cannot be converted to the type of the
2528 // corresponding template-parameter then the program is
2529 // ill-formed.
2530 //
2531 // -- for a non-type template-parameter of integral or
2532 // enumeration type, integral promotions (4.5) and integral
2533 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002534 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002535 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002536 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002537 // C++ [temp.arg.nontype]p1:
2538 // A template-argument for a non-type, non-template
2539 // template-parameter shall be one of:
2540 //
2541 // -- an integral constant-expression of integral or enumeration
2542 // type; or
2543 // -- the name of a non-type template-parameter; or
2544 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002545 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002546 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002547 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002548 diag::err_template_arg_not_integral_or_enumeral)
2549 << ArgType << Arg->getSourceRange();
2550 Diag(Param->getLocation(), diag::note_template_param_here);
2551 return true;
2552 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002553 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002554 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2555 << ArgType << Arg->getSourceRange();
2556 return true;
2557 }
2558
2559 // FIXME: We need some way to more easily get the unqualified form
2560 // of the types without going all the way to the
2561 // canonical type.
2562 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2563 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2564 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2565 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2566
2567 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002568 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002569 // Okay: no conversion necessary
2570 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2571 !ParamType->isEnumeralType()) {
2572 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002573 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002574 } else {
2575 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002576 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002577 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002578 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002579 Diag(Param->getLocation(), diag::note_template_param_here);
2580 return true;
2581 }
2582
Douglas Gregor52aba872009-03-14 00:20:21 +00002583 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002584 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002585 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002586
2587 if (!Arg->isValueDependent()) {
2588 // Check that an unsigned parameter does not receive a negative
2589 // value.
2590 if (IntegerType->isUnsignedIntegerType()
2591 && (Value.isSigned() && Value.isNegative())) {
2592 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2593 << Value.toString(10) << Param->getType()
2594 << Arg->getSourceRange();
2595 Diag(Param->getLocation(), diag::note_template_param_here);
2596 return true;
2597 }
2598
2599 // Check that we don't overflow the template parameter type.
2600 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2601 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002602 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002603 diag::err_template_arg_too_large)
2604 << Value.toString(10) << Param->getType()
2605 << Arg->getSourceRange();
2606 Diag(Param->getLocation(), diag::note_template_param_here);
2607 return true;
2608 }
2609
2610 if (Value.getBitWidth() != AllowedBits)
2611 Value.extOrTrunc(AllowedBits);
2612 Value.setIsSigned(IntegerType->isSignedIntegerType());
2613 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002614
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002615 // Add the value of this argument to the list of converted
2616 // arguments. We use the bitwidth and signedness of the template
2617 // parameter.
2618 if (Arg->isValueDependent()) {
2619 // The argument is value-dependent. Create a new
2620 // TemplateArgument with the converted expression.
2621 Converted = TemplateArgument(Arg);
2622 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002623 }
2624
John McCall0ad16662009-10-29 08:12:44 +00002625 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002626 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002627 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002628 return false;
2629 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002630
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002631 // Handle pointer-to-function, reference-to-function, and
2632 // pointer-to-member-function all in (roughly) the same way.
2633 if (// -- For a non-type template-parameter of type pointer to
2634 // function, only the function-to-pointer conversion (4.3) is
2635 // applied. If the template-argument represents a set of
2636 // overloaded functions (or a pointer to such), the matching
2637 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002638 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002639 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002640 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002641 // -- For a non-type template-parameter of type reference to
2642 // function, no conversions apply. If the template-argument
2643 // represents a set of overloaded functions, the matching
2644 // function is selected from the set (13.4).
2645 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002646 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002647 // -- For a non-type template-parameter of type pointer to
2648 // member function, no conversions apply. If the
2649 // template-argument represents a set of overloaded member
2650 // functions, the matching member function is selected from
2651 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002652 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002653 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002654 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002655 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002656 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002657 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002658 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002659 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2660 ParamType->isMemberPointerType())) {
2661 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002662 if (ParamType->isMemberPointerType())
2663 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2664 else
2665 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002666 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002667 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002668 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002669 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002670 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002671 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2672 return true;
2673
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002674 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002675 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002676 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002677 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002678 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002679 }
2680 }
2681
Mike Stump11289f42009-09-09 15:08:12 +00002682 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002683 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002684 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002685 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002686 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002687 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002688 Diag(Param->getLocation(), diag::note_template_param_here);
2689 return true;
2690 }
Mike Stump11289f42009-09-09 15:08:12 +00002691
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002692 if (ParamType->isMemberPointerType())
2693 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002694
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002695 NamedDecl *Entity = 0;
2696 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2697 return true;
2698
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002699 if (Entity)
2700 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002701 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002702 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002703 }
2704
Chris Lattner696197c2009-02-20 21:37:53 +00002705 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002706 // -- for a non-type template-parameter of type pointer to
2707 // object, qualification conversions (4.4) and the
2708 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002709 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002710 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002711 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002712
Sebastian Redl576fd422009-05-10 18:38:11 +00002713 if (ArgType->isNullPtrType()) {
2714 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002715 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002716 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002717 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002718 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002719 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002720
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002721 if (IsQualificationConversion(ArgType, ParamType)) {
2722 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002723 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002724 }
Mike Stump11289f42009-09-09 15:08:12 +00002725
Douglas Gregor1515f762009-02-11 18:22:40 +00002726 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002727 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002728 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002729 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002730 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002731 Diag(Param->getLocation(), diag::note_template_param_here);
2732 return true;
2733 }
Mike Stump11289f42009-09-09 15:08:12 +00002734
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002735 NamedDecl *Entity = 0;
2736 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2737 return true;
2738
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002739 if (Entity)
2740 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002741 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002742 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002743 }
Mike Stump11289f42009-09-09 15:08:12 +00002744
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002745 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002746 // -- For a non-type template-parameter of type reference to
2747 // object, no conversions apply. The type referred to by the
2748 // reference may be more cv-qualified than the (otherwise
2749 // identical) type of the template-argument. The
2750 // template-parameter is bound directly to the
2751 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002752 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002753 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002754
Douglas Gregor1515f762009-02-11 18:22:40 +00002755 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002756 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002757 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002758 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002759 << Arg->getSourceRange();
2760 Diag(Param->getLocation(), diag::note_template_param_here);
2761 return true;
2762 }
2763
Mike Stump11289f42009-09-09 15:08:12 +00002764 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002765 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2766 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002767
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002768 if ((ParamQuals | ArgQuals) != ParamQuals) {
2769 Diag(Arg->getSourceRange().getBegin(),
2770 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002771 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002772 << Arg->getSourceRange();
2773 Diag(Param->getLocation(), diag::note_template_param_here);
2774 return true;
2775 }
Mike Stump11289f42009-09-09 15:08:12 +00002776
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002777 NamedDecl *Entity = 0;
2778 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2779 return true;
2780
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002781 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002782 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002783 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002784 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002785
2786 // -- For a non-type template-parameter of type pointer to data
2787 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002788 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002789 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2790
Douglas Gregor1515f762009-02-11 18:22:40 +00002791 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002792 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002793 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002794 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002795 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002796 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002797 } else {
2798 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002799 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002800 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002801 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002802 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002803 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002804 }
2805
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002806 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002807}
2808
2809/// \brief Check a template argument against its corresponding
2810/// template template parameter.
2811///
2812/// This routine implements the semantics of C++ [temp.arg.template].
2813/// It returns true if an error occurred, and false otherwise.
2814bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002815 const TemplateArgumentLoc &Arg) {
2816 TemplateName Name = Arg.getArgument().getAsTemplate();
2817 TemplateDecl *Template = Name.getAsTemplateDecl();
2818 if (!Template) {
2819 // Any dependent template name is fine.
2820 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2821 return false;
2822 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002823
2824 // C++ [temp.arg.template]p1:
2825 // A template-argument for a template template-parameter shall be
2826 // the name of a class template, expressed as id-expression. Only
2827 // primary class templates are considered when matching the
2828 // template template argument with the corresponding parameter;
2829 // partial specializations are not considered even if their
2830 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002831 //
2832 // Note that we also allow template template parameters here, which
2833 // will happen when we are dealing with, e.g., class template
2834 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002835 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002836 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002837 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002838 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002839 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002840 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002841 << Template;
2842 }
2843
2844 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2845 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002846 true,
2847 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002848 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002849}
2850
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002851/// \brief Determine whether the given template parameter lists are
2852/// equivalent.
2853///
Mike Stump11289f42009-09-09 15:08:12 +00002854/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002855/// source code as part of a new template declaration.
2856///
2857/// \param Old The old template parameter list, typically found via
2858/// name lookup of the template declared with this template parameter
2859/// list.
2860///
2861/// \param Complain If true, this routine will produce a diagnostic if
2862/// the template parameter lists are not equivalent.
2863///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002864/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002865///
2866/// \param TemplateArgLoc If this source location is valid, then we
2867/// are actually checking the template parameter list of a template
2868/// argument (New) against the template parameter list of its
2869/// corresponding template template parameter (Old). We produce
2870/// slightly different diagnostics in this scenario.
2871///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002872/// \returns True if the template parameter lists are equal, false
2873/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002874bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002875Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2876 TemplateParameterList *Old,
2877 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002878 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002879 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002880 if (Old->size() != New->size()) {
2881 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002882 unsigned NextDiag = diag::err_template_param_list_different_arity;
2883 if (TemplateArgLoc.isValid()) {
2884 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2885 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002886 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002887 Diag(New->getTemplateLoc(), NextDiag)
2888 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002889 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002890 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002891 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002892 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002893 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2894 }
2895
2896 return false;
2897 }
2898
2899 for (TemplateParameterList::iterator OldParm = Old->begin(),
2900 OldParmEnd = Old->end(), NewParm = New->begin();
2901 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2902 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002903 if (Complain) {
2904 unsigned NextDiag = diag::err_template_param_different_kind;
2905 if (TemplateArgLoc.isValid()) {
2906 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2907 NextDiag = diag::note_template_param_different_kind;
2908 }
2909 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002910 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002911 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002912 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002913 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002914 return false;
2915 }
2916
2917 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2918 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002919 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002920 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002921 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2922 // The types of non-type template parameters must agree.
2923 NonTypeTemplateParmDecl *NewNTTP
2924 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002925
2926 // If we are matching a template template argument to a template
2927 // template parameter and one of the non-type template parameter types
2928 // is dependent, then we must wait until template instantiation time
2929 // to actually compare the arguments.
2930 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2931 (OldNTTP->getType()->isDependentType() ||
2932 NewNTTP->getType()->isDependentType()))
2933 continue;
2934
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002935 if (Context.getCanonicalType(OldNTTP->getType()) !=
2936 Context.getCanonicalType(NewNTTP->getType())) {
2937 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002938 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2939 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002940 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002941 diag::err_template_arg_template_params_mismatch);
2942 NextDiag = diag::note_template_nontype_parm_different_type;
2943 }
2944 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002945 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002946 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002947 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002948 diag::note_template_nontype_parm_prev_declaration)
2949 << OldNTTP->getType();
2950 }
2951 return false;
2952 }
2953 } else {
2954 // The template parameter lists of template template
2955 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002956 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002957 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002958 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002959 = cast<TemplateTemplateParmDecl>(*OldParm);
2960 TemplateTemplateParmDecl *NewTTP
2961 = cast<TemplateTemplateParmDecl>(*NewParm);
2962 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2963 OldTTP->getTemplateParameters(),
2964 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002965 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002966 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002967 return false;
2968 }
2969 }
2970
2971 return true;
2972}
2973
2974/// \brief Check whether a template can be declared within this scope.
2975///
2976/// If the template declaration is valid in this scope, returns
2977/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002978bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002979Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002980 // Find the nearest enclosing declaration scope.
2981 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2982 (S->getFlags() & Scope::TemplateParamScope) != 0)
2983 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002984
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002985 // C++ [temp]p2:
2986 // A template-declaration can appear only as a namespace scope or
2987 // class scope declaration.
2988 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002989 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2990 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002991 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002992 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002993
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002994 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002995 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002996
2997 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2998 return false;
2999
Mike Stump11289f42009-09-09 15:08:12 +00003000 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003001 diag::err_template_outside_namespace_or_class_scope)
3002 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003003}
Douglas Gregor67a65642009-02-17 23:15:12 +00003004
Douglas Gregor54888652009-10-07 00:13:32 +00003005/// \brief Determine what kind of template specialization the given declaration
3006/// is.
3007static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3008 if (!D)
3009 return TSK_Undeclared;
3010
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003011 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3012 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003013 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3014 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003015 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3016 return Var->getTemplateSpecializationKind();
3017
Douglas Gregor54888652009-10-07 00:13:32 +00003018 return TSK_Undeclared;
3019}
3020
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003021/// \brief Check whether a specialization is well-formed in the current
3022/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003023///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003024/// This routine determines whether a template specialization can be declared
3025/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003026///
3027/// \param S the semantic analysis object for which this check is being
3028/// performed.
3029///
3030/// \param Specialized the entity being specialized or instantiated, which
3031/// may be a kind of template (class template, function template, etc.) or
3032/// a member of a class template (member function, static data member,
3033/// member class).
3034///
3035/// \param PrevDecl the previous declaration of this entity, if any.
3036///
3037/// \param Loc the location of the explicit specialization or instantiation of
3038/// this entity.
3039///
3040/// \param IsPartialSpecialization whether this is a partial specialization of
3041/// a class template.
3042///
Douglas Gregor54888652009-10-07 00:13:32 +00003043/// \returns true if there was an error that we cannot recover from, false
3044/// otherwise.
3045static bool CheckTemplateSpecializationScope(Sema &S,
3046 NamedDecl *Specialized,
3047 NamedDecl *PrevDecl,
3048 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003049 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003050 // Keep these "kind" numbers in sync with the %select statements in the
3051 // various diagnostics emitted by this routine.
3052 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003053 bool isTemplateSpecialization = false;
3054 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003055 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003056 isTemplateSpecialization = true;
3057 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003058 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003059 isTemplateSpecialization = true;
3060 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003061 EntityKind = 3;
3062 else if (isa<VarDecl>(Specialized))
3063 EntityKind = 4;
3064 else if (isa<RecordDecl>(Specialized))
3065 EntityKind = 5;
3066 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003067 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3068 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003069 return true;
3070 }
3071
Douglas Gregorf47b9112009-02-25 22:02:03 +00003072 // C++ [temp.expl.spec]p2:
3073 // An explicit specialization shall be declared in the namespace
3074 // of which the template is a member, or, for member templates, in
3075 // the namespace of which the enclosing class or enclosing class
3076 // template is a member. An explicit specialization of a member
3077 // function, member class or static data member of a class
3078 // template shall be declared in the namespace of which the class
3079 // template is a member. Such a declaration may also be a
3080 // definition. If the declaration is not a definition, the
3081 // specialization may be defined later in the name- space in which
3082 // the explicit specialization was declared, or in a namespace
3083 // that encloses the one in which the explicit specialization was
3084 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003085 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3086 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003087 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003088 return true;
3089 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003090
Douglas Gregor40fb7442009-10-07 17:30:37 +00003091 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3092 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003093 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003094 return true;
3095 }
3096
Douglas Gregore4b05162009-10-07 17:21:34 +00003097 // C++ [temp.class.spec]p6:
3098 // A class template partial specialization may be declared or redeclared
3099 // in any namespace scope in which its definition may be defined (14.5.1
3100 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003101 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003102 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003103 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003104 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003105 if ((!PrevDecl ||
3106 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3107 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3108 // There is no prior declaration of this entity, so this
3109 // specialization must be in the same context as the template
3110 // itself.
3111 if (!DC->Equals(SpecializedContext)) {
3112 if (isa<TranslationUnitDecl>(SpecializedContext))
3113 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3114 << EntityKind << Specialized;
3115 else if (isa<NamespaceDecl>(SpecializedContext))
3116 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3117 << EntityKind << Specialized
3118 << cast<NamedDecl>(SpecializedContext);
3119
3120 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3121 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003122 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003123 }
Douglas Gregor54888652009-10-07 00:13:32 +00003124
3125 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003126 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003127 // Note that HandleDeclarator() performs this check for explicit
3128 // specializations of function templates, static data members, and member
3129 // functions, so we skip the check here for those kinds of entities.
3130 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003131 // Should we refactor that check, so that it occurs later?
3132 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003133 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3134 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003135 if (isa<TranslationUnitDecl>(SpecializedContext))
3136 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3137 << EntityKind << Specialized;
3138 else if (isa<NamespaceDecl>(SpecializedContext))
3139 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3140 << EntityKind << Specialized
3141 << cast<NamedDecl>(SpecializedContext);
3142
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003143 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003144 }
Douglas Gregor54888652009-10-07 00:13:32 +00003145
3146 // FIXME: check for specialization-after-instantiation errors and such.
3147
Douglas Gregorf47b9112009-02-25 22:02:03 +00003148 return false;
3149}
Douglas Gregor54888652009-10-07 00:13:32 +00003150
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003151/// \brief Check the non-type template arguments of a class template
3152/// partial specialization according to C++ [temp.class.spec]p9.
3153///
Douglas Gregor09a30232009-06-12 22:08:06 +00003154/// \param TemplateParams the template parameters of the primary class
3155/// template.
3156///
3157/// \param TemplateArg the template arguments of the class template
3158/// partial specialization.
3159///
3160/// \param MirrorsPrimaryTemplate will be set true if the class
3161/// template partial specialization arguments are identical to the
3162/// implicit template arguments of the primary template. This is not
3163/// necessarily an error (C++0x), and it is left to the caller to diagnose
3164/// this condition when it is an error.
3165///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003166/// \returns true if there was an error, false otherwise.
3167bool Sema::CheckClassTemplatePartialSpecializationArgs(
3168 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003169 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003170 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003171 // FIXME: the interface to this function will have to change to
3172 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003173 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003174
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003175 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003176
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003177 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003178 // Determine whether the template argument list of the partial
3179 // specialization is identical to the implicit argument list of
3180 // the primary template. The caller may need to diagnostic this as
3181 // an error per C++ [temp.class.spec]p9b3.
3182 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003183 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003184 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3185 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003186 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003187 MirrorsPrimaryTemplate = false;
3188 } else if (TemplateTemplateParmDecl *TTP
3189 = dyn_cast<TemplateTemplateParmDecl>(
3190 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003191 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003192 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003193 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003194 if (!ArgDecl ||
3195 ArgDecl->getIndex() != TTP->getIndex() ||
3196 ArgDecl->getDepth() != TTP->getDepth())
3197 MirrorsPrimaryTemplate = false;
3198 }
3199 }
3200
Mike Stump11289f42009-09-09 15:08:12 +00003201 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003202 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003203 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003204 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003205 }
3206
Anders Carlsson40c1d492009-06-13 18:20:51 +00003207 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003208 if (!ArgExpr) {
3209 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003210 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003211 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003212
3213 // C++ [temp.class.spec]p8:
3214 // A non-type argument is non-specialized if it is the name of a
3215 // non-type parameter. All other non-type arguments are
3216 // specialized.
3217 //
3218 // Below, we check the two conditions that only apply to
3219 // specialized non-type arguments, so skip any non-specialized
3220 // arguments.
3221 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003222 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003223 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003224 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003225 (Param->getIndex() != NTTP->getIndex() ||
3226 Param->getDepth() != NTTP->getDepth()))
3227 MirrorsPrimaryTemplate = false;
3228
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003229 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003230 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003231
3232 // C++ [temp.class.spec]p9:
3233 // Within the argument list of a class template partial
3234 // specialization, the following restrictions apply:
3235 // -- A partially specialized non-type argument expression
3236 // shall not involve a template parameter of the partial
3237 // specialization except when the argument expression is a
3238 // simple identifier.
3239 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003240 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003241 diag::err_dependent_non_type_arg_in_partial_spec)
3242 << ArgExpr->getSourceRange();
3243 return true;
3244 }
3245
3246 // -- The type of a template parameter corresponding to a
3247 // specialized non-type argument shall not be dependent on a
3248 // parameter of the specialization.
3249 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003250 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003251 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3252 << Param->getType()
3253 << ArgExpr->getSourceRange();
3254 Diag(Param->getLocation(), diag::note_template_param_here);
3255 return true;
3256 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003257
3258 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003259 }
3260
3261 return false;
3262}
3263
Douglas Gregorc08f4892009-03-25 00:13:59 +00003264Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003265Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3266 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003267 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003268 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003269 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003270 SourceLocation TemplateNameLoc,
3271 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003272 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003273 SourceLocation RAngleLoc,
3274 AttributeList *Attr,
3275 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003276 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003277
Douglas Gregor67a65642009-02-17 23:15:12 +00003278 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003279 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003280 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003281 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3282
3283 if (!ClassTemplate) {
3284 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3285 << (Name.getAsTemplateDecl() &&
3286 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3287 return true;
3288 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003289
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003290 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003291 bool isPartialSpecialization = false;
3292
Douglas Gregorf47b9112009-02-25 22:02:03 +00003293 // Check the validity of the template headers that introduce this
3294 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003295 // FIXME: We probably shouldn't complain about these headers for
3296 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003297 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003298 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3299 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003300 TemplateParameterLists.size(),
3301 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003302 if (TemplateParams && TemplateParams->size() > 0) {
3303 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003304
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003305 // C++ [temp.class.spec]p10:
3306 // The template parameter list of a specialization shall not
3307 // contain default template argument values.
3308 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3309 Decl *Param = TemplateParams->getParam(I);
3310 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3311 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003312 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003313 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003314 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003315 }
3316 } else if (NonTypeTemplateParmDecl *NTTP
3317 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3318 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003319 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003320 diag::err_default_arg_in_partial_spec)
3321 << DefArg->getSourceRange();
3322 NTTP->setDefaultArgument(0);
3323 DefArg->Destroy(Context);
3324 }
3325 } else {
3326 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003327 if (TTP->hasDefaultArgument()) {
3328 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003329 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003330 << TTP->getDefaultArgument().getSourceRange();
3331 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003332 }
3333 }
3334 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003335 } else if (TemplateParams) {
3336 if (TUK == TUK_Friend)
3337 Diag(KWLoc, diag::err_template_spec_friend)
3338 << CodeModificationHint::CreateRemoval(
3339 SourceRange(TemplateParams->getTemplateLoc(),
3340 TemplateParams->getRAngleLoc()))
3341 << SourceRange(LAngleLoc, RAngleLoc);
3342 else
3343 isExplicitSpecialization = true;
3344 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003345 Diag(KWLoc, diag::err_template_spec_needs_header)
3346 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003347 isExplicitSpecialization = true;
3348 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003349
Douglas Gregor67a65642009-02-17 23:15:12 +00003350 // Check that the specialization uses the same tag kind as the
3351 // original template.
3352 TagDecl::TagKind Kind;
3353 switch (TagSpec) {
3354 default: assert(0 && "Unknown tag type!");
3355 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3356 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3357 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3358 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003359 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003360 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003361 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003362 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003363 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003364 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003365 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003366 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003367 diag::note_previous_use);
3368 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3369 }
3370
Douglas Gregorc40290e2009-03-09 23:48:35 +00003371 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003372 TemplateArgumentListInfo TemplateArgs;
3373 TemplateArgs.setLAngleLoc(LAngleLoc);
3374 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003375 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003376
Douglas Gregor67a65642009-02-17 23:15:12 +00003377 // Check that the template argument list is well-formed for this
3378 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003379 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3380 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003381 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3382 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003383 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003384
Mike Stump11289f42009-09-09 15:08:12 +00003385 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003386 ClassTemplate->getTemplateParameters()->size()) &&
3387 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003388
Douglas Gregor2373c592009-05-31 09:31:02 +00003389 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003390 // corresponds to these arguments.
3391 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003392 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003393 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003394 if (CheckClassTemplatePartialSpecializationArgs(
3395 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003396 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003397 return true;
3398
Douglas Gregor09a30232009-06-12 22:08:06 +00003399 if (MirrorsPrimaryTemplate) {
3400 // C++ [temp.class.spec]p9b3:
3401 //
Mike Stump11289f42009-09-09 15:08:12 +00003402 // -- The argument list of the specialization shall not be identical
3403 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003404 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003405 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003406 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003407 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003408 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003409 ClassTemplate->getIdentifier(),
3410 TemplateNameLoc,
3411 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003412 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003413 AS_none);
3414 }
3415
Douglas Gregor2208a292009-09-26 20:57:03 +00003416 // FIXME: Diagnose friend partial specializations
3417
Douglas Gregor2373c592009-05-31 09:31:02 +00003418 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003419 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003420 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003421 Converted.flatSize(),
3422 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003423 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003424 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003425 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003426 Converted.flatSize(),
3427 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003428 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003429 ClassTemplateSpecializationDecl *PrevDecl = 0;
3430
3431 if (isPartialSpecialization)
3432 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003433 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003434 InsertPos);
3435 else
3436 PrevDecl
3437 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003438
3439 ClassTemplateSpecializationDecl *Specialization = 0;
3440
Douglas Gregorf47b9112009-02-25 22:02:03 +00003441 // Check whether we can declare a class template specialization in
3442 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003443 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003444 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003445 TemplateNameLoc,
3446 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003447 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003448
Douglas Gregor15301382009-07-30 17:40:51 +00003449 // The canonical type
3450 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003451 if (PrevDecl &&
3452 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3453 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003454 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003455 // arguments was referenced but not declared, or we're only
3456 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003457 // declaration node as our own, updating its source location to
3458 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003459 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003460 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003461 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003462 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003463 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003464 // Build the canonical type that describes the converted template
3465 // arguments of the class template partial specialization.
3466 CanonType = Context.getTemplateSpecializationType(
3467 TemplateName(ClassTemplate),
3468 Converted.getFlatArguments(),
3469 Converted.flatSize());
3470
Douglas Gregor2373c592009-05-31 09:31:02 +00003471 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003472 ClassTemplatePartialSpecializationDecl *PrevPartial
3473 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003474 ClassTemplatePartialSpecializationDecl *Partial
3475 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003476 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003477 TemplateNameLoc,
3478 TemplateParams,
3479 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003480 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003481 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003482 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003483
3484 if (PrevPartial) {
3485 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3486 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3487 } else {
3488 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3489 }
3490 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003491
Douglas Gregor21610382009-10-29 00:04:11 +00003492 // If we are providing an explicit specialization of a member class
3493 // template specialization, make a note of that.
3494 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3495 PrevPartial->setMemberSpecialization();
3496
Douglas Gregor91772d12009-06-13 00:26:55 +00003497 // Check that all of the template parameters of the class template
3498 // partial specialization are deducible from the template
3499 // arguments. If not, this class template partial specialization
3500 // will never be used.
3501 llvm::SmallVector<bool, 8> DeducibleParams;
3502 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003503 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003504 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003505 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003506 unsigned NumNonDeducible = 0;
3507 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3508 if (!DeducibleParams[I])
3509 ++NumNonDeducible;
3510
3511 if (NumNonDeducible) {
3512 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3513 << (NumNonDeducible > 1)
3514 << SourceRange(TemplateNameLoc, RAngleLoc);
3515 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3516 if (!DeducibleParams[I]) {
3517 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3518 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003519 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003520 diag::note_partial_spec_unused_parameter)
3521 << Param->getDeclName();
3522 else
Mike Stump11289f42009-09-09 15:08:12 +00003523 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003524 diag::note_partial_spec_unused_parameter)
3525 << std::string("<anonymous>");
3526 }
3527 }
3528 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003529 } else {
3530 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003531 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003532 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003533 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003534 ClassTemplate->getDeclContext(),
3535 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003536 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003537 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003538 PrevDecl);
3539
3540 if (PrevDecl) {
3541 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3542 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3543 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003544 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003545 InsertPos);
3546 }
Douglas Gregor15301382009-07-30 17:40:51 +00003547
3548 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003549 }
3550
Douglas Gregor06db9f52009-10-12 20:18:28 +00003551 // C++ [temp.expl.spec]p6:
3552 // If a template, a member template or the member of a class template is
3553 // explicitly specialized then that specialization shall be declared
3554 // before the first use of that specialization that would cause an implicit
3555 // instantiation to take place, in every translation unit in which such a
3556 // use occurs; no diagnostic is required.
3557 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3558 SourceRange Range(TemplateNameLoc, RAngleLoc);
3559 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3560 << Context.getTypeDeclType(Specialization) << Range;
3561
3562 Diag(PrevDecl->getPointOfInstantiation(),
3563 diag::note_instantiation_required_here)
3564 << (PrevDecl->getTemplateSpecializationKind()
3565 != TSK_ImplicitInstantiation);
3566 return true;
3567 }
3568
Douglas Gregor2208a292009-09-26 20:57:03 +00003569 // If this is not a friend, note that this is an explicit specialization.
3570 if (TUK != TUK_Friend)
3571 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003572
3573 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003574 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003575 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003576 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003577 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003578 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003579 Diag(Def->getLocation(), diag::note_previous_definition);
3580 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003581 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003582 }
3583 }
3584
Douglas Gregord56a91e2009-02-26 22:19:44 +00003585 // Build the fully-sugared type for this class template
3586 // specialization as the user wrote in the specialization
3587 // itself. This means that we'll pretty-print the type retrieved
3588 // from the specialization's declaration the way that the user
3589 // actually wrote the specialization, rather than formatting the
3590 // name based on the "canonical" representation used to store the
3591 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003592 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003593 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003594 if (TUK != TUK_Friend)
3595 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003596 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003597
Douglas Gregor1e249f82009-02-25 22:18:32 +00003598 // C++ [temp.expl.spec]p9:
3599 // A template explicit specialization is in the scope of the
3600 // namespace in which the template was defined.
3601 //
3602 // We actually implement this paragraph where we set the semantic
3603 // context (in the creation of the ClassTemplateSpecializationDecl),
3604 // but we also maintain the lexical context where the actual
3605 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003606 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003607
Douglas Gregor67a65642009-02-17 23:15:12 +00003608 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003609 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003610 Specialization->startDefinition();
3611
Douglas Gregor2208a292009-09-26 20:57:03 +00003612 if (TUK == TUK_Friend) {
3613 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3614 TemplateNameLoc,
3615 WrittenTy.getTypePtr(),
3616 /*FIXME:*/KWLoc);
3617 Friend->setAccess(AS_public);
3618 CurContext->addDecl(Friend);
3619 } else {
3620 // Add the specialization into its lexical context, so that it can
3621 // be seen when iterating through the list of declarations in that
3622 // context. However, specializations are not found by name lookup.
3623 CurContext->addDecl(Specialization);
3624 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003625 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003626}
Douglas Gregor333489b2009-03-27 23:10:48 +00003627
Mike Stump11289f42009-09-09 15:08:12 +00003628Sema::DeclPtrTy
3629Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003630 MultiTemplateParamsArg TemplateParameterLists,
3631 Declarator &D) {
3632 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3633}
3634
Mike Stump11289f42009-09-09 15:08:12 +00003635Sema::DeclPtrTy
3636Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003637 MultiTemplateParamsArg TemplateParameterLists,
3638 Declarator &D) {
3639 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3640 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3641 "Not a function declarator!");
3642 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003643
Douglas Gregor17a7c122009-06-24 00:54:41 +00003644 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003645 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003646 }
Mike Stump11289f42009-09-09 15:08:12 +00003647
Douglas Gregor17a7c122009-06-24 00:54:41 +00003648 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003649
3650 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003651 move(TemplateParameterLists),
3652 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003653 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003654 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003655 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003656 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003657 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3658 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003659 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003660}
3661
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003662/// \brief Diagnose cases where we have an explicit template specialization
3663/// before/after an explicit template instantiation, producing diagnostics
3664/// for those cases where they are required and determining whether the
3665/// new specialization/instantiation will have any effect.
3666///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003667/// \param NewLoc the location of the new explicit specialization or
3668/// instantiation.
3669///
3670/// \param NewTSK the kind of the new explicit specialization or instantiation.
3671///
3672/// \param PrevDecl the previous declaration of the entity.
3673///
3674/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3675///
3676/// \param PrevPointOfInstantiation if valid, indicates where the previus
3677/// declaration was instantiated (either implicitly or explicitly).
3678///
3679/// \param SuppressNew will be set to true to indicate that the new
3680/// specialization or instantiation has no effect and should be ignored.
3681///
3682/// \returns true if there was an error that should prevent the introduction of
3683/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003684bool
3685Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3686 TemplateSpecializationKind NewTSK,
3687 NamedDecl *PrevDecl,
3688 TemplateSpecializationKind PrevTSK,
3689 SourceLocation PrevPointOfInstantiation,
3690 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003691 SuppressNew = false;
3692
3693 switch (NewTSK) {
3694 case TSK_Undeclared:
3695 case TSK_ImplicitInstantiation:
3696 assert(false && "Don't check implicit instantiations here");
3697 return false;
3698
3699 case TSK_ExplicitSpecialization:
3700 switch (PrevTSK) {
3701 case TSK_Undeclared:
3702 case TSK_ExplicitSpecialization:
3703 // Okay, we're just specializing something that is either already
3704 // explicitly specialized or has merely been mentioned without any
3705 // instantiation.
3706 return false;
3707
3708 case TSK_ImplicitInstantiation:
3709 if (PrevPointOfInstantiation.isInvalid()) {
3710 // The declaration itself has not actually been instantiated, so it is
3711 // still okay to specialize it.
3712 return false;
3713 }
3714 // Fall through
3715
3716 case TSK_ExplicitInstantiationDeclaration:
3717 case TSK_ExplicitInstantiationDefinition:
3718 assert((PrevTSK == TSK_ImplicitInstantiation ||
3719 PrevPointOfInstantiation.isValid()) &&
3720 "Explicit instantiation without point of instantiation?");
3721
3722 // C++ [temp.expl.spec]p6:
3723 // If a template, a member template or the member of a class template
3724 // is explicitly specialized then that specialization shall be declared
3725 // before the first use of that specialization that would cause an
3726 // implicit instantiation to take place, in every translation unit in
3727 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003728 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003729 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003730 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003731 << (PrevTSK != TSK_ImplicitInstantiation);
3732
3733 return true;
3734 }
3735 break;
3736
3737 case TSK_ExplicitInstantiationDeclaration:
3738 switch (PrevTSK) {
3739 case TSK_ExplicitInstantiationDeclaration:
3740 // This explicit instantiation declaration is redundant (that's okay).
3741 SuppressNew = true;
3742 return false;
3743
3744 case TSK_Undeclared:
3745 case TSK_ImplicitInstantiation:
3746 // We're explicitly instantiating something that may have already been
3747 // implicitly instantiated; that's fine.
3748 return false;
3749
3750 case TSK_ExplicitSpecialization:
3751 // C++0x [temp.explicit]p4:
3752 // For a given set of template parameters, if an explicit instantiation
3753 // of a template appears after a declaration of an explicit
3754 // specialization for that template, the explicit instantiation has no
3755 // effect.
3756 return false;
3757
3758 case TSK_ExplicitInstantiationDefinition:
3759 // C++0x [temp.explicit]p10:
3760 // If an entity is the subject of both an explicit instantiation
3761 // declaration and an explicit instantiation definition in the same
3762 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003763 Diag(NewLoc,
3764 diag::err_explicit_instantiation_declaration_after_definition);
3765 Diag(PrevPointOfInstantiation,
3766 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003767 assert(PrevPointOfInstantiation.isValid() &&
3768 "Explicit instantiation without point of instantiation?");
3769 SuppressNew = true;
3770 return false;
3771 }
3772 break;
3773
3774 case TSK_ExplicitInstantiationDefinition:
3775 switch (PrevTSK) {
3776 case TSK_Undeclared:
3777 case TSK_ImplicitInstantiation:
3778 // We're explicitly instantiating something that may have already been
3779 // implicitly instantiated; that's fine.
3780 return false;
3781
3782 case TSK_ExplicitSpecialization:
3783 // C++ DR 259, C++0x [temp.explicit]p4:
3784 // For a given set of template parameters, if an explicit
3785 // instantiation of a template appears after a declaration of
3786 // an explicit specialization for that template, the explicit
3787 // instantiation has no effect.
3788 //
3789 // In C++98/03 mode, we only give an extension warning here, because it
3790 // is not not harmful to try to explicitly instantiate something that
3791 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003792 if (!getLangOptions().CPlusPlus0x) {
3793 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003794 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003795 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003796 diag::note_previous_template_specialization);
3797 }
3798 SuppressNew = true;
3799 return false;
3800
3801 case TSK_ExplicitInstantiationDeclaration:
3802 // We're explicity instantiating a definition for something for which we
3803 // were previously asked to suppress instantiations. That's fine.
3804 return false;
3805
3806 case TSK_ExplicitInstantiationDefinition:
3807 // C++0x [temp.spec]p5:
3808 // For a given template and a given set of template-arguments,
3809 // - an explicit instantiation definition shall appear at most once
3810 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003811 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003812 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003813 Diag(PrevPointOfInstantiation,
3814 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003815 SuppressNew = true;
3816 return false;
3817 }
3818 break;
3819 }
3820
3821 assert(false && "Missing specialization/instantiation case?");
3822
3823 return false;
3824}
3825
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003826/// \brief Perform semantic analysis for the given function template
3827/// specialization.
3828///
3829/// This routine performs all of the semantic analysis required for an
3830/// explicit function template specialization. On successful completion,
3831/// the function declaration \p FD will become a function template
3832/// specialization.
3833///
3834/// \param FD the function declaration, which will be updated to become a
3835/// function template specialization.
3836///
3837/// \param HasExplicitTemplateArgs whether any template arguments were
3838/// explicitly provided.
3839///
3840/// \param LAngleLoc the location of the left angle bracket ('<'), if
3841/// template arguments were explicitly provided.
3842///
3843/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3844/// if any.
3845///
3846/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3847/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3848/// true as in, e.g., \c void sort<>(char*, char*);
3849///
3850/// \param RAngleLoc the location of the right angle bracket ('>'), if
3851/// template arguments were explicitly provided.
3852///
3853/// \param PrevDecl the set of declarations that
3854bool
3855Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003856 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003857 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003858 // The set of function template specializations that could match this
3859 // explicit function template specialization.
3860 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3861 CandidateSet Candidates;
3862
3863 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003864 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3865 I != E; ++I) {
3866 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3867 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003868 // Only consider templates found within the same semantic lookup scope as
3869 // FD.
3870 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3871 continue;
3872
3873 // C++ [temp.expl.spec]p11:
3874 // A trailing template-argument can be left unspecified in the
3875 // template-id naming an explicit function template specialization
3876 // provided it can be deduced from the function argument type.
3877 // Perform template argument deduction to determine whether we may be
3878 // specializing this template.
3879 // FIXME: It is somewhat wasteful to build
3880 TemplateDeductionInfo Info(Context);
3881 FunctionDecl *Specialization = 0;
3882 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003883 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003884 FD->getType(),
3885 Specialization,
3886 Info)) {
3887 // FIXME: Template argument deduction failed; record why it failed, so
3888 // that we can provide nifty diagnostics.
3889 (void)TDK;
3890 continue;
3891 }
3892
3893 // Record this candidate.
3894 Candidates.push_back(Specialization);
3895 }
3896 }
3897
Douglas Gregor5de279c2009-09-26 03:41:46 +00003898 // Find the most specialized function template.
3899 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3900 Candidates.size(),
3901 TPOC_Other,
3902 FD->getLocation(),
3903 PartialDiagnostic(diag::err_function_template_spec_no_match)
3904 << FD->getDeclName(),
3905 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003906 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003907 PartialDiagnostic(diag::note_function_template_spec_matched));
3908 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003909 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003910
3911 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003912 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003913
Douglas Gregor54888652009-10-07 00:13:32 +00003914 // Check the scope of this explicit specialization.
3915 if (CheckTemplateSpecializationScope(*this,
3916 Specialization->getPrimaryTemplate(),
3917 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003918 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003919 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003920
3921 // C++ [temp.expl.spec]p6:
3922 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003923 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003924 // before the first use of that specialization that would cause an implicit
3925 // instantiation to take place, in every translation unit in which such a
3926 // use occurs; no diagnostic is required.
3927 FunctionTemplateSpecializationInfo *SpecInfo
3928 = Specialization->getTemplateSpecializationInfo();
3929 assert(SpecInfo && "Function template specialization info missing?");
3930 if (SpecInfo->getPointOfInstantiation().isValid()) {
3931 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3932 << FD;
3933 Diag(SpecInfo->getPointOfInstantiation(),
3934 diag::note_instantiation_required_here)
3935 << (Specialization->getTemplateSpecializationKind()
3936 != TSK_ImplicitInstantiation);
3937 return true;
3938 }
Douglas Gregor54888652009-10-07 00:13:32 +00003939
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003940 // Mark the prior declaration as an explicit specialization, so that later
3941 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003942 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003943
3944 // Turn the given function declaration into a function template
3945 // specialization, with the template arguments from the previous
3946 // specialization.
3947 FD->setFunctionTemplateSpecialization(Context,
3948 Specialization->getPrimaryTemplate(),
3949 new (Context) TemplateArgumentList(
3950 *Specialization->getTemplateSpecializationArgs()),
3951 /*InsertPos=*/0,
3952 TSK_ExplicitSpecialization);
3953
3954 // The "previous declaration" for this function template specialization is
3955 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003956 Previous.clear();
3957 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003958 return false;
3959}
3960
Douglas Gregor86d142a2009-10-08 07:24:58 +00003961/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003962/// specialization.
3963///
3964/// This routine performs all of the semantic analysis required for an
3965/// explicit member function specialization. On successful completion,
3966/// the function declaration \p FD will become a member function
3967/// specialization.
3968///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003969/// \param Member the member declaration, which will be updated to become a
3970/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003971///
John McCall1f82f242009-11-18 22:49:29 +00003972/// \param Previous the set of declarations, one of which may be specialized
3973/// by this function specialization; the set will be modified to contain the
3974/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003975bool
John McCall1f82f242009-11-18 22:49:29 +00003976Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003977 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3978
3979 // Try to find the member we are instantiating.
3980 NamedDecl *Instantiation = 0;
3981 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003982 MemberSpecializationInfo *MSInfo = 0;
3983
John McCall1f82f242009-11-18 22:49:29 +00003984 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003985 // Nowhere to look anyway.
3986 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003987 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3988 I != E; ++I) {
3989 NamedDecl *D = (*I)->getUnderlyingDecl();
3990 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003991 if (Context.hasSameType(Function->getType(), Method->getType())) {
3992 Instantiation = Method;
3993 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003994 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003995 break;
3996 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003997 }
3998 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003999 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004000 VarDecl *PrevVar;
4001 if (Previous.isSingleResult() &&
4002 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004003 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004004 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004005 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004006 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004007 }
4008 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004009 CXXRecordDecl *PrevRecord;
4010 if (Previous.isSingleResult() &&
4011 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4012 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004013 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004014 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004015 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004016 }
4017
4018 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004019 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004020 // specializations are always out-of-line, the caller will complain about
4021 // this mismatch later.
4022 return false;
4023 }
4024
Douglas Gregor86d142a2009-10-08 07:24:58 +00004025 // Make sure that this is a specialization of a member.
4026 if (!InstantiatedFrom) {
4027 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4028 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004029 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4030 return true;
4031 }
4032
Douglas Gregor06db9f52009-10-12 20:18:28 +00004033 // C++ [temp.expl.spec]p6:
4034 // If a template, a member template or the member of a class template is
4035 // explicitly specialized then that spe- cialization shall be declared
4036 // before the first use of that specialization that would cause an implicit
4037 // instantiation to take place, in every translation unit in which such a
4038 // use occurs; no diagnostic is required.
4039 assert(MSInfo && "Member specialization info missing?");
4040 if (MSInfo->getPointOfInstantiation().isValid()) {
4041 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
4042 << Member;
4043 Diag(MSInfo->getPointOfInstantiation(),
4044 diag::note_instantiation_required_here)
4045 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
4046 return true;
4047 }
4048
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004049 // Check the scope of this explicit specialization.
4050 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004051 InstantiatedFrom,
4052 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004053 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004054 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004055
Douglas Gregor86d142a2009-10-08 07:24:58 +00004056 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004057 // the original declaration to note that it is an explicit specialization
4058 // (if it was previously an implicit instantiation). This latter step
4059 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004060 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004061 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4062 if (InstantiationFunction->getTemplateSpecializationKind() ==
4063 TSK_ImplicitInstantiation) {
4064 InstantiationFunction->setTemplateSpecializationKind(
4065 TSK_ExplicitSpecialization);
4066 InstantiationFunction->setLocation(Member->getLocation());
4067 }
4068
Douglas Gregor86d142a2009-10-08 07:24:58 +00004069 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4070 cast<CXXMethodDecl>(InstantiatedFrom),
4071 TSK_ExplicitSpecialization);
4072 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004073 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4074 if (InstantiationVar->getTemplateSpecializationKind() ==
4075 TSK_ImplicitInstantiation) {
4076 InstantiationVar->setTemplateSpecializationKind(
4077 TSK_ExplicitSpecialization);
4078 InstantiationVar->setLocation(Member->getLocation());
4079 }
4080
Douglas Gregor86d142a2009-10-08 07:24:58 +00004081 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4082 cast<VarDecl>(InstantiatedFrom),
4083 TSK_ExplicitSpecialization);
4084 } else {
4085 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004086 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4087 if (InstantiationClass->getTemplateSpecializationKind() ==
4088 TSK_ImplicitInstantiation) {
4089 InstantiationClass->setTemplateSpecializationKind(
4090 TSK_ExplicitSpecialization);
4091 InstantiationClass->setLocation(Member->getLocation());
4092 }
4093
Douglas Gregor86d142a2009-10-08 07:24:58 +00004094 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004095 cast<CXXRecordDecl>(InstantiatedFrom),
4096 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004097 }
4098
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004099 // Save the caller the trouble of having to figure out which declaration
4100 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004101 Previous.clear();
4102 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004103 return false;
4104}
4105
Douglas Gregore47f5a72009-10-14 23:41:34 +00004106/// \brief Check the scope of an explicit instantiation.
4107static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4108 SourceLocation InstLoc,
4109 bool WasQualifiedName) {
4110 DeclContext *ExpectedContext
4111 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4112 DeclContext *CurContext = S.CurContext->getLookupContext();
4113
4114 // C++0x [temp.explicit]p2:
4115 // An explicit instantiation shall appear in an enclosing namespace of its
4116 // template.
4117 //
4118 // This is DR275, which we do not retroactively apply to C++98/03.
4119 if (S.getLangOptions().CPlusPlus0x &&
4120 !CurContext->Encloses(ExpectedContext)) {
4121 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4122 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4123 << D << NS;
4124 else
4125 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4126 << D;
4127 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4128 return;
4129 }
4130
4131 // C++0x [temp.explicit]p2:
4132 // If the name declared in the explicit instantiation is an unqualified
4133 // name, the explicit instantiation shall appear in the namespace where
4134 // its template is declared or, if that namespace is inline (7.3.1), any
4135 // namespace from its enclosing namespace set.
4136 if (WasQualifiedName)
4137 return;
4138
4139 if (CurContext->Equals(ExpectedContext))
4140 return;
4141
4142 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4143 << D << ExpectedContext;
4144 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4145}
4146
4147/// \brief Determine whether the given scope specifier has a template-id in it.
4148static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4149 if (!SS.isSet())
4150 return false;
4151
4152 // C++0x [temp.explicit]p2:
4153 // If the explicit instantiation is for a member function, a member class
4154 // or a static data member of a class template specialization, the name of
4155 // the class template specialization in the qualified-id for the member
4156 // name shall be a simple-template-id.
4157 //
4158 // C++98 has the same restriction, just worded differently.
4159 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4160 NNS; NNS = NNS->getPrefix())
4161 if (Type *T = NNS->getAsType())
4162 if (isa<TemplateSpecializationType>(T))
4163 return true;
4164
4165 return false;
4166}
4167
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004168// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004169// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004170Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004171Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004172 SourceLocation ExternLoc,
4173 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004174 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004175 SourceLocation KWLoc,
4176 const CXXScopeSpec &SS,
4177 TemplateTy TemplateD,
4178 SourceLocation TemplateNameLoc,
4179 SourceLocation LAngleLoc,
4180 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004181 SourceLocation RAngleLoc,
4182 AttributeList *Attr) {
4183 // Find the class template we're specializing
4184 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004185 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004186 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4187
4188 // Check that the specialization uses the same tag kind as the
4189 // original template.
4190 TagDecl::TagKind Kind;
4191 switch (TagSpec) {
4192 default: assert(0 && "Unknown tag type!");
4193 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4194 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4195 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4196 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004197 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004198 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004199 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004200 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004201 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004202 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004203 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004204 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004205 diag::note_previous_use);
4206 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4207 }
4208
Douglas Gregore47f5a72009-10-14 23:41:34 +00004209 // C++0x [temp.explicit]p2:
4210 // There are two forms of explicit instantiation: an explicit instantiation
4211 // definition and an explicit instantiation declaration. An explicit
4212 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004213 TemplateSpecializationKind TSK
4214 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4215 : TSK_ExplicitInstantiationDeclaration;
4216
Douglas Gregora1f49972009-05-13 00:25:59 +00004217 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004218 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004219 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004220
4221 // Check that the template argument list is well-formed for this
4222 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004223 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4224 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004225 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4226 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004227 return true;
4228
Mike Stump11289f42009-09-09 15:08:12 +00004229 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004230 ClassTemplate->getTemplateParameters()->size()) &&
4231 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004232
Douglas Gregora1f49972009-05-13 00:25:59 +00004233 // Find the class template specialization declaration that
4234 // corresponds to these arguments.
4235 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004236 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004237 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004238 Converted.flatSize(),
4239 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004240 void *InsertPos = 0;
4241 ClassTemplateSpecializationDecl *PrevDecl
4242 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4243
Douglas Gregor54888652009-10-07 00:13:32 +00004244 // C++0x [temp.explicit]p2:
4245 // [...] An explicit instantiation shall appear in an enclosing
4246 // namespace of its template. [...]
4247 //
4248 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004249 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4250 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004251
Douglas Gregora1f49972009-05-13 00:25:59 +00004252 ClassTemplateSpecializationDecl *Specialization = 0;
4253
Douglas Gregor0681a352009-11-25 06:01:46 +00004254 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004255 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004256 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004257 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004258 PrevDecl,
4259 PrevDecl->getSpecializationKind(),
4260 PrevDecl->getPointOfInstantiation(),
4261 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004262 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004263
Douglas Gregor12e49d32009-10-15 22:53:21 +00004264 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004265 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004266
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004267 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4268 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4269 // Since the only prior class template specialization with these
4270 // arguments was referenced but not declared, reuse that
4271 // declaration node as our own, updating its source location to
4272 // reflect our new declaration.
4273 Specialization = PrevDecl;
4274 Specialization->setLocation(TemplateNameLoc);
4275 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004276 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004277 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004278 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004279
4280 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004281 // Create a new class template specialization declaration node for
4282 // this explicit specialization.
4283 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004284 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004285 ClassTemplate->getDeclContext(),
4286 TemplateNameLoc,
4287 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004288 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004289
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004290 if (PrevDecl) {
4291 // Remove the previous declaration from the folding set, since we want
4292 // to introduce a new declaration.
4293 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4294 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4295 }
4296
4297 // Insert the new specialization.
4298 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004299 }
4300
4301 // Build the fully-sugared type for this explicit instantiation as
4302 // the user wrote in the explicit instantiation itself. This means
4303 // that we'll pretty-print the type retrieved from the
4304 // specialization's declaration the way that the user actually wrote
4305 // the explicit instantiation, rather than formatting the name based
4306 // on the "canonical" representation used to store the template
4307 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004308 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00004309 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004310 Context.getTypeDeclType(Specialization));
4311 Specialization->setTypeAsWritten(WrittenTy);
4312 TemplateArgsIn.release();
4313
Douglas Gregor0681a352009-11-25 06:01:46 +00004314 if (!ReusedDecl) {
4315 // Add the explicit instantiation into its lexical context. However,
4316 // since explicit instantiations are never found by name lookup, we
4317 // just put it into the declaration context directly.
4318 Specialization->setLexicalDeclContext(CurContext);
4319 CurContext->addDecl(Specialization);
4320 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004321
4322 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004323 // A definition of a class template or class member template
4324 // shall be in scope at the point of the explicit instantiation of
4325 // the class template or class member template.
4326 //
4327 // This check comes when we actually try to perform the
4328 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004329 ClassTemplateSpecializationDecl *Def
4330 = cast_or_null<ClassTemplateSpecializationDecl>(
4331 Specialization->getDefinition(Context));
4332 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004333 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004334
4335 // Instantiate the members of this class template specialization.
4336 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4337 Specialization->getDefinition(Context));
4338 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004339 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004340
4341 return DeclPtrTy::make(Specialization);
4342}
4343
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004344// Explicit instantiation of a member class of a class template.
4345Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004346Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004347 SourceLocation ExternLoc,
4348 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004349 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004350 SourceLocation KWLoc,
4351 const CXXScopeSpec &SS,
4352 IdentifierInfo *Name,
4353 SourceLocation NameLoc,
4354 AttributeList *Attr) {
4355
Douglas Gregord6ab8742009-05-28 23:31:59 +00004356 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004357 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004358 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004359 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004360 MultiTemplateParamsArg(*this, 0, 0),
4361 Owned, IsDependent);
4362 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4363
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004364 if (!TagD)
4365 return true;
4366
4367 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4368 if (Tag->isEnum()) {
4369 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4370 << Context.getTypeDeclType(Tag);
4371 return true;
4372 }
4373
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004374 if (Tag->isInvalidDecl())
4375 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004376
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004377 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4378 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4379 if (!Pattern) {
4380 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4381 << Context.getTypeDeclType(Record);
4382 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4383 return true;
4384 }
4385
Douglas Gregore47f5a72009-10-14 23:41:34 +00004386 // C++0x [temp.explicit]p2:
4387 // If the explicit instantiation is for a class or member class, the
4388 // elaborated-type-specifier in the declaration shall include a
4389 // simple-template-id.
4390 //
4391 // C++98 has the same restriction, just worded differently.
4392 if (!ScopeSpecifierHasTemplateId(SS))
4393 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4394 << Record << SS.getRange();
4395
4396 // C++0x [temp.explicit]p2:
4397 // There are two forms of explicit instantiation: an explicit instantiation
4398 // definition and an explicit instantiation declaration. An explicit
4399 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004400 TemplateSpecializationKind TSK
4401 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4402 : TSK_ExplicitInstantiationDeclaration;
4403
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004404 // C++0x [temp.explicit]p2:
4405 // [...] An explicit instantiation shall appear in an enclosing
4406 // namespace of its template. [...]
4407 //
4408 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004409 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004410
4411 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004412 CXXRecordDecl *PrevDecl
4413 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4414 if (!PrevDecl && Record->getDefinition(Context))
4415 PrevDecl = Record;
4416 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004417 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4418 bool SuppressNew = false;
4419 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004420 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004421 PrevDecl,
4422 MSInfo->getTemplateSpecializationKind(),
4423 MSInfo->getPointOfInstantiation(),
4424 SuppressNew))
4425 return true;
4426 if (SuppressNew)
4427 return TagD;
4428 }
4429
Douglas Gregor12e49d32009-10-15 22:53:21 +00004430 CXXRecordDecl *RecordDef
4431 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4432 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004433 // C++ [temp.explicit]p3:
4434 // A definition of a member class of a class template shall be in scope
4435 // at the point of an explicit instantiation of the member class.
4436 CXXRecordDecl *Def
4437 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4438 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004439 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4440 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004441 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4442 << Pattern;
4443 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004444 } else {
4445 if (InstantiateClass(NameLoc, Record, Def,
4446 getTemplateInstantiationArgs(Record),
4447 TSK))
4448 return true;
4449
4450 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4451 if (!RecordDef)
4452 return true;
4453 }
4454 }
4455
4456 // Instantiate all of the members of the class.
4457 InstantiateClassMembers(NameLoc, RecordDef,
4458 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004459
Mike Stump87c57ac2009-05-16 07:39:55 +00004460 // FIXME: We don't have any representation for explicit instantiations of
4461 // member classes. Such a representation is not needed for compilation, but it
4462 // should be available for clients that want to see all of the declarations in
4463 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004464 return TagD;
4465}
4466
Douglas Gregor450f00842009-09-25 18:43:00 +00004467Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4468 SourceLocation ExternLoc,
4469 SourceLocation TemplateLoc,
4470 Declarator &D) {
4471 // Explicit instantiations always require a name.
4472 DeclarationName Name = GetNameForDeclarator(D);
4473 if (!Name) {
4474 if (!D.isInvalidType())
4475 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4476 diag::err_explicit_instantiation_requires_name)
4477 << D.getDeclSpec().getSourceRange()
4478 << D.getSourceRange();
4479
4480 return true;
4481 }
4482
4483 // The scope passed in may not be a decl scope. Zip up the scope tree until
4484 // we find one that is.
4485 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4486 (S->getFlags() & Scope::TemplateParamScope) != 0)
4487 S = S->getParent();
4488
4489 // Determine the type of the declaration.
4490 QualType R = GetTypeForDeclarator(D, S, 0);
4491 if (R.isNull())
4492 return true;
4493
4494 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4495 // Cannot explicitly instantiate a typedef.
4496 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4497 << Name;
4498 return true;
4499 }
4500
Douglas Gregor3c74d412009-10-14 20:14:33 +00004501 // C++0x [temp.explicit]p1:
4502 // [...] An explicit instantiation of a function template shall not use the
4503 // inline or constexpr specifiers.
4504 // Presumably, this also applies to member functions of class templates as
4505 // well.
4506 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4507 Diag(D.getDeclSpec().getInlineSpecLoc(),
4508 diag::err_explicit_instantiation_inline)
4509 << CodeModificationHint::CreateRemoval(
4510 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4511
4512 // FIXME: check for constexpr specifier.
4513
Douglas Gregore47f5a72009-10-14 23:41:34 +00004514 // C++0x [temp.explicit]p2:
4515 // There are two forms of explicit instantiation: an explicit instantiation
4516 // definition and an explicit instantiation declaration. An explicit
4517 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004518 TemplateSpecializationKind TSK
4519 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4520 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004521
John McCall27b18f82009-11-17 02:14:36 +00004522 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4523 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004524
4525 if (!R->isFunctionType()) {
4526 // C++ [temp.explicit]p1:
4527 // A [...] static data member of a class template can be explicitly
4528 // instantiated from the member definition associated with its class
4529 // template.
John McCall27b18f82009-11-17 02:14:36 +00004530 if (Previous.isAmbiguous())
4531 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004532
John McCall9f3059a2009-10-09 21:13:30 +00004533 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4534 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004535 if (!Prev || !Prev->isStaticDataMember()) {
4536 // We expect to see a data data member here.
4537 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4538 << Name;
4539 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4540 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004541 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004542 return true;
4543 }
4544
4545 if (!Prev->getInstantiatedFromStaticDataMember()) {
4546 // FIXME: Check for explicit specialization?
4547 Diag(D.getIdentifierLoc(),
4548 diag::err_explicit_instantiation_data_member_not_instantiated)
4549 << Prev;
4550 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4551 // FIXME: Can we provide a note showing where this was declared?
4552 return true;
4553 }
4554
Douglas Gregore47f5a72009-10-14 23:41:34 +00004555 // C++0x [temp.explicit]p2:
4556 // If the explicit instantiation is for a member function, a member class
4557 // or a static data member of a class template specialization, the name of
4558 // the class template specialization in the qualified-id for the member
4559 // name shall be a simple-template-id.
4560 //
4561 // C++98 has the same restriction, just worded differently.
4562 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4563 Diag(D.getIdentifierLoc(),
4564 diag::err_explicit_instantiation_without_qualified_id)
4565 << Prev << D.getCXXScopeSpec().getRange();
4566
4567 // Check the scope of this explicit instantiation.
4568 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4569
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004570 // Verify that it is okay to explicitly instantiate here.
4571 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4572 assert(MSInfo && "Missing static data member specialization info?");
4573 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004574 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004575 MSInfo->getTemplateSpecializationKind(),
4576 MSInfo->getPointOfInstantiation(),
4577 SuppressNew))
4578 return true;
4579 if (SuppressNew)
4580 return DeclPtrTy();
4581
Douglas Gregor450f00842009-09-25 18:43:00 +00004582 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004583 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004584 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004585 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4586 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004587
4588 // FIXME: Create an ExplicitInstantiation node?
4589 return DeclPtrTy();
4590 }
4591
Douglas Gregor0e876e02009-09-25 23:53:26 +00004592 // If the declarator is a template-id, translate the parser's template
4593 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004594 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004595 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004596 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4597 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004598 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4599 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004600 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4601 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004602 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004603 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004604 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004605 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004606 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004607
Douglas Gregor450f00842009-09-25 18:43:00 +00004608 // C++ [temp.explicit]p1:
4609 // A [...] function [...] can be explicitly instantiated from its template.
4610 // A member function [...] of a class template can be explicitly
4611 // instantiated from the member definition associated with its class
4612 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004613 llvm::SmallVector<FunctionDecl *, 8> Matches;
4614 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4615 P != PEnd; ++P) {
4616 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004617 if (!HasExplicitTemplateArgs) {
4618 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4619 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4620 Matches.clear();
4621 Matches.push_back(Method);
4622 break;
4623 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004624 }
4625 }
4626
4627 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4628 if (!FunTmpl)
4629 continue;
4630
4631 TemplateDeductionInfo Info(Context);
4632 FunctionDecl *Specialization = 0;
4633 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004634 = DeduceTemplateArguments(FunTmpl,
4635 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004636 R, Specialization, Info)) {
4637 // FIXME: Keep track of almost-matches?
4638 (void)TDK;
4639 continue;
4640 }
4641
4642 Matches.push_back(Specialization);
4643 }
4644
4645 // Find the most specialized function template specialization.
4646 FunctionDecl *Specialization
4647 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4648 D.getIdentifierLoc(),
4649 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4650 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4651 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4652
4653 if (!Specialization)
4654 return true;
4655
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004656 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004657 Diag(D.getIdentifierLoc(),
4658 diag::err_explicit_instantiation_member_function_not_instantiated)
4659 << Specialization
4660 << (Specialization->getTemplateSpecializationKind() ==
4661 TSK_ExplicitSpecialization);
4662 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4663 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004664 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004665
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004666 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004667 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4668 PrevDecl = Specialization;
4669
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004670 if (PrevDecl) {
4671 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004672 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004673 PrevDecl,
4674 PrevDecl->getTemplateSpecializationKind(),
4675 PrevDecl->getPointOfInstantiation(),
4676 SuppressNew))
4677 return true;
4678
4679 // FIXME: We may still want to build some representation of this
4680 // explicit specialization.
4681 if (SuppressNew)
4682 return DeclPtrTy();
4683 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004684
4685 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004686
4687 if (TSK == TSK_ExplicitInstantiationDefinition)
4688 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4689 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004690
Douglas Gregore47f5a72009-10-14 23:41:34 +00004691 // C++0x [temp.explicit]p2:
4692 // If the explicit instantiation is for a member function, a member class
4693 // or a static data member of a class template specialization, the name of
4694 // the class template specialization in the qualified-id for the member
4695 // name shall be a simple-template-id.
4696 //
4697 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004698 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004699 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004700 D.getCXXScopeSpec().isSet() &&
4701 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4702 Diag(D.getIdentifierLoc(),
4703 diag::err_explicit_instantiation_without_qualified_id)
4704 << Specialization << D.getCXXScopeSpec().getRange();
4705
4706 CheckExplicitInstantiationScope(*this,
4707 FunTmpl? (NamedDecl *)FunTmpl
4708 : Specialization->getInstantiatedFromMemberFunction(),
4709 D.getIdentifierLoc(),
4710 D.getCXXScopeSpec().isSet());
4711
Douglas Gregor450f00842009-09-25 18:43:00 +00004712 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4713 return DeclPtrTy();
4714}
4715
Douglas Gregor333489b2009-03-27 23:10:48 +00004716Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004717Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4718 const CXXScopeSpec &SS, IdentifierInfo *Name,
4719 SourceLocation TagLoc, SourceLocation NameLoc) {
4720 // This has to hold, because SS is expected to be defined.
4721 assert(Name && "Expected a name in a dependent tag");
4722
4723 NestedNameSpecifier *NNS
4724 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4725 if (!NNS)
4726 return true;
4727
4728 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4729 if (T.isNull())
4730 return true;
4731
4732 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4733 QualType ElabType = Context.getElaboratedType(T, TagKind);
4734
4735 return ElabType.getAsOpaquePtr();
4736}
4737
4738Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004739Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4740 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004741 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004742 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4743 if (!NNS)
4744 return true;
4745
4746 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004747 if (T.isNull())
4748 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004749 return T.getAsOpaquePtr();
4750}
4751
Douglas Gregordce2b622009-04-01 00:28:59 +00004752Sema::TypeResult
4753Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4754 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004755 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004756 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004757 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004758 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004759 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004760 assert(TemplateId && "Expected a template specialization type");
4761
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004762 if (computeDeclContext(SS, false)) {
4763 // If we can compute a declaration context, then the "typename"
4764 // keyword was superfluous. Just build a QualifiedNameType to keep
4765 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004766
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004767 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4768 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4769 }
Mike Stump11289f42009-09-09 15:08:12 +00004770
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004771 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004772}
4773
Douglas Gregor333489b2009-03-27 23:10:48 +00004774/// \brief Build the type that describes a C++ typename specifier,
4775/// e.g., "typename T::type".
4776QualType
4777Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4778 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004779 CXXRecordDecl *CurrentInstantiation = 0;
4780 if (NNS->isDependent()) {
4781 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004782
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004783 // If the nested-name-specifier does not refer to the current
4784 // instantiation, then build a typename type.
4785 if (!CurrentInstantiation)
4786 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004787
Douglas Gregorc707da62009-09-02 13:12:51 +00004788 // The nested-name-specifier refers to the current instantiation, so the
4789 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004790 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004791 // extraneous "typename" keywords, and we retroactively apply this DR to
4792 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004793 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004794
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004795 DeclContext *Ctx = 0;
4796
4797 if (CurrentInstantiation)
4798 Ctx = CurrentInstantiation;
4799 else {
4800 CXXScopeSpec SS;
4801 SS.setScopeRep(NNS);
4802 SS.setRange(Range);
4803 if (RequireCompleteDeclContext(SS))
4804 return QualType();
4805
4806 Ctx = computeDeclContext(SS);
4807 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004808 assert(Ctx && "No declaration context?");
4809
4810 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004811 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4812 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004813 unsigned DiagID = 0;
4814 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004815 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004816 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004817 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004818 break;
4819
4820 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004821 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004822 // We found a type. Build a QualifiedNameType, since the
4823 // typename-specifier was just sugar. FIXME: Tell
4824 // QualifiedNameType that it has a "typename" prefix.
4825 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4826 }
4827
4828 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004829 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004830 break;
4831
John McCalle61f2ba2009-11-18 02:36:19 +00004832 case LookupResult::FoundUnresolvedValue:
4833 llvm::llvm_unreachable("unresolved using decl in non-dependent context");
4834 return QualType();
4835
Douglas Gregor333489b2009-03-27 23:10:48 +00004836 case LookupResult::FoundOverloaded:
4837 DiagID = diag::err_typename_nested_not_type;
4838 Referenced = *Result.begin();
4839 break;
4840
John McCall6538c932009-10-10 05:48:19 +00004841 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004842 return QualType();
4843 }
4844
4845 // If we get here, it's because name lookup did not find a
4846 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004847 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004848 if (Referenced)
4849 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4850 << Name;
4851 return QualType();
4852}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004853
4854namespace {
4855 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00004856 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00004857 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004858 SourceLocation Loc;
4859 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004860
Douglas Gregor15acfb92009-08-06 16:20:37 +00004861 public:
Mike Stump11289f42009-09-09 15:08:12 +00004862 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004863 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004864 DeclarationName Entity)
4865 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004866 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004867
4868 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004869 /// transformed.
4870 ///
4871 /// For the purposes of type reconstruction, a type has already been
4872 /// transformed if it is NULL or if it is not dependent.
4873 bool AlreadyTransformed(QualType T) {
4874 return T.isNull() || !T->isDependentType();
4875 }
Mike Stump11289f42009-09-09 15:08:12 +00004876
4877 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004878 /// rebuilt.
4879 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004880
Douglas Gregor15acfb92009-08-06 16:20:37 +00004881 /// \brief Returns the name of the entity whose type is being rebuilt.
4882 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004883
Douglas Gregoref6ab412009-10-27 06:26:26 +00004884 /// \brief Sets the "base" location and entity when that
4885 /// information is known based on another transformation.
4886 void setBase(SourceLocation Loc, DeclarationName Entity) {
4887 this->Loc = Loc;
4888 this->Entity = Entity;
4889 }
4890
Douglas Gregor15acfb92009-08-06 16:20:37 +00004891 /// \brief Transforms an expression by returning the expression itself
4892 /// (an identity function).
4893 ///
4894 /// FIXME: This is completely unsafe; we will need to actually clone the
4895 /// expressions.
4896 Sema::OwningExprResult TransformExpr(Expr *E) {
4897 return getSema().Owned(E);
4898 }
Mike Stump11289f42009-09-09 15:08:12 +00004899
Douglas Gregor15acfb92009-08-06 16:20:37 +00004900 /// \brief Transforms a typename type by determining whether the type now
4901 /// refers to a member of the current instantiation, and then
4902 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004903 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004904 };
4905}
4906
Mike Stump11289f42009-09-09 15:08:12 +00004907QualType
John McCall550e0c22009-10-21 00:40:46 +00004908CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4909 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004910 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004911
Douglas Gregor15acfb92009-08-06 16:20:37 +00004912 NestedNameSpecifier *NNS
4913 = TransformNestedNameSpecifier(T->getQualifier(),
4914 /*FIXME:*/SourceRange(getBaseLocation()));
4915 if (!NNS)
4916 return QualType();
4917
4918 // If the nested-name-specifier did not change, and we cannot compute the
4919 // context corresponding to the nested-name-specifier, then this
4920 // typename type will not change; exit early.
4921 CXXScopeSpec SS;
4922 SS.setRange(SourceRange(getBaseLocation()));
4923 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004924
4925 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004926 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004927 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004928
4929 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004930 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004931 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004932 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004933 = TransformType(QualType(TemplateId, 0));
4934 if (NewTemplateId.isNull())
4935 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004936
Douglas Gregor15acfb92009-08-06 16:20:37 +00004937 if (NNS == T->getQualifier() &&
4938 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004939 Result = QualType(T, 0);
4940 else
4941 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4942 } else
4943 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4944 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004945
John McCall0ad16662009-10-29 08:12:44 +00004946 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4947 NewTL.setNameLoc(TL.getNameLoc());
4948 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004949}
4950
4951/// \brief Rebuilds a type within the context of the current instantiation.
4952///
Mike Stump11289f42009-09-09 15:08:12 +00004953/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004954/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004955/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004956/// partial specialization thereof). This routine will rebuild that type now
4957/// that we have entered the declarator's scope, which may produce different
4958/// canonical types, e.g.,
4959///
4960/// \code
4961/// template<typename T>
4962/// struct X {
4963/// typedef T* pointer;
4964/// pointer data();
4965/// };
4966///
4967/// template<typename T>
4968/// typename X<T>::pointer X<T>::data() { ... }
4969/// \endcode
4970///
4971/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4972/// since we do not know that we can look into X<T> when we parsed the type.
4973/// This function will rebuild the type, performing the lookup of "pointer"
4974/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4975/// as the canonical type of T*, allowing the return types of the out-of-line
4976/// definition and the declaration to match.
4977QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4978 DeclarationName Name) {
4979 if (T.isNull() || !T->isDependentType())
4980 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004981
Douglas Gregor15acfb92009-08-06 16:20:37 +00004982 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4983 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004984}
Douglas Gregorbe999392009-09-15 16:23:51 +00004985
4986/// \brief Produces a formatted string that describes the binding of
4987/// template parameters to template arguments.
4988std::string
4989Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4990 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004991 // FIXME: For variadic templates, we'll need to get the structured list.
4992 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4993 Args.flat_size());
4994}
4995
4996std::string
4997Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4998 const TemplateArgument *Args,
4999 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005000 std::string Result;
5001
Douglas Gregore62e6a02009-11-11 19:13:48 +00005002 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005003 return Result;
5004
5005 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005006 if (I >= NumArgs)
5007 break;
5008
Douglas Gregorbe999392009-09-15 16:23:51 +00005009 if (I == 0)
5010 Result += "[with ";
5011 else
5012 Result += ", ";
5013
5014 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5015 Result += Id->getName();
5016 } else {
5017 Result += '$';
5018 Result += llvm::utostr(I);
5019 }
5020
5021 Result += " = ";
5022
5023 switch (Args[I].getKind()) {
5024 case TemplateArgument::Null:
5025 Result += "<no value>";
5026 break;
5027
5028 case TemplateArgument::Type: {
5029 std::string TypeStr;
5030 Args[I].getAsType().getAsStringInternal(TypeStr,
5031 Context.PrintingPolicy);
5032 Result += TypeStr;
5033 break;
5034 }
5035
5036 case TemplateArgument::Declaration: {
5037 bool Unnamed = true;
5038 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5039 if (ND->getDeclName()) {
5040 Unnamed = false;
5041 Result += ND->getNameAsString();
5042 }
5043 }
5044
5045 if (Unnamed) {
5046 Result += "<anonymous>";
5047 }
5048 break;
5049 }
5050
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005051 case TemplateArgument::Template: {
5052 std::string Str;
5053 llvm::raw_string_ostream OS(Str);
5054 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5055 Result += OS.str();
5056 break;
5057 }
5058
Douglas Gregorbe999392009-09-15 16:23:51 +00005059 case TemplateArgument::Integral: {
5060 Result += Args[I].getAsIntegral()->toString(10);
5061 break;
5062 }
5063
5064 case TemplateArgument::Expression: {
5065 assert(false && "No expressions in deduced template arguments!");
5066 Result += "<expression>";
5067 break;
5068 }
5069
5070 case TemplateArgument::Pack:
5071 // FIXME: Format template argument packs
5072 Result += "<template argument pack>";
5073 break;
5074 }
5075 }
5076
5077 Result += ']';
5078 return Result;
5079}