blob: 0e680f643814772353c934f7f8841738845b4e24 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000019#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000020#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000023#include "llvm/Support/Compiler.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D);
63 if (!Ovl)
64 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000065
Douglas Gregorb7bfe792009-09-02 22:59:36 +000066 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
67 FEnd = Ovl->function_end();
68 F != FEnd; ++F) {
69 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) {
70 // We've found a function template. Determine whether there are
71 // any other function templates we need to bundle together in an
72 // OverloadedFunctionDecl
73 for (++F; F != FEnd; ++F) {
74 if (isa<FunctionTemplateDecl>(*F))
75 break;
76 }
Mike Stump11289f42009-09-09 15:08:12 +000077
Douglas Gregorb7bfe792009-09-02 22:59:36 +000078 if (F != FEnd) {
79 // Build an overloaded function decl containing only the
80 // function templates in Ovl.
Mike Stump11289f42009-09-09 15:08:12 +000081 OverloadedFunctionDecl *OvlTemplate
Douglas Gregorb7bfe792009-09-02 22:59:36 +000082 = OverloadedFunctionDecl::Create(Context,
83 Ovl->getDeclContext(),
84 Ovl->getDeclName());
85 OvlTemplate->addOverload(FuncTmpl);
86 OvlTemplate->addOverload(*F);
87 for (++F; F != FEnd; ++F) {
88 if (isa<FunctionTemplateDecl>(*F))
89 OvlTemplate->addOverload(*F);
90 }
Mike Stump11289f42009-09-09 15:08:12 +000091
Douglas Gregorb7bfe792009-09-02 22:59:36 +000092 return OvlTemplate;
93 }
94
95 return FuncTmpl;
96 }
97 }
Mike Stump11289f42009-09-09 15:08:12 +000098
Douglas Gregorb7bfe792009-09-02 22:59:36 +000099 return 0;
100}
101
John McCalle66edc12009-11-24 19:00:30 +0000102static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
103 LookupResult::Filter filter = R.makeFilter();
104 while (filter.hasNext()) {
105 NamedDecl *Orig = filter.next();
106 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
107 if (!Repl)
108 filter.erase();
109 else if (Repl != Orig)
110 filter.replace(Repl);
111 }
112 filter.done();
113}
114
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000115TemplateNameKind Sema::isTemplateName(Scope *S,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000116 const CXXScopeSpec &SS,
117 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000118 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000119 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000120 TemplateTy &TemplateResult) {
Douglas Gregor3cf81312009-11-03 23:16:33 +0000121 DeclarationName TName;
122
123 switch (Name.getKind()) {
124 case UnqualifiedId::IK_Identifier:
125 TName = DeclarationName(Name.Identifier);
126 break;
127
128 case UnqualifiedId::IK_OperatorFunctionId:
129 TName = Context.DeclarationNames.getCXXOperatorName(
130 Name.OperatorFunctionId.Operator);
131 break;
132
133 default:
134 return TNK_Non_template;
135 }
Mike Stump11289f42009-09-09 15:08:12 +0000136
John McCalle66edc12009-11-24 19:00:30 +0000137 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000138
John McCalle66edc12009-11-24 19:00:30 +0000139 LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName);
140 R.suppressDiagnostics();
141 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
142 if (R.empty())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000143 return TNK_Non_template;
144
John McCalle66edc12009-11-24 19:00:30 +0000145 NamedDecl *Template = R.getAsSingleDecl(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000146
Douglas Gregor3cf81312009-11-03 23:16:33 +0000147 if (SS.isSet() && !SS.isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000148 NestedNameSpecifier *Qualifier
Douglas Gregor3cf81312009-11-03 23:16:33 +0000149 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +0000150 if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000151 = dyn_cast<OverloadedFunctionDecl>(Template))
Mike Stump11289f42009-09-09 15:08:12 +0000152 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000153 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
154 Ovl));
155 else
Mike Stump11289f42009-09-09 15:08:12 +0000156 TemplateResult
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000157 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false,
Mike Stump11289f42009-09-09 15:08:12 +0000158 cast<TemplateDecl>(Template)));
159 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000160 = dyn_cast<OverloadedFunctionDecl>(Template)) {
161 TemplateResult = TemplateTy::make(TemplateName(Ovl));
162 } else {
163 TemplateResult = TemplateTy::make(
164 TemplateName(cast<TemplateDecl>(Template)));
165 }
Mike Stump11289f42009-09-09 15:08:12 +0000166
167 if (isa<ClassTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000168 isa<TemplateTemplateParmDecl>(Template))
169 return TNK_Type_template;
Mike Stump11289f42009-09-09 15:08:12 +0000170
171 assert((isa<FunctionTemplateDecl>(Template) ||
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000172 isa<OverloadedFunctionDecl>(Template)) &&
173 "Unhandled template kind in Sema::isTemplateName");
John McCalle66edc12009-11-24 19:00:30 +0000174 return TNK_Function_template;
175}
176
177void Sema::LookupTemplateName(LookupResult &Found,
178 Scope *S, const CXXScopeSpec &SS,
179 QualType ObjectType,
180 bool EnteringContext) {
181 // Determine where to perform name lookup
182 DeclContext *LookupCtx = 0;
183 bool isDependent = false;
184 if (!ObjectType.isNull()) {
185 // This nested-name-specifier occurs in a member access expression, e.g.,
186 // x->B::f, and we are looking into the type of the object.
187 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
188 LookupCtx = computeDeclContext(ObjectType);
189 isDependent = ObjectType->isDependentType();
190 assert((isDependent || !ObjectType->isIncompleteType()) &&
191 "Caller should have completed object type");
192 } else if (SS.isSet()) {
193 // This nested-name-specifier occurs after another nested-name-specifier,
194 // so long into the context associated with the prior nested-name-specifier.
195 LookupCtx = computeDeclContext(SS, EnteringContext);
196 isDependent = isDependentScopeSpecifier(SS);
197
198 // The declaration context must be complete.
199 if (LookupCtx && RequireCompleteDeclContext(SS))
200 return;
201 }
202
203 bool ObjectTypeSearchedInScope = false;
204 if (LookupCtx) {
205 // Perform "qualified" name lookup into the declaration context we
206 // computed, which is either the type of the base of a member access
207 // expression or the declaration context associated with a prior
208 // nested-name-specifier.
209 LookupQualifiedName(Found, LookupCtx);
210
211 if (!ObjectType.isNull() && Found.empty()) {
212 // C++ [basic.lookup.classref]p1:
213 // In a class member access expression (5.2.5), if the . or -> token is
214 // immediately followed by an identifier followed by a <, the
215 // identifier must be looked up to determine whether the < is the
216 // beginning of a template argument list (14.2) or a less-than operator.
217 // The identifier is first looked up in the class of the object
218 // expression. If the identifier is not found, it is then looked up in
219 // the context of the entire postfix-expression and shall name a class
220 // or function template.
221 //
222 // FIXME: When we're instantiating a template, do we actually have to
223 // look in the scope of the template? Seems fishy...
224 if (S) LookupName(Found, S);
225 ObjectTypeSearchedInScope = true;
226 }
227 } else if (isDependent) {
228 // We cannot look into a dependent object type or
229 return;
230 } else {
231 // Perform unqualified name lookup in the current scope.
232 LookupName(Found, S);
233 }
234
235 // FIXME: Cope with ambiguous name-lookup results.
236 assert(!Found.isAmbiguous() &&
237 "Cannot handle template name-lookup ambiguities");
238
239 FilterAcceptableTemplateNames(Context, Found);
240 if (Found.empty())
241 return;
242
243 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
244 // C++ [basic.lookup.classref]p1:
245 // [...] If the lookup in the class of the object expression finds a
246 // template, the name is also looked up in the context of the entire
247 // postfix-expression and [...]
248 //
249 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
250 LookupOrdinaryName);
251 LookupName(FoundOuter, S);
252 FilterAcceptableTemplateNames(Context, FoundOuter);
253 // FIXME: Handle ambiguities in this lookup better
254
255 if (FoundOuter.empty()) {
256 // - if the name is not found, the name found in the class of the
257 // object expression is used, otherwise
258 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
259 // - if the name is found in the context of the entire
260 // postfix-expression and does not name a class template, the name
261 // found in the class of the object expression is used, otherwise
262 } else {
263 // - if the name found is a class template, it must refer to the same
264 // entity as the one found in the class of the object expression,
265 // otherwise the program is ill-formed.
266 if (!Found.isSingleResult() ||
267 Found.getFoundDecl()->getCanonicalDecl()
268 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
269 Diag(Found.getNameLoc(),
270 diag::err_nested_name_member_ref_lookup_ambiguous)
271 << Found.getLookupName();
272 Diag(Found.getRepresentativeDecl()->getLocation(),
273 diag::note_ambig_member_ref_object_type)
274 << ObjectType;
275 Diag(FoundOuter.getFoundDecl()->getLocation(),
276 diag::note_ambig_member_ref_scope);
277
278 // Recover by taking the template that we found in the object
279 // expression's type.
280 }
281 }
282 }
283}
284
285/// Constructs a full type for the given nested-name-specifier.
286static QualType GetTypeForQualifier(ASTContext &Context,
287 NestedNameSpecifier *Qualifier) {
288 // Three possibilities:
289
290 // 1. A namespace (global or not).
291 assert(!Qualifier->getAsNamespace() && "can't construct type for namespace");
292
293 // 2. A type (templated or not).
294 Type *Ty = Qualifier->getAsType();
295 if (Ty) return QualType(Ty, 0);
296
297 // 3. A dependent identifier.
298 assert(Qualifier->getAsIdentifier());
299 return Context.getTypenameType(Qualifier->getPrefix(),
300 Qualifier->getAsIdentifier());
301}
302
303static bool HasDependentTypeAsBase(ASTContext &Context,
304 CXXRecordDecl *Record,
305 CanQualType T) {
306 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
307 E = Record->bases_end(); I != E; ++I) {
308 CanQualType BaseT = Context.getCanonicalType((*I).getType());
309 if (BaseT == T)
310 return true;
311
312 // We have to recurse here to cover some really bizarre cases.
313 // Obviously, we can only have the dependent type as an indirect
314 // base class through a dependent base class, and usually it's
315 // impossible to know which instantiation a dependent base class
316 // will have. But! If we're actually *inside* the dependent base
317 // class, then we know its instantiation and can therefore be
318 // reasonably expected to look into it.
319
320 // template <class T> class A : Base<T> {
321 // class Inner : A<T> {
322 // void foo() {
323 // Base<T>::foo(); // statically known to be an implicit member
324 // reference
325 // }
326 // };
327 // };
328
329 CanQual<RecordType> RT = BaseT->getAs<RecordType>();
330 assert(RT && "base is not a record type");
331 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(RT->getDecl());
332 if (BaseRecord->isDefinition() &&
333 HasDependentTypeAsBase(Context, BaseRecord, T))
334 return true;
335 }
336
337 return false;
338}
339
340/// Checks whether the given dependent nested-name specifier
341/// introduces an implicit member reference. This is only true if the
342/// nested-name specifier names a type identical to one of the current
343/// instance method's context's (possibly indirect) base classes.
344static bool IsImplicitDependentMemberReference(Sema &SemaRef,
345 NestedNameSpecifier *Qualifier,
346 QualType &ThisType) {
347 // If the context isn't a C++ method, then it isn't an implicit
348 // member reference.
349 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext);
350 if (!MD || MD->isStatic())
351 return false;
352
353 ASTContext &Context = SemaRef.Context;
354
355 // We want to check whether the method's context is known to inherit
356 // from the type named by the nested name specifier. The trivial
357 // case here is:
358 // template <class T> class Base { ... };
359 // template <class T> class Derived : Base<T> {
360 // void foo() {
361 // Base<T>::foo();
362 // }
363 // };
364
365 QualType QT = GetTypeForQualifier(Context, Qualifier);
366 CanQualType T = Context.getCanonicalType(QT);
367
368 // And now, just walk the non-dependent type hierarchy, trying to
369 // find the given type as a literal base class.
370 CXXRecordDecl *Record = cast<CXXRecordDecl>(MD->getParent());
371 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
372 return true;
373
374 return HasDependentTypeAsBase(Context, Record, T);
375}
376
377/// ActOnDependentIdExpression - Handle a dependent declaration name
378/// that was just parsed.
379Sema::OwningExprResult
380Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
381 DeclarationName Name,
382 SourceLocation NameLoc,
383 bool CheckForImplicitMember,
384 const TemplateArgumentListInfo *TemplateArgs) {
385 NestedNameSpecifier *Qualifier
386 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
387
388 QualType ThisType;
389 if (CheckForImplicitMember &&
390 IsImplicitDependentMemberReference(*this, Qualifier, ThisType)) {
391 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
392
393 // Since the 'this' expression is synthesized, we don't need to
394 // perform the double-lookup check.
395 NamedDecl *FirstQualifierInScope = 0;
396
397 return Owned(CXXDependentScopeMemberExpr::Create(Context, This, true,
398 /*Op*/ SourceLocation(),
399 Qualifier, SS.getRange(),
400 FirstQualifierInScope,
401 Name, NameLoc,
402 TemplateArgs));
403 }
404
405 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
406}
407
408Sema::OwningExprResult
409Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
410 DeclarationName Name,
411 SourceLocation NameLoc,
412 const TemplateArgumentListInfo *TemplateArgs) {
413 return Owned(DependentScopeDeclRefExpr::Create(Context,
414 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
415 SS.getRange(),
416 Name, NameLoc,
417 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000418}
419
Douglas Gregor5101c242008-12-05 18:15:24 +0000420/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
421/// that the template parameter 'PrevDecl' is being shadowed by a new
422/// declaration at location Loc. Returns true to indicate that this is
423/// an error, and false otherwise.
424bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000425 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000426
427 // Microsoft Visual C++ permits template parameters to be shadowed.
428 if (getLangOptions().Microsoft)
429 return false;
430
431 // C++ [temp.local]p4:
432 // A template-parameter shall not be redeclared within its
433 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000434 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000435 << cast<NamedDecl>(PrevDecl)->getDeclName();
436 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
437 return true;
438}
439
Douglas Gregor463421d2009-03-03 04:44:36 +0000440/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000441/// the parameter D to reference the templated declaration and return a pointer
442/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000443TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000444 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000445 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000446 return Temp;
447 }
448 return 0;
449}
450
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000451static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
452 const ParsedTemplateArgument &Arg) {
453
454 switch (Arg.getKind()) {
455 case ParsedTemplateArgument::Type: {
456 DeclaratorInfo *DI;
457 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
458 if (!DI)
459 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation());
460 return TemplateArgumentLoc(TemplateArgument(T), DI);
461 }
462
463 case ParsedTemplateArgument::NonType: {
464 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
465 return TemplateArgumentLoc(TemplateArgument(E), E);
466 }
467
468 case ParsedTemplateArgument::Template: {
469 TemplateName Template
470 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
471 return TemplateArgumentLoc(TemplateArgument(Template),
472 Arg.getScopeSpec().getRange(),
473 Arg.getLocation());
474 }
475 }
476
477 llvm::llvm_unreachable("Unhandled parsed template argument");
478 return TemplateArgumentLoc();
479}
480
481/// \brief Translates template arguments as provided by the parser
482/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000483void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
484 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000485 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000486 TemplateArgs.addArgument(translateTemplateArgument(*this,
487 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000488}
489
Douglas Gregor5101c242008-12-05 18:15:24 +0000490/// ActOnTypeParameter - Called when a C++ template type parameter
491/// (e.g., "typename T") has been parsed. Typename specifies whether
492/// the keyword "typename" was used to declare the type parameter
493/// (otherwise, "class" was used), and KeyLoc is the location of the
494/// "class" or "typename" keyword. ParamName is the name of the
495/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000496/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000497/// If the type parameter has a default argument, it will be added
498/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000499Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000500 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000501 SourceLocation KeyLoc,
502 IdentifierInfo *ParamName,
503 SourceLocation ParamNameLoc,
504 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000505 assert(S->isTemplateParamScope() &&
506 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000507 bool Invalid = false;
508
509 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000510 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000511 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000512 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000513 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000514 }
515
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000516 SourceLocation Loc = ParamNameLoc;
517 if (!ParamName)
518 Loc = KeyLoc;
519
Douglas Gregor5101c242008-12-05 18:15:24 +0000520 TemplateTypeParmDecl *Param
Mike Stump11289f42009-09-09 15:08:12 +0000521 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
522 Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000523 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000524 if (Invalid)
525 Param->setInvalidDecl();
526
527 if (ParamName) {
528 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000529 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000530 IdResolver.AddDecl(Param);
531 }
532
Chris Lattner83f095c2009-03-28 19:18:32 +0000533 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000534}
535
Douglas Gregordba32632009-02-10 19:49:53 +0000536/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000537/// Default) to the given template type parameter (TypeParam).
538void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000539 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000540 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000541 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000542 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000543 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000544
545 DeclaratorInfo *DefaultDInfo;
546 GetTypeFromParser(DefaultT, &DefaultDInfo);
547
548 assert(DefaultDInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000549
Anders Carlssond3824352009-06-12 22:30:13 +0000550 // C++0x [temp.param]p9:
551 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000552 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000553 if (Parm->isParameterPack()) {
554 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000555 return;
556 }
Mike Stump11289f42009-09-09 15:08:12 +0000557
Douglas Gregordba32632009-02-10 19:49:53 +0000558 // C++ [temp.param]p14:
559 // A template-parameter shall not be used in its own default argument.
560 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000561
Douglas Gregordba32632009-02-10 19:49:53 +0000562 // Check the template argument itself.
John McCall0ad16662009-10-29 08:12:44 +0000563 if (CheckTemplateArgument(Parm, DefaultDInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000564 Parm->setInvalidDecl();
565 return;
566 }
567
John McCall0ad16662009-10-29 08:12:44 +0000568 Parm->setDefaultArgument(DefaultDInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000569}
570
Douglas Gregor463421d2009-03-03 04:44:36 +0000571/// \brief Check that the type of a non-type template parameter is
572/// well-formed.
573///
574/// \returns the (possibly-promoted) parameter type if valid;
575/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000576QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000577Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
578 // C++ [temp.param]p4:
579 //
580 // A non-type template-parameter shall have one of the following
581 // (optionally cv-qualified) types:
582 //
583 // -- integral or enumeration type,
584 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000585 // -- pointer to object or pointer to function,
586 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000587 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
588 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000589 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000590 T->isReferenceType() ||
591 // -- pointer to member.
592 T->isMemberPointerType() ||
593 // If T is a dependent type, we can't do the check now, so we
594 // assume that it is well-formed.
595 T->isDependentType())
596 return T;
597 // C++ [temp.param]p8:
598 //
599 // A non-type template-parameter of type "array of T" or
600 // "function returning T" is adjusted to be of type "pointer to
601 // T" or "pointer to function returning T", respectively.
602 else if (T->isArrayType())
603 // FIXME: Keep the type prior to promotion?
604 return Context.getArrayDecayedType(T);
605 else if (T->isFunctionType())
606 // FIXME: Keep the type prior to promotion?
607 return Context.getPointerType(T);
608
609 Diag(Loc, diag::err_template_nontype_parm_bad_type)
610 << T;
611
612 return QualType();
613}
614
Douglas Gregor5101c242008-12-05 18:15:24 +0000615/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
616/// template parameter (e.g., "int Size" in "template<int Size>
617/// class Array") has been parsed. S is the current scope and D is
618/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000619Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000620 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000621 unsigned Position) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000622 DeclaratorInfo *DInfo = 0;
623 QualType T = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000624
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000625 assert(S->isTemplateParamScope() &&
626 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000627 bool Invalid = false;
628
629 IdentifierInfo *ParamName = D.getIdentifier();
630 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000631 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000632 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000633 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000634 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000635 }
636
Douglas Gregor463421d2009-03-03 04:44:36 +0000637 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000638 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000639 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000640 Invalid = true;
641 }
Douglas Gregor81338792009-02-10 17:43:50 +0000642
Douglas Gregor5101c242008-12-05 18:15:24 +0000643 NonTypeTemplateParmDecl *Param
644 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000645 Depth, Position, ParamName, T, DInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000646 if (Invalid)
647 Param->setInvalidDecl();
648
649 if (D.getIdentifier()) {
650 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000651 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000652 IdResolver.AddDecl(Param);
653 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000654 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000655}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000656
Douglas Gregordba32632009-02-10 19:49:53 +0000657/// \brief Adds a default argument to the given non-type template
658/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000659void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000660 SourceLocation EqualLoc,
661 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000662 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000663 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000664 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000665
Douglas Gregordba32632009-02-10 19:49:53 +0000666 // C++ [temp.param]p14:
667 // A template-parameter shall not be used in its own default argument.
668 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000669
Douglas Gregordba32632009-02-10 19:49:53 +0000670 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000671 TemplateArgument Converted;
672 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
673 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000674 TemplateParm->setInvalidDecl();
675 return;
676 }
677
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000678 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000679}
680
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000681
682/// ActOnTemplateTemplateParameter - Called when a C++ template template
683/// parameter (e.g. T in template <template <typename> class T> class array)
684/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000685Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
686 SourceLocation TmpLoc,
687 TemplateParamsTy *Params,
688 IdentifierInfo *Name,
689 SourceLocation NameLoc,
690 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000691 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000692 assert(S->isTemplateParamScope() &&
693 "Template template parameter not in template parameter scope!");
694
695 // Construct the parameter object.
696 TemplateTemplateParmDecl *Param =
697 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
698 Position, Name,
699 (TemplateParameterList*)Params);
700
701 // Make sure the parameter is valid.
702 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
703 // do anything yet. However, if the template parameter list or (eventual)
704 // default value is ever invalidated, that will propagate here.
705 bool Invalid = false;
706 if (Invalid) {
707 Param->setInvalidDecl();
708 }
709
710 // If the tt-param has a name, then link the identifier into the scope
711 // and lookup mechanisms.
712 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000713 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000714 IdResolver.AddDecl(Param);
715 }
716
Chris Lattner83f095c2009-03-28 19:18:32 +0000717 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000718}
719
Douglas Gregordba32632009-02-10 19:49:53 +0000720/// \brief Adds a default argument to the given template template
721/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000722void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000723 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000724 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000725 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000726 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000727
Douglas Gregordba32632009-02-10 19:49:53 +0000728 // C++ [temp.param]p14:
729 // A template-parameter shall not be used in its own default argument.
730 // FIXME: Implement this check! Needs a recursive walk over the types.
731
Douglas Gregore62e6a02009-11-11 19:13:48 +0000732 // Check only that we have a template template argument. We don't want to
733 // try to check well-formedness now, because our template template parameter
734 // might have dependent types in its template parameters, which we wouldn't
735 // be able to match now.
736 //
737 // If none of the template template parameter's template arguments mention
738 // other template parameters, we could actually perform more checking here.
739 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000740 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000741 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
742 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
743 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000744 return;
745 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000746
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000747 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000748}
749
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000750/// ActOnTemplateParameterList - Builds a TemplateParameterList that
751/// contains the template parameters in Params/NumParams.
752Sema::TemplateParamsTy *
753Sema::ActOnTemplateParameterList(unsigned Depth,
754 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000755 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000756 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000757 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000758 SourceLocation RAngleLoc) {
759 if (ExportLoc.isValid())
760 Diag(ExportLoc, diag::note_template_export_unsupported);
761
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000762 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000763 (NamedDecl**)Params, NumParams,
764 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000765}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000766
Douglas Gregorc08f4892009-03-25 00:13:59 +0000767Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000768Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000769 SourceLocation KWLoc, const CXXScopeSpec &SS,
770 IdentifierInfo *Name, SourceLocation NameLoc,
771 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000772 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000773 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000774 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000775 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000776 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000777 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000778
779 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000780 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000781 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000782
John McCall27b5c252009-09-14 21:59:20 +0000783 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
784 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000785
786 // There is no such thing as an unnamed class template.
787 if (!Name) {
788 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000789 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000790 }
791
792 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000793 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000794 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000795 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000796 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000797 if (RequireCompleteDeclContext(SS))
798 return true;
799
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000800 SemanticContext = computeDeclContext(SS, true);
801 if (!SemanticContext) {
802 // FIXME: Produce a reasonable diagnostic here
803 return true;
804 }
Mike Stump11289f42009-09-09 15:08:12 +0000805
John McCall27b18f82009-11-17 02:14:36 +0000806 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000807 } else {
808 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000809 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000810 }
Mike Stump11289f42009-09-09 15:08:12 +0000811
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000812 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
813 NamedDecl *PrevDecl = 0;
814 if (Previous.begin() != Previous.end())
815 PrevDecl = *Previous.begin();
816
Douglas Gregor9acb6902009-09-26 07:05:09 +0000817 if (PrevDecl && TUK == TUK_Friend) {
818 // C++ [namespace.memdef]p3:
819 // [...] When looking for a prior declaration of a class or a function
820 // declared as a friend, and when the name of the friend class or
821 // function is neither a qualified name nor a template-id, scopes outside
822 // the innermost enclosing namespace scope are not considered.
823 DeclContext *OutermostContext = CurContext;
824 while (!OutermostContext->isFileContext())
825 OutermostContext = OutermostContext->getLookupParent();
826
827 if (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
828 OutermostContext->Encloses(PrevDecl->getDeclContext())) {
829 SemanticContext = PrevDecl->getDeclContext();
830 } else {
831 // Declarations in outer scopes don't matter. However, the outermost
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000832 // context we computed is the semantic context for our new
Douglas Gregor9acb6902009-09-26 07:05:09 +0000833 // declaration.
834 PrevDecl = 0;
835 SemanticContext = OutermostContext;
836 }
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000837
838 if (CurContext->isDependentContext()) {
839 // If this is a dependent context, we don't want to link the friend
840 // class template to the template in scope, because that would perform
841 // checking of the template parameter lists that can't be performed
842 // until the outer context is instantiated.
843 PrevDecl = 0;
844 }
Douglas Gregor9acb6902009-09-26 07:05:09 +0000845 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
Douglas Gregorf187420f2009-06-17 23:37:01 +0000846 PrevDecl = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000847
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000848 // If there is a previous declaration with the same name, check
849 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000850 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000851 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000852
853 // We may have found the injected-class-name of a class template,
854 // class template partial specialization, or class template specialization.
855 // In these cases, grab the template that is being defined or specialized.
856 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
857 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
858 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
859 PrevClassTemplate
860 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
861 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
862 PrevClassTemplate
863 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
864 ->getSpecializedTemplate();
865 }
866 }
867
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000868 if (PrevClassTemplate) {
869 // Ensure that the template parameter lists are compatible.
870 if (!TemplateParameterListsAreEqual(TemplateParams,
871 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000872 /*Complain=*/true,
873 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000874 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000875
876 // C++ [temp.class]p4:
877 // In a redeclaration, partial specialization, explicit
878 // specialization or explicit instantiation of a class template,
879 // the class-key shall agree in kind with the original class
880 // template declaration (7.1.5.3).
881 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000882 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000883 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000884 << Name
Mike Stump11289f42009-09-09 15:08:12 +0000885 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +0000886 PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000887 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000888 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000889 }
890
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000891 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000892 if (TUK == TUK_Definition) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000893 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
894 Diag(NameLoc, diag::err_redefinition) << Name;
895 Diag(Def->getLocation(), diag::note_previous_definition);
896 // FIXME: Would it make sense to try to "forget" the previous
897 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000898 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000899 }
900 }
901 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
902 // Maybe we will complain about the shadowed template parameter.
903 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
904 // Just pretend that we didn't see the previous declaration.
905 PrevDecl = 0;
906 } else if (PrevDecl) {
907 // C++ [temp]p5:
908 // A class template shall not have the same name as any other
909 // template, class, function, object, enumeration, enumerator,
910 // namespace, or type in the same scope (3.3), except as specified
911 // in (14.5.4).
912 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
913 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000914 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000915 }
916
Douglas Gregordba32632009-02-10 19:49:53 +0000917 // Check the template parameter list of this declaration, possibly
918 // merging in the template parameter list from the previous class
919 // template declaration.
920 if (CheckTemplateParameterList(TemplateParams,
921 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
922 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000923
Douglas Gregore362cea2009-05-10 22:57:19 +0000924 // FIXME: If we had a scope specifier, we better have a previous template
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000925 // declaration!
926
Mike Stump11289f42009-09-09 15:08:12 +0000927 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000928 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000929 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000930 PrevClassTemplate->getTemplatedDecl() : 0,
931 /*DelayTypeCreation=*/true);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000932
933 ClassTemplateDecl *NewTemplate
934 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
935 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000936 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000937 NewClass->setDescribedClassTemplate(NewTemplate);
938
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000939 // Build the type for the class template declaration now.
Mike Stump11289f42009-09-09 15:08:12 +0000940 QualType T =
941 Context.getTypeDeclType(NewClass,
942 PrevClassTemplate?
943 PrevClassTemplate->getTemplatedDecl() : 0);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000944 assert(T->isDependentType() && "Class template type is not dependent?");
945 (void)T;
946
Douglas Gregorcf915552009-10-13 16:30:37 +0000947 // If we are providing an explicit specialization of a member that is a
948 // class template, make a note of that.
949 if (PrevClassTemplate &&
950 PrevClassTemplate->getInstantiatedFromMemberTemplate())
951 PrevClassTemplate->setMemberSpecialization();
952
Anders Carlsson137108d2009-03-26 01:24:28 +0000953 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000954 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000955 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000956
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000957 // Set the lexical context of these templates
958 NewClass->setLexicalDeclContext(CurContext);
959 NewTemplate->setLexicalDeclContext(CurContext);
960
John McCall9bb74a52009-07-31 02:45:11 +0000961 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000962 NewClass->startDefinition();
963
964 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000965 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000966
John McCall27b5c252009-09-14 21:59:20 +0000967 if (TUK != TUK_Friend)
968 PushOnScopeChains(NewTemplate, S);
969 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000970 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000971 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000972 NewClass->setAccess(PrevClassTemplate->getAccess());
973 }
John McCall27b5c252009-09-14 21:59:20 +0000974
Douglas Gregor3dad8422009-09-26 06:47:28 +0000975 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
976 PrevClassTemplate != NULL);
977
John McCall27b5c252009-09-14 21:59:20 +0000978 // Friend templates are visible in fairly strange ways.
979 if (!CurContext->isDependentContext()) {
980 DeclContext *DC = SemanticContext->getLookupContext();
981 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
982 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
983 PushOnScopeChains(NewTemplate, EnclosingScope,
984 /* AddToContext = */ false);
985 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000986
987 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
988 NewClass->getLocation(),
989 NewTemplate,
990 /*FIXME:*/NewClass->getLocation());
991 Friend->setAccess(AS_public);
992 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000993 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000994
Douglas Gregordba32632009-02-10 19:49:53 +0000995 if (Invalid) {
996 NewTemplate->setInvalidDecl();
997 NewClass->setInvalidDecl();
998 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000999 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001000}
1001
Douglas Gregordba32632009-02-10 19:49:53 +00001002/// \brief Checks the validity of a template parameter list, possibly
1003/// considering the template parameter list from a previous
1004/// declaration.
1005///
1006/// If an "old" template parameter list is provided, it must be
1007/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1008/// template parameter list.
1009///
1010/// \param NewParams Template parameter list for a new template
1011/// declaration. This template parameter list will be updated with any
1012/// default arguments that are carried through from the previous
1013/// template parameter list.
1014///
1015/// \param OldParams If provided, template parameter list from a
1016/// previous declaration of the same template. Default template
1017/// arguments will be merged from the old template parameter list to
1018/// the new template parameter list.
1019///
1020/// \returns true if an error occurred, false otherwise.
1021bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1022 TemplateParameterList *OldParams) {
1023 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregordba32632009-02-10 19:49:53 +00001025 // C++ [temp.param]p10:
1026 // The set of default template-arguments available for use with a
1027 // template declaration or definition is obtained by merging the
1028 // default arguments from the definition (if in scope) and all
1029 // declarations in scope in the same way default function
1030 // arguments are (8.3.6).
1031 bool SawDefaultArgument = false;
1032 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001033
Anders Carlsson327865d2009-06-12 23:20:15 +00001034 bool SawParameterPack = false;
1035 SourceLocation ParameterPackLoc;
1036
Mike Stumpc89c8e32009-02-11 23:03:27 +00001037 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001038 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001039 if (OldParams)
1040 OldParam = OldParams->begin();
1041
1042 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1043 NewParamEnd = NewParams->end();
1044 NewParam != NewParamEnd; ++NewParam) {
1045 // Variables used to diagnose redundant default arguments
1046 bool RedundantDefaultArg = false;
1047 SourceLocation OldDefaultLoc;
1048 SourceLocation NewDefaultLoc;
1049
1050 // Variables used to diagnose missing default arguments
1051 bool MissingDefaultArg = false;
1052
Anders Carlsson327865d2009-06-12 23:20:15 +00001053 // C++0x [temp.param]p11:
1054 // If a template parameter of a class template is a template parameter pack,
1055 // it must be the last template parameter.
1056 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001057 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001058 diag::err_template_param_pack_must_be_last_template_parameter);
1059 Invalid = true;
1060 }
1061
Douglas Gregordba32632009-02-10 19:49:53 +00001062 // Merge default arguments for template type parameters.
1063 if (TemplateTypeParmDecl *NewTypeParm
1064 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Mike Stump11289f42009-09-09 15:08:12 +00001065 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001066 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001067
Anders Carlsson327865d2009-06-12 23:20:15 +00001068 if (NewTypeParm->isParameterPack()) {
1069 assert(!NewTypeParm->hasDefaultArgument() &&
1070 "Parameter packs can't have a default argument!");
1071 SawParameterPack = true;
1072 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001073 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001074 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001075 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1076 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1077 SawDefaultArgument = true;
1078 RedundantDefaultArg = true;
1079 PreviousDefaultArgLoc = NewDefaultLoc;
1080 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1081 // Merge the default argument from the old declaration to the
1082 // new declaration.
1083 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001084 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001085 true);
1086 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1087 } else if (NewTypeParm->hasDefaultArgument()) {
1088 SawDefaultArgument = true;
1089 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1090 } else if (SawDefaultArgument)
1091 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001092 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001093 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001094 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001095 NonTypeTemplateParmDecl *OldNonTypeParm
1096 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001097 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001098 NewNonTypeParm->hasDefaultArgument()) {
1099 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1100 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1101 SawDefaultArgument = true;
1102 RedundantDefaultArg = true;
1103 PreviousDefaultArgLoc = NewDefaultLoc;
1104 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1105 // Merge the default argument from the old declaration to the
1106 // new declaration.
1107 SawDefaultArgument = true;
1108 // FIXME: We need to create a new kind of "default argument"
1109 // expression that points to a previous template template
1110 // parameter.
1111 NewNonTypeParm->setDefaultArgument(
1112 OldNonTypeParm->getDefaultArgument());
1113 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1114 } else if (NewNonTypeParm->hasDefaultArgument()) {
1115 SawDefaultArgument = true;
1116 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1117 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001118 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001119 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001120 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001121 TemplateTemplateParmDecl *NewTemplateParm
1122 = cast<TemplateTemplateParmDecl>(*NewParam);
1123 TemplateTemplateParmDecl *OldTemplateParm
1124 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001125 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001126 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001127 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1128 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001129 SawDefaultArgument = true;
1130 RedundantDefaultArg = true;
1131 PreviousDefaultArgLoc = NewDefaultLoc;
1132 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1133 // Merge the default argument from the old declaration to the
1134 // new declaration.
1135 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001136 // FIXME: We need to create a new kind of "default argument" expression
1137 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001138 NewTemplateParm->setDefaultArgument(
1139 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001140 PreviousDefaultArgLoc
1141 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001142 } else if (NewTemplateParm->hasDefaultArgument()) {
1143 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001144 PreviousDefaultArgLoc
1145 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001146 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001147 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001148 }
1149
1150 if (RedundantDefaultArg) {
1151 // C++ [temp.param]p12:
1152 // A template-parameter shall not be given default arguments
1153 // by two different declarations in the same scope.
1154 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1155 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1156 Invalid = true;
1157 } else if (MissingDefaultArg) {
1158 // C++ [temp.param]p11:
1159 // If a template-parameter has a default template-argument,
1160 // all subsequent template-parameters shall have a default
1161 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001162 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001163 diag::err_template_param_default_arg_missing);
1164 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1165 Invalid = true;
1166 }
1167
1168 // If we have an old template parameter list that we're merging
1169 // in, move on to the next parameter.
1170 if (OldParams)
1171 ++OldParam;
1172 }
1173
1174 return Invalid;
1175}
Douglas Gregord32e0282009-02-09 23:23:08 +00001176
Mike Stump11289f42009-09-09 15:08:12 +00001177/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001178/// specifier, returning the template parameter list that applies to the
1179/// name.
1180///
1181/// \param DeclStartLoc the start of the declaration that has a scope
1182/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001183///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001184/// \param SS the scope specifier that will be matched to the given template
1185/// parameter lists. This scope specifier precedes a qualified name that is
1186/// being declared.
1187///
1188/// \param ParamLists the template parameter lists, from the outermost to the
1189/// innermost template parameter lists.
1190///
1191/// \param NumParamLists the number of template parameter lists in ParamLists.
1192///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001193/// \param IsExplicitSpecialization will be set true if the entity being
1194/// declared is an explicit specialization, false otherwise.
1195///
Mike Stump11289f42009-09-09 15:08:12 +00001196/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001197/// name that is preceded by the scope specifier @p SS. This template
1198/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001199/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001200/// template specialization), or may be NULL (if we were's declaring isn't
1201/// itself a template).
1202TemplateParameterList *
1203Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1204 const CXXScopeSpec &SS,
1205 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001206 unsigned NumParamLists,
1207 bool &IsExplicitSpecialization) {
1208 IsExplicitSpecialization = false;
1209
Douglas Gregord8d297c2009-07-21 23:53:31 +00001210 // Find the template-ids that occur within the nested-name-specifier. These
1211 // template-ids will match up with the template parameter lists.
1212 llvm::SmallVector<const TemplateSpecializationType *, 4>
1213 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001214 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1215 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001216 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1217 NNS; NNS = NNS->getPrefix()) {
Mike Stump11289f42009-09-09 15:08:12 +00001218 if (const TemplateSpecializationType *SpecType
Douglas Gregord8d297c2009-07-21 23:53:31 +00001219 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
1220 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1221 if (!Template)
1222 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001223
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001224 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001225 ClassTemplateSpecializationDecl *SpecDecl
1226 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1227 // If the nested name specifier refers to an explicit specialization,
1228 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001229 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1230 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001231 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001232 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001233 }
Mike Stump11289f42009-09-09 15:08:12 +00001234
Douglas Gregord8d297c2009-07-21 23:53:31 +00001235 TemplateIdsInSpecifier.push_back(SpecType);
1236 }
1237 }
Mike Stump11289f42009-09-09 15:08:12 +00001238
Douglas Gregord8d297c2009-07-21 23:53:31 +00001239 // Reverse the list of template-ids in the scope specifier, so that we can
1240 // more easily match up the template-ids and the template parameter lists.
1241 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001242
Douglas Gregord8d297c2009-07-21 23:53:31 +00001243 SourceLocation FirstTemplateLoc = DeclStartLoc;
1244 if (NumParamLists)
1245 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001246
Douglas Gregord8d297c2009-07-21 23:53:31 +00001247 // Match the template-ids found in the specifier to the template parameter
1248 // lists.
1249 unsigned Idx = 0;
1250 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1251 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001252 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1253 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001254 if (Idx >= NumParamLists) {
1255 // We have a template-id without a corresponding template parameter
1256 // list.
1257 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001258 // FIXME: the location information here isn't great.
1259 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001260 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001261 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001262 << SS.getRange();
1263 } else {
1264 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1265 << SS.getRange()
1266 << CodeModificationHint::CreateInsertion(FirstTemplateLoc,
1267 "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001268 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001269 }
1270 return 0;
1271 }
Mike Stump11289f42009-09-09 15:08:12 +00001272
Douglas Gregord8d297c2009-07-21 23:53:31 +00001273 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001274 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001275 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001276 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1277
Mike Stump11289f42009-09-09 15:08:12 +00001278 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001279 = dyn_cast<ClassTemplateDecl>(Template)) {
1280 TemplateParameterList *ExpectedTemplateParams = 0;
1281 // Is this template-id naming the primary template?
1282 if (Context.hasSameType(TemplateId,
1283 ClassTemplate->getInjectedClassNameType(Context)))
1284 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1285 // ... or a partial specialization?
1286 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1287 = ClassTemplate->findPartialSpecialization(TemplateId))
1288 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1289
1290 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001291 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001292 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001293 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001294 }
Douglas Gregor15301382009-07-30 17:40:51 +00001295 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001296 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001297 diag::err_template_param_list_matches_nontemplate)
1298 << TemplateId
1299 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001300 else
1301 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001302 }
Mike Stump11289f42009-09-09 15:08:12 +00001303
Douglas Gregord8d297c2009-07-21 23:53:31 +00001304 // If there were at least as many template-ids as there were template
1305 // parameter lists, then there are no template parameter lists remaining for
1306 // the declaration itself.
1307 if (Idx >= NumParamLists)
1308 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001309
Douglas Gregord8d297c2009-07-21 23:53:31 +00001310 // If there were too many template parameter lists, complain about that now.
1311 if (Idx != NumParamLists - 1) {
1312 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001313 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001314 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001315 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1316 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001317 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1318 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001319
1320 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1321 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1322 diag::note_explicit_template_spec_does_not_need_header)
1323 << ExplicitSpecializationsInSpecifier.back();
1324 ExplicitSpecializationsInSpecifier.pop_back();
1325 }
1326
Douglas Gregord8d297c2009-07-21 23:53:31 +00001327 ++Idx;
1328 }
1329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Douglas Gregord8d297c2009-07-21 23:53:31 +00001331 // Return the last template parameter list, which corresponds to the
1332 // entity being declared.
1333 return ParamLists[NumParamLists - 1];
1334}
1335
Douglas Gregordc572a32009-03-30 22:58:21 +00001336QualType Sema::CheckTemplateIdType(TemplateName Name,
1337 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001338 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001339 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001340 if (!Template) {
1341 // The template name does not resolve to a template, so we just
1342 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001343 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001344 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001345
Douglas Gregorc40290e2009-03-09 23:48:35 +00001346 // Check that the template argument list is well-formed for this
1347 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001348 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001349 TemplateArgs.size());
1350 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001351 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001352 return QualType();
1353
Mike Stump11289f42009-09-09 15:08:12 +00001354 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001355 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001356 "Converted template argument list is too short!");
1357
1358 QualType CanonType;
1359
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001360 if (Name.isDependent() ||
1361 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001362 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001363 // This class template specialization is a dependent
1364 // type. Therefore, its canonical type is another class template
1365 // specialization type that contains all of the converted
1366 // arguments in canonical form. This ensures that, e.g., A<T> and
1367 // A<T, T> have identical types when A is declared as:
1368 //
1369 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001370 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001371 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001372 Converted.getFlatArguments(),
1373 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001374
Douglas Gregora8e02e72009-07-28 23:00:59 +00001375 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001376 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001377 // In the future, we need to teach getTemplateSpecializationType to only
1378 // build the canonical type and return that to us.
1379 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001380 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001381 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001382 // Find the class template specialization declaration that
1383 // corresponds to these arguments.
1384 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001385 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001386 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001387 Converted.flatSize(),
1388 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001389 void *InsertPos = 0;
1390 ClassTemplateSpecializationDecl *Decl
1391 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1392 if (!Decl) {
1393 // This is the first time we have referenced this class template
1394 // specialization. Create the canonical declaration and add it to
1395 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001396 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001397 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001398 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001399 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001400 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001401 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1402 Decl->setLexicalDeclContext(CurContext);
1403 }
1404
1405 CanonType = Context.getTypeDeclType(Decl);
1406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407
Douglas Gregorc40290e2009-03-09 23:48:35 +00001408 // Build the fully-sugared type for this class template
1409 // specialization, which refers back to the class template
1410 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001411 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001412}
1413
Douglas Gregor67a65642009-02-17 23:15:12 +00001414Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001415Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001416 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001417 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001418 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001419 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001420
Douglas Gregorc40290e2009-03-09 23:48:35 +00001421 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001422 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001423 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001424
John McCall6b51f282009-11-23 01:53:49 +00001425 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001426 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001427
1428 if (Result.isNull())
1429 return true;
1430
John McCall0ad16662009-10-29 08:12:44 +00001431 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result);
1432 TemplateSpecializationTypeLoc TL
1433 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1434 TL.setTemplateNameLoc(TemplateLoc);
1435 TL.setLAngleLoc(LAngleLoc);
1436 TL.setRAngleLoc(RAngleLoc);
1437 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1438 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1439
1440 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001441}
John McCall06f6fe8d2009-09-04 01:14:41 +00001442
John McCalld8fe9af2009-09-08 17:47:29 +00001443Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1444 TagUseKind TUK,
1445 DeclSpec::TST TagSpec,
1446 SourceLocation TagLoc) {
1447 if (TypeResult.isInvalid())
1448 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001449
John McCall0ad16662009-10-29 08:12:44 +00001450 // FIXME: preserve source info, ideally without copying the DI.
1451 DeclaratorInfo *DI;
1452 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001453
John McCalld8fe9af2009-09-08 17:47:29 +00001454 // Verify the tag specifier.
1455 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001456
John McCalld8fe9af2009-09-08 17:47:29 +00001457 if (const RecordType *RT = Type->getAs<RecordType>()) {
1458 RecordDecl *D = RT->getDecl();
1459
1460 IdentifierInfo *Id = D->getIdentifier();
1461 assert(Id && "templated class must have an identifier");
1462
1463 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1464 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001465 << Type
John McCalld8fe9af2009-09-08 17:47:29 +00001466 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc),
1467 D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001468 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001469 }
1470 }
1471
John McCalld8fe9af2009-09-08 17:47:29 +00001472 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1473
1474 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001475}
1476
John McCalle66edc12009-11-24 19:00:30 +00001477Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1478 LookupResult &R,
1479 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001480 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001481 // FIXME: Can we do any checking at this point? I guess we could check the
1482 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001483 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001484 // though.
John McCalle66edc12009-11-24 19:00:30 +00001485
1486 // These should be filtered out by our callers.
1487 assert(!R.empty() && "empty lookup results when building templateid");
1488 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1489
1490 NestedNameSpecifier *Qualifier = 0;
1491 SourceRange QualifierRange;
1492 if (SS.isSet()) {
1493 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1494 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001495 }
1496
John McCalle66edc12009-11-24 19:00:30 +00001497 bool Dependent
1498 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1499 &TemplateArgs);
1500 UnresolvedLookupExpr *ULE
1501 = UnresolvedLookupExpr::Create(Context, Dependent,
1502 Qualifier, QualifierRange,
1503 R.getLookupName(), R.getNameLoc(),
1504 RequiresADL, TemplateArgs);
1505 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1506 ULE->addDecl(*I);
1507
1508 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001509}
1510
John McCalle66edc12009-11-24 19:00:30 +00001511// We actually only call this from template instantiation.
1512Sema::OwningExprResult
1513Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS,
1514 DeclarationName Name,
1515 SourceLocation NameLoc,
1516 const TemplateArgumentListInfo &TemplateArgs) {
1517 DeclContext *DC;
1518 if (!(DC = computeDeclContext(SS, false)) ||
1519 DC->isDependentContext() ||
1520 RequireCompleteDeclContext(SS))
1521 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001522
John McCalle66edc12009-11-24 19:00:30 +00001523 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1524 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001525
John McCalle66edc12009-11-24 19:00:30 +00001526 if (R.isAmbiguous())
1527 return ExprError();
1528
1529 if (R.empty()) {
1530 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1531 << Name << SS.getRange();
1532 return ExprError();
1533 }
1534
1535 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1536 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1537 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1538 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1539 return ExprError();
1540 }
1541
1542 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001543}
1544
Douglas Gregorb67535d2009-03-31 00:43:58 +00001545/// \brief Form a dependent template name.
1546///
1547/// This action forms a dependent template name given the template
1548/// name and its (presumably dependent) scope specifier. For
1549/// example, given "MetaFun::template apply", the scope specifier \p
1550/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1551/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001552Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001553Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001554 const CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001555 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001556 TypeTy *ObjectType,
1557 bool EnteringContext) {
Mike Stump11289f42009-09-09 15:08:12 +00001558 if ((ObjectType &&
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001559 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) ||
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001560 (SS.isSet() && computeDeclContext(SS, EnteringContext))) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001561 // C++0x [temp.names]p5:
1562 // If a name prefixed by the keyword template is not the name of
1563 // a template, the program is ill-formed. [Note: the keyword
1564 // template may not be applied to non-template members of class
1565 // templates. -end note ] [ Note: as is the case with the
1566 // typename prefix, the template prefix is allowed in cases
1567 // where it is not strictly necessary; i.e., when the
1568 // nested-name-specifier or the expression on the left of the ->
1569 // or . is not dependent on a template-parameter, or the use
1570 // does not appear in the scope of a template. -end note]
1571 //
1572 // Note: C++03 was more strict here, because it banned the use of
1573 // the "template" keyword prior to a template-name that was not a
1574 // dependent name. C++ DR468 relaxed this requirement (the
1575 // "template" keyword is now permitted). We follow the C++0x
1576 // rules, even in C++03 mode, retroactively applying the DR.
1577 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001578 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001579 EnteringContext, Template);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001580 if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001581 Diag(Name.getSourceRange().getBegin(),
1582 diag::err_template_kw_refers_to_non_template)
1583 << GetNameFromUnqualifiedId(Name)
1584 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001585 return TemplateTy();
1586 }
1587
1588 return Template;
1589 }
1590
Mike Stump11289f42009-09-09 15:08:12 +00001591 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001592 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001593
1594 switch (Name.getKind()) {
1595 case UnqualifiedId::IK_Identifier:
1596 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1597 Name.Identifier));
1598
Douglas Gregor71395fa2009-11-04 00:56:37 +00001599 case UnqualifiedId::IK_OperatorFunctionId:
1600 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1601 Name.OperatorFunctionId.Operator));
1602
Douglas Gregor3cf81312009-11-03 23:16:33 +00001603 default:
1604 break;
1605 }
1606
1607 Diag(Name.getSourceRange().getBegin(),
1608 diag::err_template_kw_refers_to_non_template)
1609 << GetNameFromUnqualifiedId(Name)
1610 << Name.getSourceRange();
1611 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001612}
1613
Mike Stump11289f42009-09-09 15:08:12 +00001614bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001615 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001616 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001617 const TemplateArgument &Arg = AL.getArgument();
1618
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001619 // Check template type parameter.
1620 if (Arg.getKind() != TemplateArgument::Type) {
1621 // C++ [temp.arg.type]p1:
1622 // A template-argument for a template-parameter which is a
1623 // type shall be a type-id.
1624
1625 // We have a template type parameter but the template argument
1626 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001627 SourceRange SR = AL.getSourceRange();
1628 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001629 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001630
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001631 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001632 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001633
John McCall0ad16662009-10-29 08:12:44 +00001634 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001635 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001636
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001637 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001638 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001639 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001640 return false;
1641}
1642
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001643/// \brief Substitute template arguments into the default template argument for
1644/// the given template type parameter.
1645///
1646/// \param SemaRef the semantic analysis object for which we are performing
1647/// the substitution.
1648///
1649/// \param Template the template that we are synthesizing template arguments
1650/// for.
1651///
1652/// \param TemplateLoc the location of the template name that started the
1653/// template-id we are checking.
1654///
1655/// \param RAngleLoc the location of the right angle bracket ('>') that
1656/// terminates the template-id.
1657///
1658/// \param Param the template template parameter whose default we are
1659/// substituting into.
1660///
1661/// \param Converted the list of template arguments provided for template
1662/// parameters that precede \p Param in the template parameter list.
1663///
1664/// \returns the substituted template argument, or NULL if an error occurred.
1665static DeclaratorInfo *
1666SubstDefaultTemplateArgument(Sema &SemaRef,
1667 TemplateDecl *Template,
1668 SourceLocation TemplateLoc,
1669 SourceLocation RAngleLoc,
1670 TemplateTypeParmDecl *Param,
1671 TemplateArgumentListBuilder &Converted) {
1672 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo();
1673
1674 // If the argument type is dependent, instantiate it now based
1675 // on the previously-computed template arguments.
1676 if (ArgType->getType()->isDependentType()) {
1677 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1678 /*TakeArgs=*/false);
1679
1680 MultiLevelTemplateArgumentList AllTemplateArgs
1681 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1682
1683 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1684 Template, Converted.getFlatArguments(),
1685 Converted.flatSize(),
1686 SourceRange(TemplateLoc, RAngleLoc));
1687
1688 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1689 Param->getDefaultArgumentLoc(),
1690 Param->getDeclName());
1691 }
1692
1693 return ArgType;
1694}
1695
1696/// \brief Substitute template arguments into the default template argument for
1697/// the given non-type template parameter.
1698///
1699/// \param SemaRef the semantic analysis object for which we are performing
1700/// the substitution.
1701///
1702/// \param Template the template that we are synthesizing template arguments
1703/// for.
1704///
1705/// \param TemplateLoc the location of the template name that started the
1706/// template-id we are checking.
1707///
1708/// \param RAngleLoc the location of the right angle bracket ('>') that
1709/// terminates the template-id.
1710///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001711/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001712/// substituting into.
1713///
1714/// \param Converted the list of template arguments provided for template
1715/// parameters that precede \p Param in the template parameter list.
1716///
1717/// \returns the substituted template argument, or NULL if an error occurred.
1718static Sema::OwningExprResult
1719SubstDefaultTemplateArgument(Sema &SemaRef,
1720 TemplateDecl *Template,
1721 SourceLocation TemplateLoc,
1722 SourceLocation RAngleLoc,
1723 NonTypeTemplateParmDecl *Param,
1724 TemplateArgumentListBuilder &Converted) {
1725 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1726 /*TakeArgs=*/false);
1727
1728 MultiLevelTemplateArgumentList AllTemplateArgs
1729 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1730
1731 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1732 Template, Converted.getFlatArguments(),
1733 Converted.flatSize(),
1734 SourceRange(TemplateLoc, RAngleLoc));
1735
1736 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1737}
1738
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001739/// \brief Substitute template arguments into the default template argument for
1740/// the given template template parameter.
1741///
1742/// \param SemaRef the semantic analysis object for which we are performing
1743/// the substitution.
1744///
1745/// \param Template the template that we are synthesizing template arguments
1746/// for.
1747///
1748/// \param TemplateLoc the location of the template name that started the
1749/// template-id we are checking.
1750///
1751/// \param RAngleLoc the location of the right angle bracket ('>') that
1752/// terminates the template-id.
1753///
1754/// \param Param the template template parameter whose default we are
1755/// substituting into.
1756///
1757/// \param Converted the list of template arguments provided for template
1758/// parameters that precede \p Param in the template parameter list.
1759///
1760/// \returns the substituted template argument, or NULL if an error occurred.
1761static TemplateName
1762SubstDefaultTemplateArgument(Sema &SemaRef,
1763 TemplateDecl *Template,
1764 SourceLocation TemplateLoc,
1765 SourceLocation RAngleLoc,
1766 TemplateTemplateParmDecl *Param,
1767 TemplateArgumentListBuilder &Converted) {
1768 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1769 /*TakeArgs=*/false);
1770
1771 MultiLevelTemplateArgumentList AllTemplateArgs
1772 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1773
1774 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1775 Template, Converted.getFlatArguments(),
1776 Converted.flatSize(),
1777 SourceRange(TemplateLoc, RAngleLoc));
1778
1779 return SemaRef.SubstTemplateName(
1780 Param->getDefaultArgument().getArgument().getAsTemplate(),
1781 Param->getDefaultArgument().getTemplateNameLoc(),
1782 AllTemplateArgs);
1783}
1784
Douglas Gregorda0fb532009-11-11 19:31:23 +00001785/// \brief Check that the given template argument corresponds to the given
1786/// template parameter.
1787bool Sema::CheckTemplateArgument(NamedDecl *Param,
1788 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001789 TemplateDecl *Template,
1790 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001791 SourceLocation RAngleLoc,
1792 TemplateArgumentListBuilder &Converted) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001793 // Check template type parameters.
1794 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001795 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001796
Douglas Gregoreebed722009-11-11 19:41:09 +00001797 // Check non-type template parameters.
1798 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001799 // Do substitution on the type of the non-type template parameter
1800 // with the template arguments we've seen thus far.
1801 QualType NTTPType = NTTP->getType();
1802 if (NTTPType->isDependentType()) {
1803 // Do substitution on the type of the non-type template parameter.
1804 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1805 NTTP, Converted.getFlatArguments(),
1806 Converted.flatSize(),
1807 SourceRange(TemplateLoc, RAngleLoc));
1808
1809 TemplateArgumentList TemplateArgs(Context, Converted,
1810 /*TakeArgs=*/false);
1811 NTTPType = SubstType(NTTPType,
1812 MultiLevelTemplateArgumentList(TemplateArgs),
1813 NTTP->getLocation(),
1814 NTTP->getDeclName());
1815 // If that worked, check the non-type template parameter type
1816 // for validity.
1817 if (!NTTPType.isNull())
1818 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1819 NTTP->getLocation());
1820 if (NTTPType.isNull())
1821 return true;
1822 }
1823
1824 switch (Arg.getArgument().getKind()) {
1825 case TemplateArgument::Null:
1826 assert(false && "Should never see a NULL template argument here");
1827 return true;
1828
1829 case TemplateArgument::Expression: {
1830 Expr *E = Arg.getArgument().getAsExpr();
1831 TemplateArgument Result;
1832 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1833 return true;
1834
1835 Converted.Append(Result);
1836 break;
1837 }
1838
1839 case TemplateArgument::Declaration:
1840 case TemplateArgument::Integral:
1841 // We've already checked this template argument, so just copy
1842 // it to the list of converted arguments.
1843 Converted.Append(Arg.getArgument());
1844 break;
1845
1846 case TemplateArgument::Template:
1847 // We were given a template template argument. It may not be ill-formed;
1848 // see below.
1849 if (DependentTemplateName *DTN
1850 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1851 // We have a template argument such as \c T::template X, which we
1852 // parsed as a template template argument. However, since we now
1853 // know that we need a non-type template argument, convert this
1854 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001855 Expr *E = DependentScopeDeclRefExpr::Create(Context,
1856 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00001857 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00001858 DTN->getIdentifier(),
1859 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00001860
1861 TemplateArgument Result;
1862 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
1863 return true;
1864
1865 Converted.Append(Result);
1866 break;
1867 }
1868
1869 // We have a template argument that actually does refer to a class
1870 // template, template alias, or template template parameter, and
1871 // therefore cannot be a non-type template argument.
1872 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
1873 << Arg.getSourceRange();
1874
1875 Diag(Param->getLocation(), diag::note_template_param_here);
1876 return true;
1877
1878 case TemplateArgument::Type: {
1879 // We have a non-type template parameter but the template
1880 // argument is a type.
1881
1882 // C++ [temp.arg]p2:
1883 // In a template-argument, an ambiguity between a type-id and
1884 // an expression is resolved to a type-id, regardless of the
1885 // form of the corresponding template-parameter.
1886 //
1887 // We warn specifically about this case, since it can be rather
1888 // confusing for users.
1889 QualType T = Arg.getArgument().getAsType();
1890 SourceRange SR = Arg.getSourceRange();
1891 if (T->isFunctionType())
1892 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
1893 else
1894 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
1895 Diag(Param->getLocation(), diag::note_template_param_here);
1896 return true;
1897 }
1898
1899 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001900 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001901 break;
1902 }
1903
1904 return false;
1905 }
1906
1907
1908 // Check template template parameters.
1909 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
1910
1911 // Substitute into the template parameter list of the template
1912 // template parameter, since previously-supplied template arguments
1913 // may appear within the template template parameter.
1914 {
1915 // Set up a template instantiation context.
1916 LocalInstantiationScope Scope(*this);
1917 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1918 TempParm, Converted.getFlatArguments(),
1919 Converted.flatSize(),
1920 SourceRange(TemplateLoc, RAngleLoc));
1921
1922 TemplateArgumentList TemplateArgs(Context, Converted,
1923 /*TakeArgs=*/false);
1924 TempParm = cast_or_null<TemplateTemplateParmDecl>(
1925 SubstDecl(TempParm, CurContext,
1926 MultiLevelTemplateArgumentList(TemplateArgs)));
1927 if (!TempParm)
1928 return true;
1929
1930 // FIXME: TempParam is leaked.
1931 }
1932
1933 switch (Arg.getArgument().getKind()) {
1934 case TemplateArgument::Null:
1935 assert(false && "Should never see a NULL template argument here");
1936 return true;
1937
1938 case TemplateArgument::Template:
1939 if (CheckTemplateArgument(TempParm, Arg))
1940 return true;
1941
1942 Converted.Append(Arg.getArgument());
1943 break;
1944
1945 case TemplateArgument::Expression:
1946 case TemplateArgument::Type:
1947 // We have a template template parameter but the template
1948 // argument does not refer to a template.
1949 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
1950 return true;
1951
1952 case TemplateArgument::Declaration:
1953 llvm::llvm_unreachable(
1954 "Declaration argument with template template parameter");
1955 break;
1956 case TemplateArgument::Integral:
1957 llvm::llvm_unreachable(
1958 "Integral argument with template template parameter");
1959 break;
1960
1961 case TemplateArgument::Pack:
Douglas Gregoreebed722009-11-11 19:41:09 +00001962 llvm::llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00001963 break;
1964 }
1965
1966 return false;
1967}
1968
Douglas Gregord32e0282009-02-09 23:23:08 +00001969/// \brief Check that the given template argument list is well-formed
1970/// for specializing the given template.
1971bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
1972 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001973 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001974 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001975 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001976 TemplateParameterList *Params = Template->getTemplateParameters();
1977 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00001978 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00001979 bool Invalid = false;
1980
John McCall6b51f282009-11-23 01:53:49 +00001981 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
1982
Mike Stump11289f42009-09-09 15:08:12 +00001983 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00001984 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00001985
Anders Carlsson15201f12009-06-13 02:08:00 +00001986 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00001987 (NumArgs < Params->getMinRequiredArguments() &&
1988 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00001989 // FIXME: point at either the first arg beyond what we can handle,
1990 // or the '>', depending on whether we have too many or too few
1991 // arguments.
1992 SourceRange Range;
1993 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00001994 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00001995 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
1996 << (NumArgs > NumParams)
1997 << (isa<ClassTemplateDecl>(Template)? 0 :
1998 isa<FunctionTemplateDecl>(Template)? 1 :
1999 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2000 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002001 Diag(Template->getLocation(), diag::note_template_decl_here)
2002 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002003 Invalid = true;
2004 }
Mike Stump11289f42009-09-09 15:08:12 +00002005
2006 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002007 // [...] The type and form of each template-argument specified in
2008 // a template-id shall match the type and form specified for the
2009 // corresponding parameter declared by the template in its
2010 // template-parameter-list.
2011 unsigned ArgIdx = 0;
2012 for (TemplateParameterList::iterator Param = Params->begin(),
2013 ParamEnd = Params->end();
2014 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002015 if (ArgIdx > NumArgs && PartialTemplateArgs)
2016 break;
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregoreebed722009-11-11 19:41:09 +00002018 // If we have a template parameter pack, check every remaining template
2019 // argument against that template parameter pack.
2020 if ((*Param)->isTemplateParameterPack()) {
2021 Converted.BeginPack();
2022 for (; ArgIdx < NumArgs; ++ArgIdx) {
2023 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2024 TemplateLoc, RAngleLoc, Converted)) {
2025 Invalid = true;
2026 break;
2027 }
2028 }
2029 Converted.EndPack();
2030 continue;
2031 }
2032
Douglas Gregor84d49a22009-11-11 21:54:23 +00002033 if (ArgIdx < NumArgs) {
2034 // Check the template argument we were given.
2035 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2036 TemplateLoc, RAngleLoc, Converted))
2037 return true;
2038
2039 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002040 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002041
Douglas Gregor84d49a22009-11-11 21:54:23 +00002042 // We have a default template argument that we will use.
2043 TemplateArgumentLoc Arg;
2044
2045 // Retrieve the default template argument from the template
2046 // parameter. For each kind of template parameter, we substitute the
2047 // template arguments provided thus far and any "outer" template arguments
2048 // (when the template parameter was part of a nested template) into
2049 // the default argument.
2050 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2051 if (!TTP->hasDefaultArgument()) {
2052 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2053 break;
2054 }
2055
2056 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this,
2057 Template,
2058 TemplateLoc,
2059 RAngleLoc,
2060 TTP,
2061 Converted);
2062 if (!ArgType)
2063 return true;
2064
2065 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2066 ArgType);
2067 } else if (NonTypeTemplateParmDecl *NTTP
2068 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2069 if (!NTTP->hasDefaultArgument()) {
2070 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2071 break;
2072 }
2073
2074 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2075 TemplateLoc,
2076 RAngleLoc,
2077 NTTP,
2078 Converted);
2079 if (E.isInvalid())
2080 return true;
2081
2082 Expr *Ex = E.takeAs<Expr>();
2083 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2084 } else {
2085 TemplateTemplateParmDecl *TempParm
2086 = cast<TemplateTemplateParmDecl>(*Param);
2087
2088 if (!TempParm->hasDefaultArgument()) {
2089 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2090 break;
2091 }
2092
2093 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2094 TemplateLoc,
2095 RAngleLoc,
2096 TempParm,
2097 Converted);
2098 if (Name.isNull())
2099 return true;
2100
2101 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2102 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2103 TempParm->getDefaultArgument().getTemplateNameLoc());
2104 }
2105
2106 // Introduce an instantiation record that describes where we are using
2107 // the default template argument.
2108 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2109 Converted.getFlatArguments(),
2110 Converted.flatSize(),
2111 SourceRange(TemplateLoc, RAngleLoc));
2112
2113 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002114 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002115 RAngleLoc, Converted))
2116 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002117 }
2118
2119 return Invalid;
2120}
2121
2122/// \brief Check a template argument against its corresponding
2123/// template type parameter.
2124///
2125/// This routine implements the semantics of C++ [temp.arg.type]. It
2126/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002127bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00002128 DeclaratorInfo *ArgInfo) {
2129 assert(ArgInfo && "invalid DeclaratorInfo");
2130 QualType Arg = ArgInfo->getType();
2131
Douglas Gregord32e0282009-02-09 23:23:08 +00002132 // C++ [temp.arg.type]p2:
2133 // A local type, a type with no linkage, an unnamed type or a type
2134 // compounded from any of these types shall not be used as a
2135 // template-argument for a template type-parameter.
2136 //
2137 // FIXME: Perform the recursive and no-linkage type checks.
2138 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002139 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002140 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002141 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002142 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002143 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2144 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2145 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2146 << QualType(Tag, 0) << SR;
2147 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002148 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002149 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2150 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002151 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2152 return true;
2153 }
2154
2155 return false;
2156}
2157
Douglas Gregorccb07762009-02-11 19:52:55 +00002158/// \brief Checks whether the given template argument is the address
2159/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002160bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
2161 NamedDecl *&Entity) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002162 bool Invalid = false;
2163
2164 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002165 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002166 Arg = Cast->getSubExpr();
2167
Sebastian Redl576fd422009-05-10 18:38:11 +00002168 // C++0x allows nullptr, and there's no further checking to be done for that.
2169 if (Arg->getType()->isNullPtrType())
2170 return false;
2171
Douglas Gregorccb07762009-02-11 19:52:55 +00002172 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002173 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002174 // A template-argument for a non-type, non-template
2175 // template-parameter shall be one of: [...]
2176 //
2177 // -- the address of an object or function with external
2178 // linkage, including function templates and function
2179 // template-ids but excluding non-static class members,
2180 // expressed as & id-expression where the & is optional if
2181 // the name refers to a function or array, or if the
2182 // corresponding template-parameter is a reference; or
2183 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002184
Douglas Gregorccb07762009-02-11 19:52:55 +00002185 // Ignore (and complain about) any excess parentheses.
2186 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2187 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002188 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002189 diag::err_template_arg_extra_parens)
2190 << Arg->getSourceRange();
2191 Invalid = true;
2192 }
2193
2194 Arg = Parens->getSubExpr();
2195 }
2196
2197 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2198 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2199 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2200 } else
2201 DRE = dyn_cast<DeclRefExpr>(Arg);
2202
2203 if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
Mike Stump11289f42009-09-09 15:08:12 +00002204 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002205 diag::err_template_arg_not_object_or_func_form)
2206 << Arg->getSourceRange();
2207
2208 // Cannot refer to non-static data members
2209 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
2210 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2211 << Field << Arg->getSourceRange();
2212
2213 // Cannot refer to non-static member functions
2214 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2215 if (!Method->isStatic())
Mike Stump11289f42009-09-09 15:08:12 +00002216 return Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002217 diag::err_template_arg_method)
2218 << Method << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002219
Douglas Gregorccb07762009-02-11 19:52:55 +00002220 // Functions must have external linkage.
2221 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2222 if (Func->getStorageClass() == FunctionDecl::Static) {
Mike Stump11289f42009-09-09 15:08:12 +00002223 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002224 diag::err_template_arg_function_not_extern)
2225 << Func << Arg->getSourceRange();
2226 Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2227 << true;
2228 return true;
2229 }
2230
2231 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002232 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002233 return Invalid;
2234 }
2235
2236 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2237 if (!Var->hasGlobalStorage()) {
Mike Stump11289f42009-09-09 15:08:12 +00002238 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002239 diag::err_template_arg_object_not_extern)
2240 << Var << Arg->getSourceRange();
2241 Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2242 << true;
2243 return true;
2244 }
2245
2246 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002247 Entity = Var;
Douglas Gregorccb07762009-02-11 19:52:55 +00002248 return Invalid;
2249 }
Mike Stump11289f42009-09-09 15:08:12 +00002250
Douglas Gregorccb07762009-02-11 19:52:55 +00002251 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002252 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002253 diag::err_template_arg_not_object_or_func)
2254 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002255 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002256 diag::note_template_arg_refers_here);
2257 return true;
2258}
2259
2260/// \brief Checks whether the given template argument is a pointer to
2261/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002262bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2263 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002264 bool Invalid = false;
2265
2266 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002267 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002268 Arg = Cast->getSubExpr();
2269
Sebastian Redl576fd422009-05-10 18:38:11 +00002270 // C++0x allows nullptr, and there's no further checking to be done for that.
2271 if (Arg->getType()->isNullPtrType())
2272 return false;
2273
Douglas Gregorccb07762009-02-11 19:52:55 +00002274 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002275 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002276 // A template-argument for a non-type, non-template
2277 // template-parameter shall be one of: [...]
2278 //
2279 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002280 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002281
2282 // Ignore (and complain about) any excess parentheses.
2283 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2284 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002285 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002286 diag::err_template_arg_extra_parens)
2287 << Arg->getSourceRange();
2288 Invalid = true;
2289 }
2290
2291 Arg = Parens->getSubExpr();
2292 }
2293
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002294 // A pointer-to-member constant written &Class::member.
2295 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002296 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2297 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2298 if (DRE && !DRE->getQualifier())
2299 DRE = 0;
2300 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002301 }
2302 // A constant of pointer-to-member type.
2303 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2304 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2305 if (VD->getType()->isMemberPointerType()) {
2306 if (isa<NonTypeTemplateParmDecl>(VD) ||
2307 (isa<VarDecl>(VD) &&
2308 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2309 if (Arg->isTypeDependent() || Arg->isValueDependent())
2310 Converted = TemplateArgument(Arg->Retain());
2311 else
2312 Converted = TemplateArgument(VD->getCanonicalDecl());
2313 return Invalid;
2314 }
2315 }
2316 }
2317
2318 DRE = 0;
2319 }
2320
Douglas Gregorccb07762009-02-11 19:52:55 +00002321 if (!DRE)
2322 return Diag(Arg->getSourceRange().getBegin(),
2323 diag::err_template_arg_not_pointer_to_member_form)
2324 << Arg->getSourceRange();
2325
2326 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2327 assert((isa<FieldDecl>(DRE->getDecl()) ||
2328 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2329 "Only non-static member pointers can make it here");
2330
2331 // Okay: this is the address of a non-static member, and therefore
2332 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002333 if (Arg->isTypeDependent() || Arg->isValueDependent())
2334 Converted = TemplateArgument(Arg->Retain());
2335 else
2336 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002337 return Invalid;
2338 }
2339
2340 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002341 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002342 diag::err_template_arg_not_pointer_to_member_form)
2343 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002344 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002345 diag::note_template_arg_refers_here);
2346 return true;
2347}
2348
Douglas Gregord32e0282009-02-09 23:23:08 +00002349/// \brief Check a template argument against its corresponding
2350/// non-type template parameter.
2351///
Douglas Gregor463421d2009-03-03 04:44:36 +00002352/// This routine implements the semantics of C++ [temp.arg.nontype].
2353/// It returns true if an error occurred, and false otherwise. \p
2354/// InstantiatedParamType is the type of the non-type template
2355/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002356///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002357/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002358bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002359 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002360 TemplateArgument &Converted) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002361 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2362
Douglas Gregor86560402009-02-10 23:36:10 +00002363 // If either the parameter has a dependent type or the argument is
2364 // type-dependent, there's nothing we can check now.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002365 // FIXME: Add template argument to Converted!
Douglas Gregorc40290e2009-03-09 23:48:35 +00002366 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2367 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002368 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002369 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002370 }
Douglas Gregor86560402009-02-10 23:36:10 +00002371
2372 // C++ [temp.arg.nontype]p5:
2373 // The following conversions are performed on each expression used
2374 // as a non-type template-argument. If a non-type
2375 // template-argument cannot be converted to the type of the
2376 // corresponding template-parameter then the program is
2377 // ill-formed.
2378 //
2379 // -- for a non-type template-parameter of integral or
2380 // enumeration type, integral promotions (4.5) and integral
2381 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002382 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002383 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002384 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002385 // C++ [temp.arg.nontype]p1:
2386 // A template-argument for a non-type, non-template
2387 // template-parameter shall be one of:
2388 //
2389 // -- an integral constant-expression of integral or enumeration
2390 // type; or
2391 // -- the name of a non-type template-parameter; or
2392 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002393 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002394 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002395 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002396 diag::err_template_arg_not_integral_or_enumeral)
2397 << ArgType << Arg->getSourceRange();
2398 Diag(Param->getLocation(), diag::note_template_param_here);
2399 return true;
2400 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002401 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002402 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2403 << ArgType << Arg->getSourceRange();
2404 return true;
2405 }
2406
2407 // FIXME: We need some way to more easily get the unqualified form
2408 // of the types without going all the way to the
2409 // canonical type.
2410 if (Context.getCanonicalType(ParamType).getCVRQualifiers())
2411 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
2412 if (Context.getCanonicalType(ArgType).getCVRQualifiers())
2413 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
2414
2415 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002416 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002417 // Okay: no conversion necessary
2418 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2419 !ParamType->isEnumeralType()) {
2420 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002421 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002422 } else {
2423 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002424 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002425 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002426 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002427 Diag(Param->getLocation(), diag::note_template_param_here);
2428 return true;
2429 }
2430
Douglas Gregor52aba872009-03-14 00:20:21 +00002431 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002432 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002433 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002434
2435 if (!Arg->isValueDependent()) {
2436 // Check that an unsigned parameter does not receive a negative
2437 // value.
2438 if (IntegerType->isUnsignedIntegerType()
2439 && (Value.isSigned() && Value.isNegative())) {
2440 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
2441 << Value.toString(10) << Param->getType()
2442 << Arg->getSourceRange();
2443 Diag(Param->getLocation(), diag::note_template_param_here);
2444 return true;
2445 }
2446
2447 // Check that we don't overflow the template parameter type.
2448 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2449 if (Value.getActiveBits() > AllowedBits) {
Mike Stump11289f42009-09-09 15:08:12 +00002450 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor52aba872009-03-14 00:20:21 +00002451 diag::err_template_arg_too_large)
2452 << Value.toString(10) << Param->getType()
2453 << Arg->getSourceRange();
2454 Diag(Param->getLocation(), diag::note_template_param_here);
2455 return true;
2456 }
2457
2458 if (Value.getBitWidth() != AllowedBits)
2459 Value.extOrTrunc(AllowedBits);
2460 Value.setIsSigned(IntegerType->isSignedIntegerType());
2461 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002462
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002463 // Add the value of this argument to the list of converted
2464 // arguments. We use the bitwidth and signedness of the template
2465 // parameter.
2466 if (Arg->isValueDependent()) {
2467 // The argument is value-dependent. Create a new
2468 // TemplateArgument with the converted expression.
2469 Converted = TemplateArgument(Arg);
2470 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002471 }
2472
John McCall0ad16662009-10-29 08:12:44 +00002473 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002474 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002475 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002476 return false;
2477 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002478
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002479 // Handle pointer-to-function, reference-to-function, and
2480 // pointer-to-member-function all in (roughly) the same way.
2481 if (// -- For a non-type template-parameter of type pointer to
2482 // function, only the function-to-pointer conversion (4.3) is
2483 // applied. If the template-argument represents a set of
2484 // overloaded functions (or a pointer to such), the matching
2485 // function is selected from the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002486 // In C++0x, any std::nullptr_t value can be converted.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002487 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002488 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002489 // -- For a non-type template-parameter of type reference to
2490 // function, no conversions apply. If the template-argument
2491 // represents a set of overloaded functions, the matching
2492 // function is selected from the set (13.4).
2493 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002494 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002495 // -- For a non-type template-parameter of type pointer to
2496 // member function, no conversions apply. If the
2497 // template-argument represents a set of overloaded member
2498 // functions, the matching member function is selected from
2499 // the set (13.4).
Sebastian Redl576fd422009-05-10 18:38:11 +00002500 // Again, C++0x allows a std::nullptr_t value.
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002501 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002502 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002503 ->isFunctionType())) {
Mike Stump11289f42009-09-09 15:08:12 +00002504 if (Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002505 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002506 // We don't have to do anything: the types already match.
Sebastian Redl576fd422009-05-10 18:38:11 +00002507 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
2508 ParamType->isMemberPointerType())) {
2509 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002510 if (ParamType->isMemberPointerType())
2511 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
2512 else
2513 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002514 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002515 ArgType = Context.getPointerType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002516 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Mike Stump11289f42009-09-09 15:08:12 +00002517 } else if (FunctionDecl *Fn
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002518 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002519 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2520 return true;
2521
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00002522 Arg = FixOverloadedFunctionReference(Arg, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002523 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002524 if (ArgType->isFunctionType() && ParamType->isPointerType()) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002525 ArgType = Context.getPointerType(Arg->getType());
Eli Friedman06ed2a52009-10-20 08:27:19 +00002526 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002527 }
2528 }
2529
Mike Stump11289f42009-09-09 15:08:12 +00002530 if (!Context.hasSameUnqualifiedType(ArgType,
Douglas Gregorccb07762009-02-11 19:52:55 +00002531 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002532 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002533 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002534 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002535 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002536 Diag(Param->getLocation(), diag::note_template_param_here);
2537 return true;
2538 }
Mike Stump11289f42009-09-09 15:08:12 +00002539
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002540 if (ParamType->isMemberPointerType())
2541 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Mike Stump11289f42009-09-09 15:08:12 +00002542
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002543 NamedDecl *Entity = 0;
2544 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2545 return true;
2546
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002547 if (Entity)
2548 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002549 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002550 return false;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002551 }
2552
Chris Lattner696197c2009-02-20 21:37:53 +00002553 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002554 // -- for a non-type template-parameter of type pointer to
2555 // object, qualification conversions (4.4) and the
2556 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002557 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002558 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002559 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002560
Sebastian Redl576fd422009-05-10 18:38:11 +00002561 if (ArgType->isNullPtrType()) {
2562 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002563 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast);
Sebastian Redl576fd422009-05-10 18:38:11 +00002564 } else if (ArgType->isArrayType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002565 ArgType = Context.getArrayDecayedType(ArgType);
Eli Friedman06ed2a52009-10-20 08:27:19 +00002566 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregora9faa442009-02-11 00:44:29 +00002567 }
Sebastian Redl576fd422009-05-10 18:38:11 +00002568
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002569 if (IsQualificationConversion(ArgType, ParamType)) {
2570 ArgType = ParamType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002571 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002572 }
Mike Stump11289f42009-09-09 15:08:12 +00002573
Douglas Gregor1515f762009-02-11 18:22:40 +00002574 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002575 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002576 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002577 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002578 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002579 Diag(Param->getLocation(), diag::note_template_param_here);
2580 return true;
2581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002583 NamedDecl *Entity = 0;
2584 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2585 return true;
2586
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002587 if (Entity)
2588 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002589 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002590 return false;
Douglas Gregora9faa442009-02-11 00:44:29 +00002591 }
Mike Stump11289f42009-09-09 15:08:12 +00002592
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002593 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002594 // -- For a non-type template-parameter of type reference to
2595 // object, no conversions apply. The type referred to by the
2596 // reference may be more cv-qualified than the (otherwise
2597 // identical) type of the template-argument. The
2598 // template-parameter is bound directly to the
2599 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002600 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002601 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002602
Douglas Gregor1515f762009-02-11 18:22:40 +00002603 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002604 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002605 diag::err_template_arg_no_ref_bind)
Douglas Gregor463421d2009-03-03 04:44:36 +00002606 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002607 << Arg->getSourceRange();
2608 Diag(Param->getLocation(), diag::note_template_param_here);
2609 return true;
2610 }
2611
Mike Stump11289f42009-09-09 15:08:12 +00002612 unsigned ParamQuals
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002613 = Context.getCanonicalType(ParamType).getCVRQualifiers();
2614 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00002615
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002616 if ((ParamQuals | ArgQuals) != ParamQuals) {
2617 Diag(Arg->getSourceRange().getBegin(),
2618 diag::err_template_arg_ref_bind_ignores_quals)
Douglas Gregor463421d2009-03-03 04:44:36 +00002619 << InstantiatedParamType << Arg->getType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002620 << Arg->getSourceRange();
2621 Diag(Param->getLocation(), diag::note_template_param_here);
2622 return true;
2623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002625 NamedDecl *Entity = 0;
2626 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
2627 return true;
2628
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002629 Entity = cast<NamedDecl>(Entity->getCanonicalDecl());
John McCall0ad16662009-10-29 08:12:44 +00002630 Converted = TemplateArgument(Entity);
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002631 return false;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002632 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002633
2634 // -- For a non-type template-parameter of type pointer to data
2635 // member, qualification conversions (4.4) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002636 // C++0x allows std::nullptr_t values.
Douglas Gregor0e558532009-02-11 16:16:59 +00002637 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2638
Douglas Gregor1515f762009-02-11 18:22:40 +00002639 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002640 // Types match exactly: nothing more to do here.
Sebastian Redl576fd422009-05-10 18:38:11 +00002641 } else if (ArgType->isNullPtrType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002642 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer);
Douglas Gregor0e558532009-02-11 16:16:59 +00002643 } else if (IsQualificationConversion(ArgType, ParamType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00002644 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp);
Douglas Gregor0e558532009-02-11 16:16:59 +00002645 } else {
2646 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002647 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002648 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002649 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002650 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002651 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002652 }
2653
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002654 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002655}
2656
2657/// \brief Check a template argument against its corresponding
2658/// template template parameter.
2659///
2660/// This routine implements the semantics of C++ [temp.arg.template].
2661/// It returns true if an error occurred, and false otherwise.
2662bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002663 const TemplateArgumentLoc &Arg) {
2664 TemplateName Name = Arg.getArgument().getAsTemplate();
2665 TemplateDecl *Template = Name.getAsTemplateDecl();
2666 if (!Template) {
2667 // Any dependent template name is fine.
2668 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2669 return false;
2670 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002671
2672 // C++ [temp.arg.template]p1:
2673 // A template-argument for a template template-parameter shall be
2674 // the name of a class template, expressed as id-expression. Only
2675 // primary class templates are considered when matching the
2676 // template template argument with the corresponding parameter;
2677 // partial specializations are not considered even if their
2678 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002679 //
2680 // Note that we also allow template template parameters here, which
2681 // will happen when we are dealing with, e.g., class template
2682 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002683 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002684 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002685 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002686 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002687 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002688 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002689 << Template;
2690 }
2691
2692 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2693 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002694 true,
2695 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002696 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002697}
2698
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002699/// \brief Determine whether the given template parameter lists are
2700/// equivalent.
2701///
Mike Stump11289f42009-09-09 15:08:12 +00002702/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002703/// source code as part of a new template declaration.
2704///
2705/// \param Old The old template parameter list, typically found via
2706/// name lookup of the template declared with this template parameter
2707/// list.
2708///
2709/// \param Complain If true, this routine will produce a diagnostic if
2710/// the template parameter lists are not equivalent.
2711///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002712/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00002713///
2714/// \param TemplateArgLoc If this source location is valid, then we
2715/// are actually checking the template parameter list of a template
2716/// argument (New) against the template parameter list of its
2717/// corresponding template template parameter (Old). We produce
2718/// slightly different diagnostics in this scenario.
2719///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002720/// \returns True if the template parameter lists are equal, false
2721/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002722bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002723Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
2724 TemplateParameterList *Old,
2725 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002726 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002727 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002728 if (Old->size() != New->size()) {
2729 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002730 unsigned NextDiag = diag::err_template_param_list_different_arity;
2731 if (TemplateArgLoc.isValid()) {
2732 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2733 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00002734 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002735 Diag(New->getTemplateLoc(), NextDiag)
2736 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002737 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002738 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002739 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002740 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002741 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
2742 }
2743
2744 return false;
2745 }
2746
2747 for (TemplateParameterList::iterator OldParm = Old->begin(),
2748 OldParmEnd = Old->end(), NewParm = New->begin();
2749 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
2750 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00002751 if (Complain) {
2752 unsigned NextDiag = diag::err_template_param_different_kind;
2753 if (TemplateArgLoc.isValid()) {
2754 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
2755 NextDiag = diag::note_template_param_different_kind;
2756 }
2757 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002758 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00002759 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002760 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00002761 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002762 return false;
2763 }
2764
2765 if (isa<TemplateTypeParmDecl>(*OldParm)) {
2766 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00002767 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00002768 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002769 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
2770 // The types of non-type template parameters must agree.
2771 NonTypeTemplateParmDecl *NewNTTP
2772 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002773
2774 // If we are matching a template template argument to a template
2775 // template parameter and one of the non-type template parameter types
2776 // is dependent, then we must wait until template instantiation time
2777 // to actually compare the arguments.
2778 if (Kind == TPL_TemplateTemplateArgumentMatch &&
2779 (OldNTTP->getType()->isDependentType() ||
2780 NewNTTP->getType()->isDependentType()))
2781 continue;
2782
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002783 if (Context.getCanonicalType(OldNTTP->getType()) !=
2784 Context.getCanonicalType(NewNTTP->getType())) {
2785 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00002786 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
2787 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00002788 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00002789 diag::err_template_arg_template_params_mismatch);
2790 NextDiag = diag::note_template_nontype_parm_different_type;
2791 }
2792 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002793 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002794 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00002795 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002796 diag::note_template_nontype_parm_prev_declaration)
2797 << OldNTTP->getType();
2798 }
2799 return false;
2800 }
2801 } else {
2802 // The template parameter lists of template template
2803 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00002804 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002805 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00002806 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002807 = cast<TemplateTemplateParmDecl>(*OldParm);
2808 TemplateTemplateParmDecl *NewTTP
2809 = cast<TemplateTemplateParmDecl>(*NewParm);
2810 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
2811 OldTTP->getTemplateParameters(),
2812 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002813 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00002814 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002815 return false;
2816 }
2817 }
2818
2819 return true;
2820}
2821
2822/// \brief Check whether a template can be declared within this scope.
2823///
2824/// If the template declaration is valid in this scope, returns
2825/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00002826bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002827Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002828 // Find the nearest enclosing declaration scope.
2829 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2830 (S->getFlags() & Scope::TemplateParamScope) != 0)
2831 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002832
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002833 // C++ [temp]p2:
2834 // A template-declaration can appear only as a namespace scope or
2835 // class scope declaration.
2836 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002837 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
2838 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00002839 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002840 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002841
Eli Friedmandfbd0c42009-07-31 01:43:05 +00002842 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002843 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002844
2845 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
2846 return false;
2847
Mike Stump11289f42009-09-09 15:08:12 +00002848 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00002849 diag::err_template_outside_namespace_or_class_scope)
2850 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002851}
Douglas Gregor67a65642009-02-17 23:15:12 +00002852
Douglas Gregor54888652009-10-07 00:13:32 +00002853/// \brief Determine what kind of template specialization the given declaration
2854/// is.
2855static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
2856 if (!D)
2857 return TSK_Undeclared;
2858
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002859 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
2860 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00002861 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2862 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00002863 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2864 return Var->getTemplateSpecializationKind();
2865
Douglas Gregor54888652009-10-07 00:13:32 +00002866 return TSK_Undeclared;
2867}
2868
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002869/// \brief Check whether a specialization is well-formed in the current
2870/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00002871///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002872/// This routine determines whether a template specialization can be declared
2873/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00002874///
2875/// \param S the semantic analysis object for which this check is being
2876/// performed.
2877///
2878/// \param Specialized the entity being specialized or instantiated, which
2879/// may be a kind of template (class template, function template, etc.) or
2880/// a member of a class template (member function, static data member,
2881/// member class).
2882///
2883/// \param PrevDecl the previous declaration of this entity, if any.
2884///
2885/// \param Loc the location of the explicit specialization or instantiation of
2886/// this entity.
2887///
2888/// \param IsPartialSpecialization whether this is a partial specialization of
2889/// a class template.
2890///
Douglas Gregor54888652009-10-07 00:13:32 +00002891/// \returns true if there was an error that we cannot recover from, false
2892/// otherwise.
2893static bool CheckTemplateSpecializationScope(Sema &S,
2894 NamedDecl *Specialized,
2895 NamedDecl *PrevDecl,
2896 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002897 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00002898 // Keep these "kind" numbers in sync with the %select statements in the
2899 // various diagnostics emitted by this routine.
2900 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002901 bool isTemplateSpecialization = false;
2902 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002903 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002904 isTemplateSpecialization = true;
2905 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00002906 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00002907 isTemplateSpecialization = true;
2908 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00002909 EntityKind = 3;
2910 else if (isa<VarDecl>(Specialized))
2911 EntityKind = 4;
2912 else if (isa<RecordDecl>(Specialized))
2913 EntityKind = 5;
2914 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002915 S.Diag(Loc, diag::err_template_spec_unknown_kind);
2916 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00002917 return true;
2918 }
2919
Douglas Gregorf47b9112009-02-25 22:02:03 +00002920 // C++ [temp.expl.spec]p2:
2921 // An explicit specialization shall be declared in the namespace
2922 // of which the template is a member, or, for member templates, in
2923 // the namespace of which the enclosing class or enclosing class
2924 // template is a member. An explicit specialization of a member
2925 // function, member class or static data member of a class
2926 // template shall be declared in the namespace of which the class
2927 // template is a member. Such a declaration may also be a
2928 // definition. If the declaration is not a definition, the
2929 // specialization may be defined later in the name- space in which
2930 // the explicit specialization was declared, or in a namespace
2931 // that encloses the one in which the explicit specialization was
2932 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00002933 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
2934 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002935 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002936 return true;
2937 }
Douglas Gregore4b05162009-10-07 17:21:34 +00002938
Douglas Gregor40fb7442009-10-07 17:30:37 +00002939 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
2940 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002941 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00002942 return true;
2943 }
2944
Douglas Gregore4b05162009-10-07 17:21:34 +00002945 // C++ [temp.class.spec]p6:
2946 // A class template partial specialization may be declared or redeclared
2947 // in any namespace scope in which its definition may be defined (14.5.1
2948 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00002949 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00002950 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00002951 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00002952 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002953 if ((!PrevDecl ||
2954 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
2955 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
2956 // There is no prior declaration of this entity, so this
2957 // specialization must be in the same context as the template
2958 // itself.
2959 if (!DC->Equals(SpecializedContext)) {
2960 if (isa<TranslationUnitDecl>(SpecializedContext))
2961 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
2962 << EntityKind << Specialized;
2963 else if (isa<NamespaceDecl>(SpecializedContext))
2964 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
2965 << EntityKind << Specialized
2966 << cast<NamedDecl>(SpecializedContext);
2967
2968 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
2969 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00002970 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00002971 }
Douglas Gregor54888652009-10-07 00:13:32 +00002972
2973 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002974 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00002975 // Note that HandleDeclarator() performs this check for explicit
2976 // specializations of function templates, static data members, and member
2977 // functions, so we skip the check here for those kinds of entities.
2978 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00002979 // Should we refactor that check, so that it occurs later?
2980 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002981 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
2982 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00002983 if (isa<TranslationUnitDecl>(SpecializedContext))
2984 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
2985 << EntityKind << Specialized;
2986 else if (isa<NamespaceDecl>(SpecializedContext))
2987 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
2988 << EntityKind << Specialized
2989 << cast<NamedDecl>(SpecializedContext);
2990
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00002991 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00002992 }
Douglas Gregor54888652009-10-07 00:13:32 +00002993
2994 // FIXME: check for specialization-after-instantiation errors and such.
2995
Douglas Gregorf47b9112009-02-25 22:02:03 +00002996 return false;
2997}
Douglas Gregor54888652009-10-07 00:13:32 +00002998
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00002999/// \brief Check the non-type template arguments of a class template
3000/// partial specialization according to C++ [temp.class.spec]p9.
3001///
Douglas Gregor09a30232009-06-12 22:08:06 +00003002/// \param TemplateParams the template parameters of the primary class
3003/// template.
3004///
3005/// \param TemplateArg the template arguments of the class template
3006/// partial specialization.
3007///
3008/// \param MirrorsPrimaryTemplate will be set true if the class
3009/// template partial specialization arguments are identical to the
3010/// implicit template arguments of the primary template. This is not
3011/// necessarily an error (C++0x), and it is left to the caller to diagnose
3012/// this condition when it is an error.
3013///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003014/// \returns true if there was an error, false otherwise.
3015bool Sema::CheckClassTemplatePartialSpecializationArgs(
3016 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003017 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003018 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003019 // FIXME: the interface to this function will have to change to
3020 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003021 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003022
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003023 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003024
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003025 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003026 // Determine whether the template argument list of the partial
3027 // specialization is identical to the implicit argument list of
3028 // the primary template. The caller may need to diagnostic this as
3029 // an error per C++ [temp.class.spec]p9b3.
3030 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003031 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003032 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3033 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003034 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003035 MirrorsPrimaryTemplate = false;
3036 } else if (TemplateTemplateParmDecl *TTP
3037 = dyn_cast<TemplateTemplateParmDecl>(
3038 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003039 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003040 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003041 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003042 if (!ArgDecl ||
3043 ArgDecl->getIndex() != TTP->getIndex() ||
3044 ArgDecl->getDepth() != TTP->getDepth())
3045 MirrorsPrimaryTemplate = false;
3046 }
3047 }
3048
Mike Stump11289f42009-09-09 15:08:12 +00003049 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003050 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003051 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003052 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003053 }
3054
Anders Carlsson40c1d492009-06-13 18:20:51 +00003055 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003056 if (!ArgExpr) {
3057 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003058 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003059 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003060
3061 // C++ [temp.class.spec]p8:
3062 // A non-type argument is non-specialized if it is the name of a
3063 // non-type parameter. All other non-type arguments are
3064 // specialized.
3065 //
3066 // Below, we check the two conditions that only apply to
3067 // specialized non-type arguments, so skip any non-specialized
3068 // arguments.
3069 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003070 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003071 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003072 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003073 (Param->getIndex() != NTTP->getIndex() ||
3074 Param->getDepth() != NTTP->getDepth()))
3075 MirrorsPrimaryTemplate = false;
3076
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003077 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003078 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003079
3080 // C++ [temp.class.spec]p9:
3081 // Within the argument list of a class template partial
3082 // specialization, the following restrictions apply:
3083 // -- A partially specialized non-type argument expression
3084 // shall not involve a template parameter of the partial
3085 // specialization except when the argument expression is a
3086 // simple identifier.
3087 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003088 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003089 diag::err_dependent_non_type_arg_in_partial_spec)
3090 << ArgExpr->getSourceRange();
3091 return true;
3092 }
3093
3094 // -- The type of a template parameter corresponding to a
3095 // specialized non-type argument shall not be dependent on a
3096 // parameter of the specialization.
3097 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003098 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003099 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3100 << Param->getType()
3101 << ArgExpr->getSourceRange();
3102 Diag(Param->getLocation(), diag::note_template_param_here);
3103 return true;
3104 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003105
3106 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003107 }
3108
3109 return false;
3110}
3111
Douglas Gregorc08f4892009-03-25 00:13:59 +00003112Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003113Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3114 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003115 SourceLocation KWLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +00003116 const CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003117 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003118 SourceLocation TemplateNameLoc,
3119 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003120 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003121 SourceLocation RAngleLoc,
3122 AttributeList *Attr,
3123 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003124 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003125
Douglas Gregor67a65642009-02-17 23:15:12 +00003126 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003127 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003128 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003129 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3130
3131 if (!ClassTemplate) {
3132 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3133 << (Name.getAsTemplateDecl() &&
3134 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3135 return true;
3136 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003137
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003138 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003139 bool isPartialSpecialization = false;
3140
Douglas Gregorf47b9112009-02-25 22:02:03 +00003141 // Check the validity of the template headers that introduce this
3142 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003143 // FIXME: We probably shouldn't complain about these headers for
3144 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003145 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003146 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3147 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003148 TemplateParameterLists.size(),
3149 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003150 if (TemplateParams && TemplateParams->size() > 0) {
3151 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003152
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003153 // C++ [temp.class.spec]p10:
3154 // The template parameter list of a specialization shall not
3155 // contain default template argument values.
3156 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3157 Decl *Param = TemplateParams->getParam(I);
3158 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3159 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003160 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003161 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003162 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003163 }
3164 } else if (NonTypeTemplateParmDecl *NTTP
3165 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3166 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003167 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003168 diag::err_default_arg_in_partial_spec)
3169 << DefArg->getSourceRange();
3170 NTTP->setDefaultArgument(0);
3171 DefArg->Destroy(Context);
3172 }
3173 } else {
3174 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003175 if (TTP->hasDefaultArgument()) {
3176 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003177 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003178 << TTP->getDefaultArgument().getSourceRange();
3179 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003180 }
3181 }
3182 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003183 } else if (TemplateParams) {
3184 if (TUK == TUK_Friend)
3185 Diag(KWLoc, diag::err_template_spec_friend)
3186 << CodeModificationHint::CreateRemoval(
3187 SourceRange(TemplateParams->getTemplateLoc(),
3188 TemplateParams->getRAngleLoc()))
3189 << SourceRange(LAngleLoc, RAngleLoc);
3190 else
3191 isExplicitSpecialization = true;
3192 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003193 Diag(KWLoc, diag::err_template_spec_needs_header)
3194 << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003195 isExplicitSpecialization = true;
3196 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003197
Douglas Gregor67a65642009-02-17 23:15:12 +00003198 // Check that the specialization uses the same tag kind as the
3199 // original template.
3200 TagDecl::TagKind Kind;
3201 switch (TagSpec) {
3202 default: assert(0 && "Unknown tag type!");
3203 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3204 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3205 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3206 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003207 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003208 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003209 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003210 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003211 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00003212 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003213 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003214 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003215 diag::note_previous_use);
3216 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3217 }
3218
Douglas Gregorc40290e2009-03-09 23:48:35 +00003219 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003220 TemplateArgumentListInfo TemplateArgs;
3221 TemplateArgs.setLAngleLoc(LAngleLoc);
3222 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003223 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003224
Douglas Gregor67a65642009-02-17 23:15:12 +00003225 // Check that the template argument list is well-formed for this
3226 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003227 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3228 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003229 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3230 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003231 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003232
Mike Stump11289f42009-09-09 15:08:12 +00003233 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003234 ClassTemplate->getTemplateParameters()->size()) &&
3235 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003236
Douglas Gregor2373c592009-05-31 09:31:02 +00003237 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003238 // corresponds to these arguments.
3239 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003240 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003241 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003242 if (CheckClassTemplatePartialSpecializationArgs(
3243 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003244 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003245 return true;
3246
Douglas Gregor09a30232009-06-12 22:08:06 +00003247 if (MirrorsPrimaryTemplate) {
3248 // C++ [temp.class.spec]p9b3:
3249 //
Mike Stump11289f42009-09-09 15:08:12 +00003250 // -- The argument list of the specialization shall not be identical
3251 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003252 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003253 << (TUK == TUK_Definition)
Mike Stump11289f42009-09-09 15:08:12 +00003254 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
Douglas Gregor09a30232009-06-12 22:08:06 +00003255 RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003256 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003257 ClassTemplate->getIdentifier(),
3258 TemplateNameLoc,
3259 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003260 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003261 AS_none);
3262 }
3263
Douglas Gregor2208a292009-09-26 20:57:03 +00003264 // FIXME: Diagnose friend partial specializations
3265
Douglas Gregor2373c592009-05-31 09:31:02 +00003266 // FIXME: Template parameter list matters, too
Mike Stump11289f42009-09-09 15:08:12 +00003267 ClassTemplatePartialSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003268 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003269 Converted.flatSize(),
3270 Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003271 } else
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003272 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003273 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003274 Converted.flatSize(),
3275 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003276 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003277 ClassTemplateSpecializationDecl *PrevDecl = 0;
3278
3279 if (isPartialSpecialization)
3280 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003281 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003282 InsertPos);
3283 else
3284 PrevDecl
3285 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003286
3287 ClassTemplateSpecializationDecl *Specialization = 0;
3288
Douglas Gregorf47b9112009-02-25 22:02:03 +00003289 // Check whether we can declare a class template specialization in
3290 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003291 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003292 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003293 TemplateNameLoc,
3294 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003295 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003296
Douglas Gregor15301382009-07-30 17:40:51 +00003297 // The canonical type
3298 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003299 if (PrevDecl &&
3300 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3301 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003302 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003303 // arguments was referenced but not declared, or we're only
3304 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003305 // declaration node as our own, updating its source location to
3306 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003307 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003308 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003309 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003310 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003311 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003312 // Build the canonical type that describes the converted template
3313 // arguments of the class template partial specialization.
3314 CanonType = Context.getTemplateSpecializationType(
3315 TemplateName(ClassTemplate),
3316 Converted.getFlatArguments(),
3317 Converted.flatSize());
3318
Douglas Gregor2373c592009-05-31 09:31:02 +00003319 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003320 ClassTemplatePartialSpecializationDecl *PrevPartial
3321 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003322 ClassTemplatePartialSpecializationDecl *Partial
3323 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003324 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003325 TemplateNameLoc,
3326 TemplateParams,
3327 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003328 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003329 TemplateArgs,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003330 PrevPartial);
Douglas Gregor2373c592009-05-31 09:31:02 +00003331
3332 if (PrevPartial) {
3333 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3334 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3335 } else {
3336 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3337 }
3338 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003339
Douglas Gregor21610382009-10-29 00:04:11 +00003340 // If we are providing an explicit specialization of a member class
3341 // template specialization, make a note of that.
3342 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3343 PrevPartial->setMemberSpecialization();
3344
Douglas Gregor91772d12009-06-13 00:26:55 +00003345 // Check that all of the template parameters of the class template
3346 // partial specialization are deducible from the template
3347 // arguments. If not, this class template partial specialization
3348 // will never be used.
3349 llvm::SmallVector<bool, 8> DeducibleParams;
3350 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003351 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003352 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003353 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003354 unsigned NumNonDeducible = 0;
3355 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3356 if (!DeducibleParams[I])
3357 ++NumNonDeducible;
3358
3359 if (NumNonDeducible) {
3360 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3361 << (NumNonDeducible > 1)
3362 << SourceRange(TemplateNameLoc, RAngleLoc);
3363 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3364 if (!DeducibleParams[I]) {
3365 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3366 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003367 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003368 diag::note_partial_spec_unused_parameter)
3369 << Param->getDeclName();
3370 else
Mike Stump11289f42009-09-09 15:08:12 +00003371 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003372 diag::note_partial_spec_unused_parameter)
3373 << std::string("<anonymous>");
3374 }
3375 }
3376 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003377 } else {
3378 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003379 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003380 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003381 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003382 ClassTemplate->getDeclContext(),
3383 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003384 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003385 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003386 PrevDecl);
3387
3388 if (PrevDecl) {
3389 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3390 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3391 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003392 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003393 InsertPos);
3394 }
Douglas Gregor15301382009-07-30 17:40:51 +00003395
3396 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003397 }
3398
Douglas Gregor06db9f52009-10-12 20:18:28 +00003399 // C++ [temp.expl.spec]p6:
3400 // If a template, a member template or the member of a class template is
3401 // explicitly specialized then that specialization shall be declared
3402 // before the first use of that specialization that would cause an implicit
3403 // instantiation to take place, in every translation unit in which such a
3404 // use occurs; no diagnostic is required.
3405 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3406 SourceRange Range(TemplateNameLoc, RAngleLoc);
3407 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3408 << Context.getTypeDeclType(Specialization) << Range;
3409
3410 Diag(PrevDecl->getPointOfInstantiation(),
3411 diag::note_instantiation_required_here)
3412 << (PrevDecl->getTemplateSpecializationKind()
3413 != TSK_ImplicitInstantiation);
3414 return true;
3415 }
3416
Douglas Gregor2208a292009-09-26 20:57:03 +00003417 // If this is not a friend, note that this is an explicit specialization.
3418 if (TUK != TUK_Friend)
3419 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003420
3421 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003422 if (TUK == TUK_Definition) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003423 if (RecordDecl *Def = Specialization->getDefinition(Context)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003424 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003425 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003426 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003427 Diag(Def->getLocation(), diag::note_previous_definition);
3428 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003429 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003430 }
3431 }
3432
Douglas Gregord56a91e2009-02-26 22:19:44 +00003433 // Build the fully-sugared type for this class template
3434 // specialization as the user wrote in the specialization
3435 // itself. This means that we'll pretty-print the type retrieved
3436 // from the specialization's declaration the way that the user
3437 // actually wrote the specialization, rather than formatting the
3438 // name based on the "canonical" representation used to store the
3439 // template arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003440 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00003441 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003442 if (TUK != TUK_Friend)
3443 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003444 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003445
Douglas Gregor1e249f82009-02-25 22:18:32 +00003446 // C++ [temp.expl.spec]p9:
3447 // A template explicit specialization is in the scope of the
3448 // namespace in which the template was defined.
3449 //
3450 // We actually implement this paragraph where we set the semantic
3451 // context (in the creation of the ClassTemplateSpecializationDecl),
3452 // but we also maintain the lexical context where the actual
3453 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003454 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003455
Douglas Gregor67a65642009-02-17 23:15:12 +00003456 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003457 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003458 Specialization->startDefinition();
3459
Douglas Gregor2208a292009-09-26 20:57:03 +00003460 if (TUK == TUK_Friend) {
3461 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3462 TemplateNameLoc,
3463 WrittenTy.getTypePtr(),
3464 /*FIXME:*/KWLoc);
3465 Friend->setAccess(AS_public);
3466 CurContext->addDecl(Friend);
3467 } else {
3468 // Add the specialization into its lexical context, so that it can
3469 // be seen when iterating through the list of declarations in that
3470 // context. However, specializations are not found by name lookup.
3471 CurContext->addDecl(Specialization);
3472 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003473 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003474}
Douglas Gregor333489b2009-03-27 23:10:48 +00003475
Mike Stump11289f42009-09-09 15:08:12 +00003476Sema::DeclPtrTy
3477Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003478 MultiTemplateParamsArg TemplateParameterLists,
3479 Declarator &D) {
3480 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3481}
3482
Mike Stump11289f42009-09-09 15:08:12 +00003483Sema::DeclPtrTy
3484Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003485 MultiTemplateParamsArg TemplateParameterLists,
3486 Declarator &D) {
3487 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3488 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3489 "Not a function declarator!");
3490 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003491
Douglas Gregor17a7c122009-06-24 00:54:41 +00003492 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003493 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003494 }
Mike Stump11289f42009-09-09 15:08:12 +00003495
Douglas Gregor17a7c122009-06-24 00:54:41 +00003496 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003497
3498 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003499 move(TemplateParameterLists),
3500 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003501 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003502 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003503 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003504 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003505 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3506 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003507 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003508}
3509
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003510/// \brief Diagnose cases where we have an explicit template specialization
3511/// before/after an explicit template instantiation, producing diagnostics
3512/// for those cases where they are required and determining whether the
3513/// new specialization/instantiation will have any effect.
3514///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003515/// \param NewLoc the location of the new explicit specialization or
3516/// instantiation.
3517///
3518/// \param NewTSK the kind of the new explicit specialization or instantiation.
3519///
3520/// \param PrevDecl the previous declaration of the entity.
3521///
3522/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3523///
3524/// \param PrevPointOfInstantiation if valid, indicates where the previus
3525/// declaration was instantiated (either implicitly or explicitly).
3526///
3527/// \param SuppressNew will be set to true to indicate that the new
3528/// specialization or instantiation has no effect and should be ignored.
3529///
3530/// \returns true if there was an error that should prevent the introduction of
3531/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003532bool
3533Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3534 TemplateSpecializationKind NewTSK,
3535 NamedDecl *PrevDecl,
3536 TemplateSpecializationKind PrevTSK,
3537 SourceLocation PrevPointOfInstantiation,
3538 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003539 SuppressNew = false;
3540
3541 switch (NewTSK) {
3542 case TSK_Undeclared:
3543 case TSK_ImplicitInstantiation:
3544 assert(false && "Don't check implicit instantiations here");
3545 return false;
3546
3547 case TSK_ExplicitSpecialization:
3548 switch (PrevTSK) {
3549 case TSK_Undeclared:
3550 case TSK_ExplicitSpecialization:
3551 // Okay, we're just specializing something that is either already
3552 // explicitly specialized or has merely been mentioned without any
3553 // instantiation.
3554 return false;
3555
3556 case TSK_ImplicitInstantiation:
3557 if (PrevPointOfInstantiation.isInvalid()) {
3558 // The declaration itself has not actually been instantiated, so it is
3559 // still okay to specialize it.
3560 return false;
3561 }
3562 // Fall through
3563
3564 case TSK_ExplicitInstantiationDeclaration:
3565 case TSK_ExplicitInstantiationDefinition:
3566 assert((PrevTSK == TSK_ImplicitInstantiation ||
3567 PrevPointOfInstantiation.isValid()) &&
3568 "Explicit instantiation without point of instantiation?");
3569
3570 // C++ [temp.expl.spec]p6:
3571 // If a template, a member template or the member of a class template
3572 // is explicitly specialized then that specialization shall be declared
3573 // before the first use of that specialization that would cause an
3574 // implicit instantiation to take place, in every translation unit in
3575 // which such a use occurs; no diagnostic is required.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003576 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003577 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003578 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003579 << (PrevTSK != TSK_ImplicitInstantiation);
3580
3581 return true;
3582 }
3583 break;
3584
3585 case TSK_ExplicitInstantiationDeclaration:
3586 switch (PrevTSK) {
3587 case TSK_ExplicitInstantiationDeclaration:
3588 // This explicit instantiation declaration is redundant (that's okay).
3589 SuppressNew = true;
3590 return false;
3591
3592 case TSK_Undeclared:
3593 case TSK_ImplicitInstantiation:
3594 // We're explicitly instantiating something that may have already been
3595 // implicitly instantiated; that's fine.
3596 return false;
3597
3598 case TSK_ExplicitSpecialization:
3599 // C++0x [temp.explicit]p4:
3600 // For a given set of template parameters, if an explicit instantiation
3601 // of a template appears after a declaration of an explicit
3602 // specialization for that template, the explicit instantiation has no
3603 // effect.
3604 return false;
3605
3606 case TSK_ExplicitInstantiationDefinition:
3607 // C++0x [temp.explicit]p10:
3608 // If an entity is the subject of both an explicit instantiation
3609 // declaration and an explicit instantiation definition in the same
3610 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003611 Diag(NewLoc,
3612 diag::err_explicit_instantiation_declaration_after_definition);
3613 Diag(PrevPointOfInstantiation,
3614 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003615 assert(PrevPointOfInstantiation.isValid() &&
3616 "Explicit instantiation without point of instantiation?");
3617 SuppressNew = true;
3618 return false;
3619 }
3620 break;
3621
3622 case TSK_ExplicitInstantiationDefinition:
3623 switch (PrevTSK) {
3624 case TSK_Undeclared:
3625 case TSK_ImplicitInstantiation:
3626 // We're explicitly instantiating something that may have already been
3627 // implicitly instantiated; that's fine.
3628 return false;
3629
3630 case TSK_ExplicitSpecialization:
3631 // C++ DR 259, C++0x [temp.explicit]p4:
3632 // For a given set of template parameters, if an explicit
3633 // instantiation of a template appears after a declaration of
3634 // an explicit specialization for that template, the explicit
3635 // instantiation has no effect.
3636 //
3637 // In C++98/03 mode, we only give an extension warning here, because it
3638 // is not not harmful to try to explicitly instantiate something that
3639 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003640 if (!getLangOptions().CPlusPlus0x) {
3641 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003642 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003643 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003644 diag::note_previous_template_specialization);
3645 }
3646 SuppressNew = true;
3647 return false;
3648
3649 case TSK_ExplicitInstantiationDeclaration:
3650 // We're explicity instantiating a definition for something for which we
3651 // were previously asked to suppress instantiations. That's fine.
3652 return false;
3653
3654 case TSK_ExplicitInstantiationDefinition:
3655 // C++0x [temp.spec]p5:
3656 // For a given template and a given set of template-arguments,
3657 // - an explicit instantiation definition shall appear at most once
3658 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00003659 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003660 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00003661 Diag(PrevPointOfInstantiation,
3662 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003663 SuppressNew = true;
3664 return false;
3665 }
3666 break;
3667 }
3668
3669 assert(false && "Missing specialization/instantiation case?");
3670
3671 return false;
3672}
3673
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003674/// \brief Perform semantic analysis for the given function template
3675/// specialization.
3676///
3677/// This routine performs all of the semantic analysis required for an
3678/// explicit function template specialization. On successful completion,
3679/// the function declaration \p FD will become a function template
3680/// specialization.
3681///
3682/// \param FD the function declaration, which will be updated to become a
3683/// function template specialization.
3684///
3685/// \param HasExplicitTemplateArgs whether any template arguments were
3686/// explicitly provided.
3687///
3688/// \param LAngleLoc the location of the left angle bracket ('<'), if
3689/// template arguments were explicitly provided.
3690///
3691/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
3692/// if any.
3693///
3694/// \param NumExplicitTemplateArgs the number of explicitly-provided template
3695/// arguments. This number may be zero even when HasExplicitTemplateArgs is
3696/// true as in, e.g., \c void sort<>(char*, char*);
3697///
3698/// \param RAngleLoc the location of the right angle bracket ('>'), if
3699/// template arguments were explicitly provided.
3700///
3701/// \param PrevDecl the set of declarations that
3702bool
3703Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00003704 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00003705 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003706 // The set of function template specializations that could match this
3707 // explicit function template specialization.
3708 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet;
3709 CandidateSet Candidates;
3710
3711 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00003712 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3713 I != E; ++I) {
3714 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
3715 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003716 // Only consider templates found within the same semantic lookup scope as
3717 // FD.
3718 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
3719 continue;
3720
3721 // C++ [temp.expl.spec]p11:
3722 // A trailing template-argument can be left unspecified in the
3723 // template-id naming an explicit function template specialization
3724 // provided it can be deduced from the function argument type.
3725 // Perform template argument deduction to determine whether we may be
3726 // specializing this template.
3727 // FIXME: It is somewhat wasteful to build
3728 TemplateDeductionInfo Info(Context);
3729 FunctionDecl *Specialization = 0;
3730 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00003731 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003732 FD->getType(),
3733 Specialization,
3734 Info)) {
3735 // FIXME: Template argument deduction failed; record why it failed, so
3736 // that we can provide nifty diagnostics.
3737 (void)TDK;
3738 continue;
3739 }
3740
3741 // Record this candidate.
3742 Candidates.push_back(Specialization);
3743 }
3744 }
3745
Douglas Gregor5de279c2009-09-26 03:41:46 +00003746 // Find the most specialized function template.
3747 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(),
3748 Candidates.size(),
3749 TPOC_Other,
3750 FD->getLocation(),
3751 PartialDiagnostic(diag::err_function_template_spec_no_match)
3752 << FD->getDeclName(),
3753 PartialDiagnostic(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00003754 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor5de279c2009-09-26 03:41:46 +00003755 PartialDiagnostic(diag::note_function_template_spec_matched));
3756 if (!Specialization)
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003757 return true;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003758
3759 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003760 // If so, we have run afoul of .
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003761
Douglas Gregor54888652009-10-07 00:13:32 +00003762 // Check the scope of this explicit specialization.
3763 if (CheckTemplateSpecializationScope(*this,
3764 Specialization->getPrimaryTemplate(),
3765 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003766 false))
Douglas Gregor54888652009-10-07 00:13:32 +00003767 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003768
3769 // C++ [temp.expl.spec]p6:
3770 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00003771 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00003772 // before the first use of that specialization that would cause an implicit
3773 // instantiation to take place, in every translation unit in which such a
3774 // use occurs; no diagnostic is required.
3775 FunctionTemplateSpecializationInfo *SpecInfo
3776 = Specialization->getTemplateSpecializationInfo();
3777 assert(SpecInfo && "Function template specialization info missing?");
3778 if (SpecInfo->getPointOfInstantiation().isValid()) {
3779 Diag(FD->getLocation(), diag::err_specialization_after_instantiation)
3780 << FD;
3781 Diag(SpecInfo->getPointOfInstantiation(),
3782 diag::note_instantiation_required_here)
3783 << (Specialization->getTemplateSpecializationKind()
3784 != TSK_ImplicitInstantiation);
3785 return true;
3786 }
Douglas Gregor54888652009-10-07 00:13:32 +00003787
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003788 // Mark the prior declaration as an explicit specialization, so that later
3789 // clients know that this is an explicit specialization.
Douglas Gregor06db9f52009-10-12 20:18:28 +00003790 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003791
3792 // Turn the given function declaration into a function template
3793 // specialization, with the template arguments from the previous
3794 // specialization.
3795 FD->setFunctionTemplateSpecialization(Context,
3796 Specialization->getPrimaryTemplate(),
3797 new (Context) TemplateArgumentList(
3798 *Specialization->getTemplateSpecializationArgs()),
3799 /*InsertPos=*/0,
3800 TSK_ExplicitSpecialization);
3801
3802 // The "previous declaration" for this function template specialization is
3803 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00003804 Previous.clear();
3805 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003806 return false;
3807}
3808
Douglas Gregor86d142a2009-10-08 07:24:58 +00003809/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003810/// specialization.
3811///
3812/// This routine performs all of the semantic analysis required for an
3813/// explicit member function specialization. On successful completion,
3814/// the function declaration \p FD will become a member function
3815/// specialization.
3816///
Douglas Gregor86d142a2009-10-08 07:24:58 +00003817/// \param Member the member declaration, which will be updated to become a
3818/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003819///
John McCall1f82f242009-11-18 22:49:29 +00003820/// \param Previous the set of declarations, one of which may be specialized
3821/// by this function specialization; the set will be modified to contain the
3822/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003823bool
John McCall1f82f242009-11-18 22:49:29 +00003824Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003825 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
3826
3827 // Try to find the member we are instantiating.
3828 NamedDecl *Instantiation = 0;
3829 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003830 MemberSpecializationInfo *MSInfo = 0;
3831
John McCall1f82f242009-11-18 22:49:29 +00003832 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003833 // Nowhere to look anyway.
3834 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003835 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3836 I != E; ++I) {
3837 NamedDecl *D = (*I)->getUnderlyingDecl();
3838 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003839 if (Context.hasSameType(Function->getType(), Method->getType())) {
3840 Instantiation = Method;
3841 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003842 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003843 break;
3844 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003845 }
3846 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00003847 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003848 VarDecl *PrevVar;
3849 if (Previous.isSingleResult() &&
3850 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00003851 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00003852 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003853 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003854 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003855 }
3856 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00003857 CXXRecordDecl *PrevRecord;
3858 if (Previous.isSingleResult() &&
3859 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
3860 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00003861 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00003862 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003863 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003864 }
3865
3866 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00003867 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003868 // specializations are always out-of-line, the caller will complain about
3869 // this mismatch later.
3870 return false;
3871 }
3872
Douglas Gregor86d142a2009-10-08 07:24:58 +00003873 // Make sure that this is a specialization of a member.
3874 if (!InstantiatedFrom) {
3875 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
3876 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003877 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
3878 return true;
3879 }
3880
Douglas Gregor06db9f52009-10-12 20:18:28 +00003881 // C++ [temp.expl.spec]p6:
3882 // If a template, a member template or the member of a class template is
3883 // explicitly specialized then that spe- cialization shall be declared
3884 // before the first use of that specialization that would cause an implicit
3885 // instantiation to take place, in every translation unit in which such a
3886 // use occurs; no diagnostic is required.
3887 assert(MSInfo && "Member specialization info missing?");
3888 if (MSInfo->getPointOfInstantiation().isValid()) {
3889 Diag(Member->getLocation(), diag::err_specialization_after_instantiation)
3890 << Member;
3891 Diag(MSInfo->getPointOfInstantiation(),
3892 diag::note_instantiation_required_here)
3893 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation);
3894 return true;
3895 }
3896
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003897 // Check the scope of this explicit specialization.
3898 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00003899 InstantiatedFrom,
3900 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003901 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003902 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00003903
Douglas Gregor86d142a2009-10-08 07:24:58 +00003904 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003905 // the original declaration to note that it is an explicit specialization
3906 // (if it was previously an implicit instantiation). This latter step
3907 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00003908 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003909 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
3910 if (InstantiationFunction->getTemplateSpecializationKind() ==
3911 TSK_ImplicitInstantiation) {
3912 InstantiationFunction->setTemplateSpecializationKind(
3913 TSK_ExplicitSpecialization);
3914 InstantiationFunction->setLocation(Member->getLocation());
3915 }
3916
Douglas Gregor86d142a2009-10-08 07:24:58 +00003917 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
3918 cast<CXXMethodDecl>(InstantiatedFrom),
3919 TSK_ExplicitSpecialization);
3920 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003921 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
3922 if (InstantiationVar->getTemplateSpecializationKind() ==
3923 TSK_ImplicitInstantiation) {
3924 InstantiationVar->setTemplateSpecializationKind(
3925 TSK_ExplicitSpecialization);
3926 InstantiationVar->setLocation(Member->getLocation());
3927 }
3928
Douglas Gregor86d142a2009-10-08 07:24:58 +00003929 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
3930 cast<VarDecl>(InstantiatedFrom),
3931 TSK_ExplicitSpecialization);
3932 } else {
3933 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003934 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
3935 if (InstantiationClass->getTemplateSpecializationKind() ==
3936 TSK_ImplicitInstantiation) {
3937 InstantiationClass->setTemplateSpecializationKind(
3938 TSK_ExplicitSpecialization);
3939 InstantiationClass->setLocation(Member->getLocation());
3940 }
3941
Douglas Gregor86d142a2009-10-08 07:24:58 +00003942 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003943 cast<CXXRecordDecl>(InstantiatedFrom),
3944 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003945 }
3946
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003947 // Save the caller the trouble of having to figure out which declaration
3948 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00003949 Previous.clear();
3950 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003951 return false;
3952}
3953
Douglas Gregore47f5a72009-10-14 23:41:34 +00003954/// \brief Check the scope of an explicit instantiation.
3955static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
3956 SourceLocation InstLoc,
3957 bool WasQualifiedName) {
3958 DeclContext *ExpectedContext
3959 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
3960 DeclContext *CurContext = S.CurContext->getLookupContext();
3961
3962 // C++0x [temp.explicit]p2:
3963 // An explicit instantiation shall appear in an enclosing namespace of its
3964 // template.
3965 //
3966 // This is DR275, which we do not retroactively apply to C++98/03.
3967 if (S.getLangOptions().CPlusPlus0x &&
3968 !CurContext->Encloses(ExpectedContext)) {
3969 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
3970 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
3971 << D << NS;
3972 else
3973 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
3974 << D;
3975 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3976 return;
3977 }
3978
3979 // C++0x [temp.explicit]p2:
3980 // If the name declared in the explicit instantiation is an unqualified
3981 // name, the explicit instantiation shall appear in the namespace where
3982 // its template is declared or, if that namespace is inline (7.3.1), any
3983 // namespace from its enclosing namespace set.
3984 if (WasQualifiedName)
3985 return;
3986
3987 if (CurContext->Equals(ExpectedContext))
3988 return;
3989
3990 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
3991 << D << ExpectedContext;
3992 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
3993}
3994
3995/// \brief Determine whether the given scope specifier has a template-id in it.
3996static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
3997 if (!SS.isSet())
3998 return false;
3999
4000 // C++0x [temp.explicit]p2:
4001 // If the explicit instantiation is for a member function, a member class
4002 // or a static data member of a class template specialization, the name of
4003 // the class template specialization in the qualified-id for the member
4004 // name shall be a simple-template-id.
4005 //
4006 // C++98 has the same restriction, just worded differently.
4007 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4008 NNS; NNS = NNS->getPrefix())
4009 if (Type *T = NNS->getAsType())
4010 if (isa<TemplateSpecializationType>(T))
4011 return true;
4012
4013 return false;
4014}
4015
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004016// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004017// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004018Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004019Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004020 SourceLocation ExternLoc,
4021 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004022 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004023 SourceLocation KWLoc,
4024 const CXXScopeSpec &SS,
4025 TemplateTy TemplateD,
4026 SourceLocation TemplateNameLoc,
4027 SourceLocation LAngleLoc,
4028 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004029 SourceLocation RAngleLoc,
4030 AttributeList *Attr) {
4031 // Find the class template we're specializing
4032 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004033 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004034 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4035
4036 // Check that the specialization uses the same tag kind as the
4037 // original template.
4038 TagDecl::TagKind Kind;
4039 switch (TagSpec) {
4040 default: assert(0 && "Unknown tag type!");
4041 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4042 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4043 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4044 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004045 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004046 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004047 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004048 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004049 << ClassTemplate
Mike Stump11289f42009-09-09 15:08:12 +00004050 << CodeModificationHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004051 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004052 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004053 diag::note_previous_use);
4054 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4055 }
4056
Douglas Gregore47f5a72009-10-14 23:41:34 +00004057 // C++0x [temp.explicit]p2:
4058 // There are two forms of explicit instantiation: an explicit instantiation
4059 // definition and an explicit instantiation declaration. An explicit
4060 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004061 TemplateSpecializationKind TSK
4062 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4063 : TSK_ExplicitInstantiationDeclaration;
4064
Douglas Gregora1f49972009-05-13 00:25:59 +00004065 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004066 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004067 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004068
4069 // Check that the template argument list is well-formed for this
4070 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004071 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4072 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004073 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4074 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004075 return true;
4076
Mike Stump11289f42009-09-09 15:08:12 +00004077 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004078 ClassTemplate->getTemplateParameters()->size()) &&
4079 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004080
Douglas Gregora1f49972009-05-13 00:25:59 +00004081 // Find the class template specialization declaration that
4082 // corresponds to these arguments.
4083 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004084 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004085 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004086 Converted.flatSize(),
4087 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004088 void *InsertPos = 0;
4089 ClassTemplateSpecializationDecl *PrevDecl
4090 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4091
Douglas Gregor54888652009-10-07 00:13:32 +00004092 // C++0x [temp.explicit]p2:
4093 // [...] An explicit instantiation shall appear in an enclosing
4094 // namespace of its template. [...]
4095 //
4096 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004097 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4098 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004099
Douglas Gregora1f49972009-05-13 00:25:59 +00004100 ClassTemplateSpecializationDecl *Specialization = 0;
4101
4102 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004103 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004104 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004105 PrevDecl,
4106 PrevDecl->getSpecializationKind(),
4107 PrevDecl->getPointOfInstantiation(),
4108 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004109 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004110
Douglas Gregor12e49d32009-10-15 22:53:21 +00004111 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004112 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004113
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004114 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4115 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4116 // Since the only prior class template specialization with these
4117 // arguments was referenced but not declared, reuse that
4118 // declaration node as our own, updating its source location to
4119 // reflect our new declaration.
4120 Specialization = PrevDecl;
4121 Specialization->setLocation(TemplateNameLoc);
4122 PrevDecl = 0;
4123 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004124 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004125
4126 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004127 // Create a new class template specialization declaration node for
4128 // this explicit specialization.
4129 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004130 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004131 ClassTemplate->getDeclContext(),
4132 TemplateNameLoc,
4133 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004134 Converted, PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004135
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004136 if (PrevDecl) {
4137 // Remove the previous declaration from the folding set, since we want
4138 // to introduce a new declaration.
4139 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4140 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4141 }
4142
4143 // Insert the new specialization.
4144 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004145 }
4146
4147 // Build the fully-sugared type for this explicit instantiation as
4148 // the user wrote in the explicit instantiation itself. This means
4149 // that we'll pretty-print the type retrieved from the
4150 // specialization's declaration the way that the user actually wrote
4151 // the explicit instantiation, rather than formatting the name based
4152 // on the "canonical" representation used to store the template
4153 // arguments in the specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004154 QualType WrittenTy
John McCall6b51f282009-11-23 01:53:49 +00004155 = Context.getTemplateSpecializationType(Name, TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004156 Context.getTypeDeclType(Specialization));
4157 Specialization->setTypeAsWritten(WrittenTy);
4158 TemplateArgsIn.release();
4159
4160 // Add the explicit instantiation into its lexical context. However,
4161 // since explicit instantiations are never found by name lookup, we
4162 // just put it into the declaration context directly.
4163 Specialization->setLexicalDeclContext(CurContext);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004164 CurContext->addDecl(Specialization);
Douglas Gregora1f49972009-05-13 00:25:59 +00004165
4166 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004167 // A definition of a class template or class member template
4168 // shall be in scope at the point of the explicit instantiation of
4169 // the class template or class member template.
4170 //
4171 // This check comes when we actually try to perform the
4172 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004173 ClassTemplateSpecializationDecl *Def
4174 = cast_or_null<ClassTemplateSpecializationDecl>(
4175 Specialization->getDefinition(Context));
4176 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004177 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004178
4179 // Instantiate the members of this class template specialization.
4180 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4181 Specialization->getDefinition(Context));
4182 if (Def)
Douglas Gregor12e49d32009-10-15 22:53:21 +00004183 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004184
4185 return DeclPtrTy::make(Specialization);
4186}
4187
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004188// Explicit instantiation of a member class of a class template.
4189Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004190Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004191 SourceLocation ExternLoc,
4192 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004193 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004194 SourceLocation KWLoc,
4195 const CXXScopeSpec &SS,
4196 IdentifierInfo *Name,
4197 SourceLocation NameLoc,
4198 AttributeList *Attr) {
4199
Douglas Gregord6ab8742009-05-28 23:31:59 +00004200 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004201 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004202 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004203 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004204 MultiTemplateParamsArg(*this, 0, 0),
4205 Owned, IsDependent);
4206 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4207
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004208 if (!TagD)
4209 return true;
4210
4211 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4212 if (Tag->isEnum()) {
4213 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4214 << Context.getTypeDeclType(Tag);
4215 return true;
4216 }
4217
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004218 if (Tag->isInvalidDecl())
4219 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004220
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004221 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4222 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4223 if (!Pattern) {
4224 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4225 << Context.getTypeDeclType(Record);
4226 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4227 return true;
4228 }
4229
Douglas Gregore47f5a72009-10-14 23:41:34 +00004230 // C++0x [temp.explicit]p2:
4231 // If the explicit instantiation is for a class or member class, the
4232 // elaborated-type-specifier in the declaration shall include a
4233 // simple-template-id.
4234 //
4235 // C++98 has the same restriction, just worded differently.
4236 if (!ScopeSpecifierHasTemplateId(SS))
4237 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4238 << Record << SS.getRange();
4239
4240 // C++0x [temp.explicit]p2:
4241 // There are two forms of explicit instantiation: an explicit instantiation
4242 // definition and an explicit instantiation declaration. An explicit
4243 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004244 TemplateSpecializationKind TSK
4245 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4246 : TSK_ExplicitInstantiationDeclaration;
4247
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004248 // C++0x [temp.explicit]p2:
4249 // [...] An explicit instantiation shall appear in an enclosing
4250 // namespace of its template. [...]
4251 //
4252 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004253 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004254
4255 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004256 CXXRecordDecl *PrevDecl
4257 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4258 if (!PrevDecl && Record->getDefinition(Context))
4259 PrevDecl = Record;
4260 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004261 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4262 bool SuppressNew = false;
4263 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004264 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004265 PrevDecl,
4266 MSInfo->getTemplateSpecializationKind(),
4267 MSInfo->getPointOfInstantiation(),
4268 SuppressNew))
4269 return true;
4270 if (SuppressNew)
4271 return TagD;
4272 }
4273
Douglas Gregor12e49d32009-10-15 22:53:21 +00004274 CXXRecordDecl *RecordDef
4275 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4276 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004277 // C++ [temp.explicit]p3:
4278 // A definition of a member class of a class template shall be in scope
4279 // at the point of an explicit instantiation of the member class.
4280 CXXRecordDecl *Def
4281 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
4282 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004283 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4284 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004285 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4286 << Pattern;
4287 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004288 } else {
4289 if (InstantiateClass(NameLoc, Record, Def,
4290 getTemplateInstantiationArgs(Record),
4291 TSK))
4292 return true;
4293
4294 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context));
4295 if (!RecordDef)
4296 return true;
4297 }
4298 }
4299
4300 // Instantiate all of the members of the class.
4301 InstantiateClassMembers(NameLoc, RecordDef,
4302 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004303
Mike Stump87c57ac2009-05-16 07:39:55 +00004304 // FIXME: We don't have any representation for explicit instantiations of
4305 // member classes. Such a representation is not needed for compilation, but it
4306 // should be available for clients that want to see all of the declarations in
4307 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004308 return TagD;
4309}
4310
Douglas Gregor450f00842009-09-25 18:43:00 +00004311Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4312 SourceLocation ExternLoc,
4313 SourceLocation TemplateLoc,
4314 Declarator &D) {
4315 // Explicit instantiations always require a name.
4316 DeclarationName Name = GetNameForDeclarator(D);
4317 if (!Name) {
4318 if (!D.isInvalidType())
4319 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4320 diag::err_explicit_instantiation_requires_name)
4321 << D.getDeclSpec().getSourceRange()
4322 << D.getSourceRange();
4323
4324 return true;
4325 }
4326
4327 // The scope passed in may not be a decl scope. Zip up the scope tree until
4328 // we find one that is.
4329 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4330 (S->getFlags() & Scope::TemplateParamScope) != 0)
4331 S = S->getParent();
4332
4333 // Determine the type of the declaration.
4334 QualType R = GetTypeForDeclarator(D, S, 0);
4335 if (R.isNull())
4336 return true;
4337
4338 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4339 // Cannot explicitly instantiate a typedef.
4340 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4341 << Name;
4342 return true;
4343 }
4344
Douglas Gregor3c74d412009-10-14 20:14:33 +00004345 // C++0x [temp.explicit]p1:
4346 // [...] An explicit instantiation of a function template shall not use the
4347 // inline or constexpr specifiers.
4348 // Presumably, this also applies to member functions of class templates as
4349 // well.
4350 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4351 Diag(D.getDeclSpec().getInlineSpecLoc(),
4352 diag::err_explicit_instantiation_inline)
4353 << CodeModificationHint::CreateRemoval(
4354 SourceRange(D.getDeclSpec().getInlineSpecLoc()));
4355
4356 // FIXME: check for constexpr specifier.
4357
Douglas Gregore47f5a72009-10-14 23:41:34 +00004358 // C++0x [temp.explicit]p2:
4359 // There are two forms of explicit instantiation: an explicit instantiation
4360 // definition and an explicit instantiation declaration. An explicit
4361 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004362 TemplateSpecializationKind TSK
4363 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4364 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004365
John McCall27b18f82009-11-17 02:14:36 +00004366 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4367 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004368
4369 if (!R->isFunctionType()) {
4370 // C++ [temp.explicit]p1:
4371 // A [...] static data member of a class template can be explicitly
4372 // instantiated from the member definition associated with its class
4373 // template.
John McCall27b18f82009-11-17 02:14:36 +00004374 if (Previous.isAmbiguous())
4375 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004376
John McCall9f3059a2009-10-09 21:13:30 +00004377 VarDecl *Prev = dyn_cast_or_null<VarDecl>(
4378 Previous.getAsSingleDecl(Context));
Douglas Gregor450f00842009-09-25 18:43:00 +00004379 if (!Prev || !Prev->isStaticDataMember()) {
4380 // We expect to see a data data member here.
4381 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4382 << Name;
4383 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4384 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004385 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004386 return true;
4387 }
4388
4389 if (!Prev->getInstantiatedFromStaticDataMember()) {
4390 // FIXME: Check for explicit specialization?
4391 Diag(D.getIdentifierLoc(),
4392 diag::err_explicit_instantiation_data_member_not_instantiated)
4393 << Prev;
4394 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4395 // FIXME: Can we provide a note showing where this was declared?
4396 return true;
4397 }
4398
Douglas Gregore47f5a72009-10-14 23:41:34 +00004399 // C++0x [temp.explicit]p2:
4400 // If the explicit instantiation is for a member function, a member class
4401 // or a static data member of a class template specialization, the name of
4402 // the class template specialization in the qualified-id for the member
4403 // name shall be a simple-template-id.
4404 //
4405 // C++98 has the same restriction, just worded differently.
4406 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4407 Diag(D.getIdentifierLoc(),
4408 diag::err_explicit_instantiation_without_qualified_id)
4409 << Prev << D.getCXXScopeSpec().getRange();
4410
4411 // Check the scope of this explicit instantiation.
4412 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4413
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004414 // Verify that it is okay to explicitly instantiate here.
4415 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4416 assert(MSInfo && "Missing static data member specialization info?");
4417 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004418 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004419 MSInfo->getTemplateSpecializationKind(),
4420 MSInfo->getPointOfInstantiation(),
4421 SuppressNew))
4422 return true;
4423 if (SuppressNew)
4424 return DeclPtrTy();
4425
Douglas Gregor450f00842009-09-25 18:43:00 +00004426 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004427 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004428 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004429 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4430 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004431
4432 // FIXME: Create an ExplicitInstantiation node?
4433 return DeclPtrTy();
4434 }
4435
Douglas Gregor0e876e02009-09-25 23:53:26 +00004436 // If the declarator is a template-id, translate the parser's template
4437 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004438 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004439 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004440 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4441 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004442 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4443 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004444 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4445 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004446 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004447 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004448 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004449 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004450 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004451
Douglas Gregor450f00842009-09-25 18:43:00 +00004452 // C++ [temp.explicit]p1:
4453 // A [...] function [...] can be explicitly instantiated from its template.
4454 // A member function [...] of a class template can be explicitly
4455 // instantiated from the member definition associated with its class
4456 // template.
Douglas Gregor450f00842009-09-25 18:43:00 +00004457 llvm::SmallVector<FunctionDecl *, 8> Matches;
4458 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4459 P != PEnd; ++P) {
4460 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004461 if (!HasExplicitTemplateArgs) {
4462 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4463 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4464 Matches.clear();
4465 Matches.push_back(Method);
4466 break;
4467 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004468 }
4469 }
4470
4471 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4472 if (!FunTmpl)
4473 continue;
4474
4475 TemplateDeductionInfo Info(Context);
4476 FunctionDecl *Specialization = 0;
4477 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004478 = DeduceTemplateArguments(FunTmpl,
4479 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004480 R, Specialization, Info)) {
4481 // FIXME: Keep track of almost-matches?
4482 (void)TDK;
4483 continue;
4484 }
4485
4486 Matches.push_back(Specialization);
4487 }
4488
4489 // Find the most specialized function template specialization.
4490 FunctionDecl *Specialization
4491 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other,
4492 D.getIdentifierLoc(),
4493 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name,
4494 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name,
4495 PartialDiagnostic(diag::note_explicit_instantiation_candidate));
4496
4497 if (!Specialization)
4498 return true;
4499
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004500 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004501 Diag(D.getIdentifierLoc(),
4502 diag::err_explicit_instantiation_member_function_not_instantiated)
4503 << Specialization
4504 << (Specialization->getTemplateSpecializationKind() ==
4505 TSK_ExplicitSpecialization);
4506 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
4507 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004508 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00004509
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004510 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00004511 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
4512 PrevDecl = Specialization;
4513
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004514 if (PrevDecl) {
4515 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004516 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004517 PrevDecl,
4518 PrevDecl->getTemplateSpecializationKind(),
4519 PrevDecl->getPointOfInstantiation(),
4520 SuppressNew))
4521 return true;
4522
4523 // FIXME: We may still want to build some representation of this
4524 // explicit specialization.
4525 if (SuppressNew)
4526 return DeclPtrTy();
4527 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00004528
4529 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004530
4531 if (TSK == TSK_ExplicitInstantiationDefinition)
4532 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
4533 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004534
Douglas Gregore47f5a72009-10-14 23:41:34 +00004535 // C++0x [temp.explicit]p2:
4536 // If the explicit instantiation is for a member function, a member class
4537 // or a static data member of a class template specialization, the name of
4538 // the class template specialization in the qualified-id for the member
4539 // name shall be a simple-template-id.
4540 //
4541 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004542 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00004543 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00004544 D.getCXXScopeSpec().isSet() &&
4545 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4546 Diag(D.getIdentifierLoc(),
4547 diag::err_explicit_instantiation_without_qualified_id)
4548 << Specialization << D.getCXXScopeSpec().getRange();
4549
4550 CheckExplicitInstantiationScope(*this,
4551 FunTmpl? (NamedDecl *)FunTmpl
4552 : Specialization->getInstantiatedFromMemberFunction(),
4553 D.getIdentifierLoc(),
4554 D.getCXXScopeSpec().isSet());
4555
Douglas Gregor450f00842009-09-25 18:43:00 +00004556 // FIXME: Create some kind of ExplicitInstantiationDecl here.
4557 return DeclPtrTy();
4558}
4559
Douglas Gregor333489b2009-03-27 23:10:48 +00004560Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00004561Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4562 const CXXScopeSpec &SS, IdentifierInfo *Name,
4563 SourceLocation TagLoc, SourceLocation NameLoc) {
4564 // This has to hold, because SS is expected to be defined.
4565 assert(Name && "Expected a name in a dependent tag");
4566
4567 NestedNameSpecifier *NNS
4568 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4569 if (!NNS)
4570 return true;
4571
4572 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc));
4573 if (T.isNull())
4574 return true;
4575
4576 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
4577 QualType ElabType = Context.getElaboratedType(T, TagKind);
4578
4579 return ElabType.getAsOpaquePtr();
4580}
4581
4582Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00004583Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4584 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004585 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00004586 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4587 if (!NNS)
4588 return true;
4589
4590 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00004591 if (T.isNull())
4592 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00004593 return T.getAsOpaquePtr();
4594}
4595
Douglas Gregordce2b622009-04-01 00:28:59 +00004596Sema::TypeResult
4597Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
4598 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00004599 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00004600 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00004601 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00004602 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00004603 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00004604 assert(TemplateId && "Expected a template specialization type");
4605
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004606 if (computeDeclContext(SS, false)) {
4607 // If we can compute a declaration context, then the "typename"
4608 // keyword was superfluous. Just build a QualifiedNameType to keep
4609 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00004610
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004611 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
4612 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
4613 }
Mike Stump11289f42009-09-09 15:08:12 +00004614
Douglas Gregor12bbfe12009-09-02 13:05:45 +00004615 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00004616}
4617
Douglas Gregor333489b2009-03-27 23:10:48 +00004618/// \brief Build the type that describes a C++ typename specifier,
4619/// e.g., "typename T::type".
4620QualType
4621Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
4622 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004623 CXXRecordDecl *CurrentInstantiation = 0;
4624 if (NNS->isDependent()) {
4625 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00004626
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004627 // If the nested-name-specifier does not refer to the current
4628 // instantiation, then build a typename type.
4629 if (!CurrentInstantiation)
4630 return Context.getTypenameType(NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00004631
Douglas Gregorc707da62009-09-02 13:12:51 +00004632 // The nested-name-specifier refers to the current instantiation, so the
4633 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00004634 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00004635 // extraneous "typename" keywords, and we retroactively apply this DR to
4636 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004637 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004638
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004639 DeclContext *Ctx = 0;
4640
4641 if (CurrentInstantiation)
4642 Ctx = CurrentInstantiation;
4643 else {
4644 CXXScopeSpec SS;
4645 SS.setScopeRep(NNS);
4646 SS.setRange(Range);
4647 if (RequireCompleteDeclContext(SS))
4648 return QualType();
4649
4650 Ctx = computeDeclContext(SS);
4651 }
Douglas Gregor333489b2009-03-27 23:10:48 +00004652 assert(Ctx && "No declaration context?");
4653
4654 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00004655 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
4656 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00004657 unsigned DiagID = 0;
4658 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00004659 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004660 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00004661 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00004662 break;
4663
4664 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00004665 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00004666 // We found a type. Build a QualifiedNameType, since the
4667 // typename-specifier was just sugar. FIXME: Tell
4668 // QualifiedNameType that it has a "typename" prefix.
4669 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
4670 }
4671
4672 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00004673 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00004674 break;
4675
John McCalle61f2ba2009-11-18 02:36:19 +00004676 case LookupResult::FoundUnresolvedValue:
4677 llvm::llvm_unreachable("unresolved using decl in non-dependent context");
4678 return QualType();
4679
Douglas Gregor333489b2009-03-27 23:10:48 +00004680 case LookupResult::FoundOverloaded:
4681 DiagID = diag::err_typename_nested_not_type;
4682 Referenced = *Result.begin();
4683 break;
4684
John McCall6538c932009-10-10 05:48:19 +00004685 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00004686 return QualType();
4687 }
4688
4689 // If we get here, it's because name lookup did not find a
4690 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00004691 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00004692 if (Referenced)
4693 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
4694 << Name;
4695 return QualType();
4696}
Douglas Gregor15acfb92009-08-06 16:20:37 +00004697
4698namespace {
4699 // See Sema::RebuildTypeInCurrentInstantiation
Mike Stump11289f42009-09-09 15:08:12 +00004700 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder
4701 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00004702 SourceLocation Loc;
4703 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00004704
Douglas Gregor15acfb92009-08-06 16:20:37 +00004705 public:
Mike Stump11289f42009-09-09 15:08:12 +00004706 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00004707 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004708 DeclarationName Entity)
4709 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00004710 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00004711
4712 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00004713 /// transformed.
4714 ///
4715 /// For the purposes of type reconstruction, a type has already been
4716 /// transformed if it is NULL or if it is not dependent.
4717 bool AlreadyTransformed(QualType T) {
4718 return T.isNull() || !T->isDependentType();
4719 }
Mike Stump11289f42009-09-09 15:08:12 +00004720
4721 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00004722 /// rebuilt.
4723 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00004724
Douglas Gregor15acfb92009-08-06 16:20:37 +00004725 /// \brief Returns the name of the entity whose type is being rebuilt.
4726 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00004727
Douglas Gregoref6ab412009-10-27 06:26:26 +00004728 /// \brief Sets the "base" location and entity when that
4729 /// information is known based on another transformation.
4730 void setBase(SourceLocation Loc, DeclarationName Entity) {
4731 this->Loc = Loc;
4732 this->Entity = Entity;
4733 }
4734
Douglas Gregor15acfb92009-08-06 16:20:37 +00004735 /// \brief Transforms an expression by returning the expression itself
4736 /// (an identity function).
4737 ///
4738 /// FIXME: This is completely unsafe; we will need to actually clone the
4739 /// expressions.
4740 Sema::OwningExprResult TransformExpr(Expr *E) {
4741 return getSema().Owned(E);
4742 }
Mike Stump11289f42009-09-09 15:08:12 +00004743
Douglas Gregor15acfb92009-08-06 16:20:37 +00004744 /// \brief Transforms a typename type by determining whether the type now
4745 /// refers to a member of the current instantiation, and then
4746 /// type-checking and building a QualifiedNameType (when possible).
John McCall550e0c22009-10-21 00:40:46 +00004747 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL);
Douglas Gregor15acfb92009-08-06 16:20:37 +00004748 };
4749}
4750
Mike Stump11289f42009-09-09 15:08:12 +00004751QualType
John McCall550e0c22009-10-21 00:40:46 +00004752CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB,
4753 TypenameTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00004754 TypenameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00004755
Douglas Gregor15acfb92009-08-06 16:20:37 +00004756 NestedNameSpecifier *NNS
4757 = TransformNestedNameSpecifier(T->getQualifier(),
4758 /*FIXME:*/SourceRange(getBaseLocation()));
4759 if (!NNS)
4760 return QualType();
4761
4762 // If the nested-name-specifier did not change, and we cannot compute the
4763 // context corresponding to the nested-name-specifier, then this
4764 // typename type will not change; exit early.
4765 CXXScopeSpec SS;
4766 SS.setRange(SourceRange(getBaseLocation()));
4767 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00004768
4769 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004770 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00004771 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004772
4773 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00004774 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00004775 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00004776 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00004777 = TransformType(QualType(TemplateId, 0));
4778 if (NewTemplateId.isNull())
4779 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004780
Douglas Gregor15acfb92009-08-06 16:20:37 +00004781 if (NNS == T->getQualifier() &&
4782 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00004783 Result = QualType(T, 0);
4784 else
4785 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId);
4786 } else
4787 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(),
4788 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00004789
John McCall0ad16662009-10-29 08:12:44 +00004790 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result);
4791 NewTL.setNameLoc(TL.getNameLoc());
4792 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00004793}
4794
4795/// \brief Rebuilds a type within the context of the current instantiation.
4796///
Mike Stump11289f42009-09-09 15:08:12 +00004797/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00004798/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00004799/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00004800/// partial specialization thereof). This routine will rebuild that type now
4801/// that we have entered the declarator's scope, which may produce different
4802/// canonical types, e.g.,
4803///
4804/// \code
4805/// template<typename T>
4806/// struct X {
4807/// typedef T* pointer;
4808/// pointer data();
4809/// };
4810///
4811/// template<typename T>
4812/// typename X<T>::pointer X<T>::data() { ... }
4813/// \endcode
4814///
4815/// Here, the type "typename X<T>::pointer" will be created as a TypenameType,
4816/// since we do not know that we can look into X<T> when we parsed the type.
4817/// This function will rebuild the type, performing the lookup of "pointer"
4818/// in X<T> and returning a QualifiedNameType whose canonical type is the same
4819/// as the canonical type of T*, allowing the return types of the out-of-line
4820/// definition and the declaration to match.
4821QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
4822 DeclarationName Name) {
4823 if (T.isNull() || !T->isDependentType())
4824 return T;
Mike Stump11289f42009-09-09 15:08:12 +00004825
Douglas Gregor15acfb92009-08-06 16:20:37 +00004826 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
4827 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00004828}
Douglas Gregorbe999392009-09-15 16:23:51 +00004829
4830/// \brief Produces a formatted string that describes the binding of
4831/// template parameters to template arguments.
4832std::string
4833Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4834 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004835 // FIXME: For variadic templates, we'll need to get the structured list.
4836 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
4837 Args.flat_size());
4838}
4839
4840std::string
4841Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
4842 const TemplateArgument *Args,
4843 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004844 std::string Result;
4845
Douglas Gregore62e6a02009-11-11 19:13:48 +00004846 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00004847 return Result;
4848
4849 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00004850 if (I >= NumArgs)
4851 break;
4852
Douglas Gregorbe999392009-09-15 16:23:51 +00004853 if (I == 0)
4854 Result += "[with ";
4855 else
4856 Result += ", ";
4857
4858 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
4859 Result += Id->getName();
4860 } else {
4861 Result += '$';
4862 Result += llvm::utostr(I);
4863 }
4864
4865 Result += " = ";
4866
4867 switch (Args[I].getKind()) {
4868 case TemplateArgument::Null:
4869 Result += "<no value>";
4870 break;
4871
4872 case TemplateArgument::Type: {
4873 std::string TypeStr;
4874 Args[I].getAsType().getAsStringInternal(TypeStr,
4875 Context.PrintingPolicy);
4876 Result += TypeStr;
4877 break;
4878 }
4879
4880 case TemplateArgument::Declaration: {
4881 bool Unnamed = true;
4882 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
4883 if (ND->getDeclName()) {
4884 Unnamed = false;
4885 Result += ND->getNameAsString();
4886 }
4887 }
4888
4889 if (Unnamed) {
4890 Result += "<anonymous>";
4891 }
4892 break;
4893 }
4894
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004895 case TemplateArgument::Template: {
4896 std::string Str;
4897 llvm::raw_string_ostream OS(Str);
4898 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
4899 Result += OS.str();
4900 break;
4901 }
4902
Douglas Gregorbe999392009-09-15 16:23:51 +00004903 case TemplateArgument::Integral: {
4904 Result += Args[I].getAsIntegral()->toString(10);
4905 break;
4906 }
4907
4908 case TemplateArgument::Expression: {
4909 assert(false && "No expressions in deduced template arguments!");
4910 Result += "<expression>";
4911 break;
4912 }
4913
4914 case TemplateArgument::Pack:
4915 // FIXME: Format template argument packs
4916 Result += "<template argument pack>";
4917 break;
4918 }
4919 }
4920
4921 Result += ']';
4922 return Result;
4923}