blob: 8ff637f2d113744b9f80345a0cff4fea0e607669 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregor2dd078a2009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Douglas Gregor2dd078a2009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000036
Douglas Gregor2dd078a2009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor2dd078a2009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump1eb44332009-09-09 15:08:12 +000061
Douglas Gregor2dd078a2009-09-02 22:59:36 +000062 return 0;
63}
64
John McCallf7a1a742009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
71 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
72 if (!Repl)
73 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCallf7a1a742009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor01e56ae2010-04-12 20:54:26 +000093 }
John McCallf7a1a742009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregor2dd078a2009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000100 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000101 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000102 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000103 TemplateTy &TemplateResult,
104 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000105 assert(getLangOptions().CPlusPlus && "No template names in C!");
106
Douglas Gregor014e88d2009-11-03 23:16:33 +0000107 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000108 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000109
110 switch (Name.getKind()) {
111 case UnqualifiedId::IK_Identifier:
112 TName = DeclarationName(Name.Identifier);
113 break;
114
115 case UnqualifiedId::IK_OperatorFunctionId:
116 TName = Context.DeclarationNames.getCXXOperatorName(
117 Name.OperatorFunctionId.Operator);
118 break;
119
Sean Hunte6252d12009-11-28 08:58:14 +0000120 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000121 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
122 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000123
Douglas Gregor014e88d2009-11-03 23:16:33 +0000124 default:
125 return TNK_Non_template;
126 }
Mike Stump1eb44332009-09-09 15:08:12 +0000127
John McCallf7a1a742009-11-24 19:00:30 +0000128 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Douglas Gregorbfea2392009-12-31 08:11:17 +0000130 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
131 LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +0000132 R.suppressDiagnostics();
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000133 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
134 MemberOfUnknownSpecialization);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000135 if (R.empty() || R.isAmbiguous())
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000136 return TNK_Non_template;
137
John McCall0bd6feb2009-12-02 08:04:21 +0000138 TemplateName Template;
139 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000140
John McCall0bd6feb2009-12-02 08:04:21 +0000141 unsigned ResultCount = R.end() - R.begin();
142 if (ResultCount > 1) {
143 // We assume that we'll preserve the qualifier from a function
144 // template name in other ways.
145 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
146 TemplateKind = TNK_Function_template;
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000147 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000148 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
149
150 if (SS.isSet() && !SS.isInvalid()) {
151 NestedNameSpecifier *Qualifier
152 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
153 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
154 } else {
155 Template = TemplateName(TD);
156 }
157
158 if (isa<FunctionTemplateDecl>(TD))
159 TemplateKind = TNK_Function_template;
160 else {
161 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
162 TemplateKind = TNK_Type_template;
163 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000164 }
Mike Stump1eb44332009-09-09 15:08:12 +0000165
John McCall0bd6feb2009-12-02 08:04:21 +0000166 TemplateResult = TemplateTy::make(Template);
167 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000168}
169
Douglas Gregor84d0a192010-01-12 21:28:44 +0000170bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
171 SourceLocation IILoc,
172 Scope *S,
173 const CXXScopeSpec *SS,
174 TemplateTy &SuggestedTemplate,
175 TemplateNameKind &SuggestedKind) {
176 // We can't recover unless there's a dependent scope specifier preceding the
177 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000178 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000179 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
180 computeDeclContext(*SS))
181 return false;
182
183 // The code is missing a 'template' keyword prior to the dependent template
184 // name.
185 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
186 Diag(IILoc, diag::err_template_kw_missing)
187 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000188 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000189 SuggestedTemplate
190 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
191 SuggestedKind = TNK_Dependent_template_name;
192 return true;
193}
194
John McCallf7a1a742009-11-24 19:00:30 +0000195void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000196 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000197 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000198 bool EnteringContext,
199 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000200 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000201 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000202 DeclContext *LookupCtx = 0;
203 bool isDependent = false;
204 if (!ObjectType.isNull()) {
205 // This nested-name-specifier occurs in a member access expression, e.g.,
206 // x->B::f, and we are looking into the type of the object.
207 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
208 LookupCtx = computeDeclContext(ObjectType);
209 isDependent = ObjectType->isDependentType();
210 assert((isDependent || !ObjectType->isIncompleteType()) &&
211 "Caller should have completed object type");
212 } else if (SS.isSet()) {
213 // This nested-name-specifier occurs after another nested-name-specifier,
214 // so long into the context associated with the prior nested-name-specifier.
215 LookupCtx = computeDeclContext(SS, EnteringContext);
216 isDependent = isDependentScopeSpecifier(SS);
217
218 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000219 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000220 return;
221 }
222
223 bool ObjectTypeSearchedInScope = false;
224 if (LookupCtx) {
225 // Perform "qualified" name lookup into the declaration context we
226 // computed, which is either the type of the base of a member access
227 // expression or the declaration context associated with a prior
228 // nested-name-specifier.
229 LookupQualifiedName(Found, LookupCtx);
230
231 if (!ObjectType.isNull() && Found.empty()) {
232 // C++ [basic.lookup.classref]p1:
233 // In a class member access expression (5.2.5), if the . or -> token is
234 // immediately followed by an identifier followed by a <, the
235 // identifier must be looked up to determine whether the < is the
236 // beginning of a template argument list (14.2) or a less-than operator.
237 // The identifier is first looked up in the class of the object
238 // expression. If the identifier is not found, it is then looked up in
239 // the context of the entire postfix-expression and shall name a class
240 // or function template.
241 //
242 // FIXME: When we're instantiating a template, do we actually have to
243 // look in the scope of the template? Seems fishy...
244 if (S) LookupName(Found, S);
245 ObjectTypeSearchedInScope = true;
246 }
247 } else if (isDependent) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000248 // We cannot look into a dependent object type or nested nme
249 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000250 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000251 return;
252 } else {
253 // Perform unqualified name lookup in the current scope.
254 LookupName(Found, S);
255 }
256
Douglas Gregor2e933882010-01-12 17:06:20 +0000257 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000258 // If we did not find any names, attempt to correct any typos.
259 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000260 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
261 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000262 FilterAcceptableTemplateNames(Context, Found);
263 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
264 if (LookupCtx)
265 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
266 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000267 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000268 Found.getLookupName().getAsString());
269 else
270 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
271 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000272 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000273 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000274 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
275 Diag(Template->getLocation(), diag::note_previous_decl)
276 << Template->getDeclName();
Douglas Gregorbfea2392009-12-31 08:11:17 +0000277 } else
278 Found.clear();
279 } else {
280 Found.clear();
281 }
282 }
283
John McCallf7a1a742009-11-24 19:00:30 +0000284 FilterAcceptableTemplateNames(Context, Found);
285 if (Found.empty())
286 return;
287
288 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
289 // C++ [basic.lookup.classref]p1:
290 // [...] If the lookup in the class of the object expression finds a
291 // template, the name is also looked up in the context of the entire
292 // postfix-expression and [...]
293 //
294 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
295 LookupOrdinaryName);
296 LookupName(FoundOuter, S);
297 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000298
John McCallf7a1a742009-11-24 19:00:30 +0000299 if (FoundOuter.empty()) {
300 // - if the name is not found, the name found in the class of the
301 // object expression is used, otherwise
302 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
303 // - if the name is found in the context of the entire
304 // postfix-expression and does not name a class template, the name
305 // found in the class of the object expression is used, otherwise
306 } else {
307 // - if the name found is a class template, it must refer to the same
308 // entity as the one found in the class of the object expression,
309 // otherwise the program is ill-formed.
310 if (!Found.isSingleResult() ||
311 Found.getFoundDecl()->getCanonicalDecl()
312 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
313 Diag(Found.getNameLoc(),
314 diag::err_nested_name_member_ref_lookup_ambiguous)
315 << Found.getLookupName();
316 Diag(Found.getRepresentativeDecl()->getLocation(),
317 diag::note_ambig_member_ref_object_type)
318 << ObjectType;
319 Diag(FoundOuter.getFoundDecl()->getLocation(),
320 diag::note_ambig_member_ref_scope);
321
322 // Recover by taking the template that we found in the object
323 // expression's type.
324 }
325 }
326 }
327}
328
John McCall2f841ba2009-12-02 03:53:29 +0000329/// ActOnDependentIdExpression - Handle a dependent id-expression that
330/// was just parsed. This is only possible with an explicit scope
331/// specifier naming a dependent type.
John McCallf7a1a742009-11-24 19:00:30 +0000332Sema::OwningExprResult
333Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
334 DeclarationName Name,
335 SourceLocation NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000336 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000337 const TemplateArgumentListInfo *TemplateArgs) {
338 NestedNameSpecifier *Qualifier
339 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000340
341 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000342
John McCall2f841ba2009-12-02 03:53:29 +0000343 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000344 isa<CXXMethodDecl>(DC) &&
345 cast<CXXMethodDecl>(DC)->isInstance()) {
346 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000347
John McCallf7a1a742009-11-24 19:00:30 +0000348 // Since the 'this' expression is synthesized, we don't need to
349 // perform the double-lookup check.
350 NamedDecl *FirstQualifierInScope = 0;
351
John McCallaa81e162009-12-01 22:10:20 +0000352 return Owned(CXXDependentScopeMemberExpr::Create(Context,
353 /*This*/ 0, ThisType,
354 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000355 /*Op*/ SourceLocation(),
356 Qualifier, SS.getRange(),
357 FirstQualifierInScope,
358 Name, NameLoc,
359 TemplateArgs));
360 }
361
362 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
363}
364
365Sema::OwningExprResult
366Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
367 DeclarationName Name,
368 SourceLocation NameLoc,
369 const TemplateArgumentListInfo *TemplateArgs) {
370 return Owned(DependentScopeDeclRefExpr::Create(Context,
371 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
372 SS.getRange(),
373 Name, NameLoc,
374 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000375}
376
Douglas Gregor72c3f312008-12-05 18:15:24 +0000377/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
378/// that the template parameter 'PrevDecl' is being shadowed by a new
379/// declaration at location Loc. Returns true to indicate that this is
380/// an error, and false otherwise.
381bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000382 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000383
384 // Microsoft Visual C++ permits template parameters to be shadowed.
385 if (getLangOptions().Microsoft)
386 return false;
387
388 // C++ [temp.local]p4:
389 // A template-parameter shall not be redeclared within its
390 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000391 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000392 << cast<NamedDecl>(PrevDecl)->getDeclName();
393 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
394 return true;
395}
396
Douglas Gregor2943aed2009-03-03 04:44:36 +0000397/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000398/// the parameter D to reference the templated declaration and return a pointer
399/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000400TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000401 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000402 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000403 return Temp;
404 }
405 return 0;
406}
407
Douglas Gregor788cd062009-11-11 01:00:40 +0000408static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
409 const ParsedTemplateArgument &Arg) {
410
411 switch (Arg.getKind()) {
412 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000413 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000414 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
415 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000416 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000417 return TemplateArgumentLoc(TemplateArgument(T), DI);
418 }
419
420 case ParsedTemplateArgument::NonType: {
421 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
422 return TemplateArgumentLoc(TemplateArgument(E), E);
423 }
424
425 case ParsedTemplateArgument::Template: {
426 TemplateName Template
427 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
428 return TemplateArgumentLoc(TemplateArgument(Template),
429 Arg.getScopeSpec().getRange(),
430 Arg.getLocation());
431 }
432 }
433
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000434 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000435 return TemplateArgumentLoc();
436}
437
438/// \brief Translates template arguments as provided by the parser
439/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000440void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
441 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000442 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000443 TemplateArgs.addArgument(translateTemplateArgument(*this,
444 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000445}
446
Douglas Gregor72c3f312008-12-05 18:15:24 +0000447/// ActOnTypeParameter - Called when a C++ template type parameter
448/// (e.g., "typename T") has been parsed. Typename specifies whether
449/// the keyword "typename" was used to declare the type parameter
450/// (otherwise, "class" was used), and KeyLoc is the location of the
451/// "class" or "typename" keyword. ParamName is the name of the
452/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000453/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000454/// If the type parameter has a default argument, it will be added
455/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000456Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000457 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000458 SourceLocation KeyLoc,
459 IdentifierInfo *ParamName,
460 SourceLocation ParamNameLoc,
461 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000462 assert(S->isTemplateParamScope() &&
463 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000464 bool Invalid = false;
465
466 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000467 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000468 LookupOrdinaryName,
469 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000470 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000471 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000472 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000473 }
474
Douglas Gregorddc29e12009-02-06 22:42:48 +0000475 SourceLocation Loc = ParamNameLoc;
476 if (!ParamName)
477 Loc = KeyLoc;
478
Douglas Gregor72c3f312008-12-05 18:15:24 +0000479 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000480 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
481 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000482 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000483 if (Invalid)
484 Param->setInvalidDecl();
485
486 if (ParamName) {
487 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000488 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000489 IdResolver.AddDecl(Param);
490 }
491
Chris Lattnerb28317a2009-03-28 19:18:32 +0000492 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000493}
494
Douglas Gregord684b002009-02-10 19:49:53 +0000495/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000496/// Default) to the given template type parameter (TypeParam).
497void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000498 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000499 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000500 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000501 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000502 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000503
John McCalla93c9342009-12-07 02:54:59 +0000504 TypeSourceInfo *DefaultTInfo;
505 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000506
John McCalla93c9342009-12-07 02:54:59 +0000507 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000508
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000509 // C++0x [temp.param]p9:
510 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000511 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000512 if (Parm->isParameterPack()) {
513 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000514 return;
515 }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Douglas Gregord684b002009-02-10 19:49:53 +0000517 // C++ [temp.param]p14:
518 // A template-parameter shall not be used in its own default argument.
519 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Douglas Gregord684b002009-02-10 19:49:53 +0000521 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000522 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000523 Parm->setInvalidDecl();
524 return;
525 }
526
John McCalla93c9342009-12-07 02:54:59 +0000527 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000528}
529
Douglas Gregor2943aed2009-03-03 04:44:36 +0000530/// \brief Check that the type of a non-type template parameter is
531/// well-formed.
532///
533/// \returns the (possibly-promoted) parameter type if valid;
534/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000535QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000536Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
537 // C++ [temp.param]p4:
538 //
539 // A non-type template-parameter shall have one of the following
540 // (optionally cv-qualified) types:
541 //
542 // -- integral or enumeration type,
543 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000544 // -- pointer to object or pointer to function,
545 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000546 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
547 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000548 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000549 T->isReferenceType() ||
550 // -- pointer to member.
551 T->isMemberPointerType() ||
552 // If T is a dependent type, we can't do the check now, so we
553 // assume that it is well-formed.
554 T->isDependentType())
555 return T;
556 // C++ [temp.param]p8:
557 //
558 // A non-type template-parameter of type "array of T" or
559 // "function returning T" is adjusted to be of type "pointer to
560 // T" or "pointer to function returning T", respectively.
561 else if (T->isArrayType())
562 // FIXME: Keep the type prior to promotion?
563 return Context.getArrayDecayedType(T);
564 else if (T->isFunctionType())
565 // FIXME: Keep the type prior to promotion?
566 return Context.getPointerType(T);
567
568 Diag(Loc, diag::err_template_nontype_parm_bad_type)
569 << T;
570
571 return QualType();
572}
573
Douglas Gregor72c3f312008-12-05 18:15:24 +0000574/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
575/// template parameter (e.g., "int Size" in "template<int Size>
576/// class Array") has been parsed. S is the current scope and D is
577/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000578Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000579 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000580 unsigned Position) {
John McCalla93c9342009-12-07 02:54:59 +0000581 TypeSourceInfo *TInfo = 0;
582 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000583
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000584 assert(S->isTemplateParamScope() &&
585 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000586 bool Invalid = false;
587
588 IdentifierInfo *ParamName = D.getIdentifier();
589 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000590 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000591 LookupOrdinaryName,
592 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000593 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000594 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000595 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000596 }
597
Douglas Gregor2943aed2009-03-03 04:44:36 +0000598 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000599 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000600 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000601 Invalid = true;
602 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000603
Douglas Gregor72c3f312008-12-05 18:15:24 +0000604 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000605 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
606 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000607 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000608 if (Invalid)
609 Param->setInvalidDecl();
610
611 if (D.getIdentifier()) {
612 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000613 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000614 IdResolver.AddDecl(Param);
615 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000616 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000617}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000618
Douglas Gregord684b002009-02-10 19:49:53 +0000619/// \brief Adds a default argument to the given non-type template
620/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000621void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000622 SourceLocation EqualLoc,
623 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000624 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000625 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000626 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Douglas Gregord684b002009-02-10 19:49:53 +0000628 // C++ [temp.param]p14:
629 // A template-parameter shall not be used in its own default argument.
630 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Douglas Gregord684b002009-02-10 19:49:53 +0000632 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000633 TemplateArgument Converted;
634 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
635 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000636 TemplateParm->setInvalidDecl();
637 return;
638 }
639
Anders Carlssone9146f22009-05-01 19:49:17 +0000640 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregord684b002009-02-10 19:49:53 +0000641}
642
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000643
644/// ActOnTemplateTemplateParameter - Called when a C++ template template
645/// parameter (e.g. T in template <template <typename> class T> class array)
646/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000647Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
648 SourceLocation TmpLoc,
649 TemplateParamsTy *Params,
650 IdentifierInfo *Name,
651 SourceLocation NameLoc,
652 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000653 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000654 assert(S->isTemplateParamScope() &&
655 "Template template parameter not in template parameter scope!");
656
657 // Construct the parameter object.
658 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000659 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
660 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000661 (TemplateParameterList*)Params);
662
663 // Make sure the parameter is valid.
664 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
665 // do anything yet. However, if the template parameter list or (eventual)
666 // default value is ever invalidated, that will propagate here.
667 bool Invalid = false;
668 if (Invalid) {
669 Param->setInvalidDecl();
670 }
671
672 // If the tt-param has a name, then link the identifier into the scope
673 // and lookup mechanisms.
674 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000675 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000676 IdResolver.AddDecl(Param);
677 }
678
Chris Lattnerb28317a2009-03-28 19:18:32 +0000679 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000680}
681
Douglas Gregord684b002009-02-10 19:49:53 +0000682/// \brief Adds a default argument to the given template template
683/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000684void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000685 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000686 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000687 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000688 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000689
Douglas Gregord684b002009-02-10 19:49:53 +0000690 // C++ [temp.param]p14:
691 // A template-parameter shall not be used in its own default argument.
692 // FIXME: Implement this check! Needs a recursive walk over the types.
693
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000694 // Check only that we have a template template argument. We don't want to
695 // try to check well-formedness now, because our template template parameter
696 // might have dependent types in its template parameters, which we wouldn't
697 // be able to match now.
698 //
699 // If none of the template template parameter's template arguments mention
700 // other template parameters, we could actually perform more checking here.
701 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000702 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000703 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
704 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
705 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000706 return;
707 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000708
Douglas Gregor788cd062009-11-11 01:00:40 +0000709 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregord684b002009-02-10 19:49:53 +0000710}
711
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000712/// ActOnTemplateParameterList - Builds a TemplateParameterList that
713/// contains the template parameters in Params/NumParams.
714Sema::TemplateParamsTy *
715Sema::ActOnTemplateParameterList(unsigned Depth,
716 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000717 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000718 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000719 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000720 SourceLocation RAngleLoc) {
721 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000722 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000723
Douglas Gregorddc29e12009-02-06 22:42:48 +0000724 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000725 (NamedDecl**)Params, NumParams,
726 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000727}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000728
John McCallb6217662010-03-15 10:12:16 +0000729static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
730 if (SS.isSet())
731 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
732 SS.getRange());
733}
734
Douglas Gregor212e81c2009-03-25 00:13:59 +0000735Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000736Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000737 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000738 IdentifierInfo *Name, SourceLocation NameLoc,
739 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000740 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000741 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000742 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000743 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000744 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000745 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000746
747 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000748 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000749 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000750
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000751 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
752 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000753
754 // There is no such thing as an unnamed class template.
755 if (!Name) {
756 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000757 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000758 }
759
760 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000761 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000762 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000763 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000764 if (SS.isNotEmpty() && !SS.isInvalid()) {
765 SemanticContext = computeDeclContext(SS, true);
766 if (!SemanticContext) {
767 // FIXME: Produce a reasonable diagnostic here
768 return true;
769 }
Mike Stump1eb44332009-09-09 15:08:12 +0000770
John McCall77bb1aa2010-05-01 00:40:08 +0000771 if (RequireCompleteDeclContext(SS, SemanticContext))
772 return true;
773
John McCalla24dc2e2009-11-17 02:14:36 +0000774 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000775 } else {
776 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000777 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Douglas Gregor57265e32010-04-12 16:00:01 +0000780 if (Previous.isAmbiguous())
781 return true;
782
Douglas Gregorddc29e12009-02-06 22:42:48 +0000783 NamedDecl *PrevDecl = 0;
784 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000785 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000786
Douglas Gregorddc29e12009-02-06 22:42:48 +0000787 // If there is a previous declaration with the same name, check
788 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000789 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000790 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000791
792 // We may have found the injected-class-name of a class template,
793 // class template partial specialization, or class template specialization.
794 // In these cases, grab the template that is being defined or specialized.
795 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
796 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
797 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
798 PrevClassTemplate
799 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
800 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
801 PrevClassTemplate
802 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
803 ->getSpecializedTemplate();
804 }
805 }
806
John McCall65c49462009-12-18 11:25:59 +0000807 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000808 // C++ [namespace.memdef]p3:
809 // [...] When looking for a prior declaration of a class or a function
810 // declared as a friend, and when the name of the friend class or
811 // function is neither a qualified name nor a template-id, scopes outside
812 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000813 if (!SS.isSet()) {
814 DeclContext *OutermostContext = CurContext;
815 while (!OutermostContext->isFileContext())
816 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000817
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000818 if (PrevDecl &&
819 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
820 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
821 SemanticContext = PrevDecl->getDeclContext();
822 } else {
823 // Declarations in outer scopes don't matter. However, the outermost
824 // context we computed is the semantic context for our new
825 // declaration.
826 PrevDecl = PrevClassTemplate = 0;
827 SemanticContext = OutermostContext;
828 }
John McCalle129d442009-12-17 23:21:11 +0000829 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000830
John McCalle129d442009-12-17 23:21:11 +0000831 if (CurContext->isDependentContext()) {
832 // If this is a dependent context, we don't want to link the friend
833 // class template to the template in scope, because that would perform
834 // checking of the template parameter lists that can't be performed
835 // until the outer context is instantiated.
836 PrevDecl = PrevClassTemplate = 0;
837 }
838 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
839 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000840
Douglas Gregorddc29e12009-02-06 22:42:48 +0000841 if (PrevClassTemplate) {
842 // Ensure that the template parameter lists are compatible.
843 if (!TemplateParameterListsAreEqual(TemplateParams,
844 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000845 /*Complain=*/true,
846 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000847 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000848
849 // C++ [temp.class]p4:
850 // In a redeclaration, partial specialization, explicit
851 // specialization or explicit instantiation of a class template,
852 // the class-key shall agree in kind with the original class
853 // template declaration (7.1.5.3).
854 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000855 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000856 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000857 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000858 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000859 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000860 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000861 }
862
Douglas Gregorddc29e12009-02-06 22:42:48 +0000863 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000864 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000865 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000866 Diag(NameLoc, diag::err_redefinition) << Name;
867 Diag(Def->getLocation(), diag::note_previous_definition);
868 // FIXME: Would it make sense to try to "forget" the previous
869 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000870 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000871 }
872 }
873 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
874 // Maybe we will complain about the shadowed template parameter.
875 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
876 // Just pretend that we didn't see the previous declaration.
877 PrevDecl = 0;
878 } else if (PrevDecl) {
879 // C++ [temp]p5:
880 // A class template shall not have the same name as any other
881 // template, class, function, object, enumeration, enumerator,
882 // namespace, or type in the same scope (3.3), except as specified
883 // in (14.5.4).
884 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
885 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000886 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000887 }
888
Douglas Gregord684b002009-02-10 19:49:53 +0000889 // Check the template parameter list of this declaration, possibly
890 // merging in the template parameter list from the previous class
891 // template declaration.
892 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000893 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
894 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000895 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Douglas Gregor57265e32010-04-12 16:00:01 +0000897 if (SS.isSet()) {
898 // If the name of the template was qualified, we must be defining the
899 // template out-of-line.
900 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
901 !(TUK == TUK_Friend && CurContext->isDependentContext()))
902 Diag(NameLoc, diag::err_member_def_does_not_match)
903 << Name << SemanticContext << SS.getRange();
904 }
905
Mike Stump1eb44332009-09-09 15:08:12 +0000906 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000907 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000908 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000909 PrevClassTemplate->getTemplatedDecl() : 0,
910 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000911 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000912
913 ClassTemplateDecl *NewTemplate
914 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
915 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000916 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000917 NewClass->setDescribedClassTemplate(NewTemplate);
918
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000919 // Build the type for the class template declaration now.
John McCall3cb0ebd2010-03-10 03:28:59 +0000920 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
921 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000922 assert(T->isDependentType() && "Class template type is not dependent?");
923 (void)T;
924
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000925 // If we are providing an explicit specialization of a member that is a
926 // class template, make a note of that.
927 if (PrevClassTemplate &&
928 PrevClassTemplate->getInstantiatedFromMemberTemplate())
929 PrevClassTemplate->setMemberSpecialization();
930
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000931 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000932 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000933 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Douglas Gregorddc29e12009-02-06 22:42:48 +0000935 // Set the lexical context of these templates
936 NewClass->setLexicalDeclContext(CurContext);
937 NewTemplate->setLexicalDeclContext(CurContext);
938
John McCall0f434ec2009-07-31 02:45:11 +0000939 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000940 NewClass->startDefinition();
941
942 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000943 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000944
John McCall05b23ea2009-09-14 21:59:20 +0000945 if (TUK != TUK_Friend)
946 PushOnScopeChains(NewTemplate, S);
947 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000948 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000949 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000950 NewClass->setAccess(PrevClassTemplate->getAccess());
951 }
John McCall05b23ea2009-09-14 21:59:20 +0000952
Douglas Gregord85bea22009-09-26 06:47:28 +0000953 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
954 PrevClassTemplate != NULL);
955
John McCall05b23ea2009-09-14 21:59:20 +0000956 // Friend templates are visible in fairly strange ways.
957 if (!CurContext->isDependentContext()) {
958 DeclContext *DC = SemanticContext->getLookupContext();
959 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
960 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
961 PushOnScopeChains(NewTemplate, EnclosingScope,
962 /* AddToContext = */ false);
963 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000964
965 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
966 NewClass->getLocation(),
967 NewTemplate,
968 /*FIXME:*/NewClass->getLocation());
969 Friend->setAccess(AS_public);
970 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000971 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000972
Douglas Gregord684b002009-02-10 19:49:53 +0000973 if (Invalid) {
974 NewTemplate->setInvalidDecl();
975 NewClass->setInvalidDecl();
976 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000977 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000978}
979
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000980/// \brief Diagnose the presence of a default template argument on a
981/// template parameter, which is ill-formed in certain contexts.
982///
983/// \returns true if the default template argument should be dropped.
984static bool DiagnoseDefaultTemplateArgument(Sema &S,
985 Sema::TemplateParamListContext TPC,
986 SourceLocation ParamLoc,
987 SourceRange DefArgRange) {
988 switch (TPC) {
989 case Sema::TPC_ClassTemplate:
990 return false;
991
992 case Sema::TPC_FunctionTemplate:
993 // C++ [temp.param]p9:
994 // A default template-argument shall not be specified in a
995 // function template declaration or a function template
996 // definition [...]
997 // (This sentence is not in C++0x, per DR226).
998 if (!S.getLangOptions().CPlusPlus0x)
999 S.Diag(ParamLoc,
1000 diag::err_template_parameter_default_in_function_template)
1001 << DefArgRange;
1002 return false;
1003
1004 case Sema::TPC_ClassTemplateMember:
1005 // C++0x [temp.param]p9:
1006 // A default template-argument shall not be specified in the
1007 // template-parameter-lists of the definition of a member of a
1008 // class template that appears outside of the member's class.
1009 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1010 << DefArgRange;
1011 return true;
1012
1013 case Sema::TPC_FriendFunctionTemplate:
1014 // C++ [temp.param]p9:
1015 // A default template-argument shall not be specified in a
1016 // friend template declaration.
1017 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1018 << DefArgRange;
1019 return true;
1020
1021 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1022 // for friend function templates if there is only a single
1023 // declaration (and it is a definition). Strange!
1024 }
1025
1026 return false;
1027}
1028
Douglas Gregord684b002009-02-10 19:49:53 +00001029/// \brief Checks the validity of a template parameter list, possibly
1030/// considering the template parameter list from a previous
1031/// declaration.
1032///
1033/// If an "old" template parameter list is provided, it must be
1034/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1035/// template parameter list.
1036///
1037/// \param NewParams Template parameter list for a new template
1038/// declaration. This template parameter list will be updated with any
1039/// default arguments that are carried through from the previous
1040/// template parameter list.
1041///
1042/// \param OldParams If provided, template parameter list from a
1043/// previous declaration of the same template. Default template
1044/// arguments will be merged from the old template parameter list to
1045/// the new template parameter list.
1046///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001047/// \param TPC Describes the context in which we are checking the given
1048/// template parameter list.
1049///
Douglas Gregord684b002009-02-10 19:49:53 +00001050/// \returns true if an error occurred, false otherwise.
1051bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001052 TemplateParameterList *OldParams,
1053 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001054 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregord684b002009-02-10 19:49:53 +00001056 // C++ [temp.param]p10:
1057 // The set of default template-arguments available for use with a
1058 // template declaration or definition is obtained by merging the
1059 // default arguments from the definition (if in scope) and all
1060 // declarations in scope in the same way default function
1061 // arguments are (8.3.6).
1062 bool SawDefaultArgument = false;
1063 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001064
Anders Carlsson49d25572009-06-12 23:20:15 +00001065 bool SawParameterPack = false;
1066 SourceLocation ParameterPackLoc;
1067
Mike Stump1a35fde2009-02-11 23:03:27 +00001068 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001069 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001070 if (OldParams)
1071 OldParam = OldParams->begin();
1072
1073 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1074 NewParamEnd = NewParams->end();
1075 NewParam != NewParamEnd; ++NewParam) {
1076 // Variables used to diagnose redundant default arguments
1077 bool RedundantDefaultArg = false;
1078 SourceLocation OldDefaultLoc;
1079 SourceLocation NewDefaultLoc;
1080
1081 // Variables used to diagnose missing default arguments
1082 bool MissingDefaultArg = false;
1083
Anders Carlsson49d25572009-06-12 23:20:15 +00001084 // C++0x [temp.param]p11:
1085 // If a template parameter of a class template is a template parameter pack,
1086 // it must be the last template parameter.
1087 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001088 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001089 diag::err_template_param_pack_must_be_last_template_parameter);
1090 Invalid = true;
1091 }
1092
Douglas Gregord684b002009-02-10 19:49:53 +00001093 if (TemplateTypeParmDecl *NewTypeParm
1094 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001095 // Check the presence of a default argument here.
1096 if (NewTypeParm->hasDefaultArgument() &&
1097 DiagnoseDefaultTemplateArgument(*this, TPC,
1098 NewTypeParm->getLocation(),
1099 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001100 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001101 NewTypeParm->removeDefaultArgument();
1102
1103 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001104 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001105 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Anders Carlsson49d25572009-06-12 23:20:15 +00001107 if (NewTypeParm->isParameterPack()) {
1108 assert(!NewTypeParm->hasDefaultArgument() &&
1109 "Parameter packs can't have a default argument!");
1110 SawParameterPack = true;
1111 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001112 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001113 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001114 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1115 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1116 SawDefaultArgument = true;
1117 RedundantDefaultArg = true;
1118 PreviousDefaultArgLoc = NewDefaultLoc;
1119 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1120 // Merge the default argument from the old declaration to the
1121 // new declaration.
1122 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001123 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001124 true);
1125 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1126 } else if (NewTypeParm->hasDefaultArgument()) {
1127 SawDefaultArgument = true;
1128 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1129 } else if (SawDefaultArgument)
1130 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001131 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001132 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001133 // Check the presence of a default argument here.
1134 if (NewNonTypeParm->hasDefaultArgument() &&
1135 DiagnoseDefaultTemplateArgument(*this, TPC,
1136 NewNonTypeParm->getLocation(),
1137 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1138 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1139 NewNonTypeParm->setDefaultArgument(0);
1140 }
1141
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001142 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001143 NonTypeTemplateParmDecl *OldNonTypeParm
1144 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001145 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001146 NewNonTypeParm->hasDefaultArgument()) {
1147 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1148 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1149 SawDefaultArgument = true;
1150 RedundantDefaultArg = true;
1151 PreviousDefaultArgLoc = NewDefaultLoc;
1152 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1153 // Merge the default argument from the old declaration to the
1154 // new declaration.
1155 SawDefaultArgument = true;
1156 // FIXME: We need to create a new kind of "default argument"
1157 // expression that points to a previous template template
1158 // parameter.
1159 NewNonTypeParm->setDefaultArgument(
1160 OldNonTypeParm->getDefaultArgument());
1161 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1162 } else if (NewNonTypeParm->hasDefaultArgument()) {
1163 SawDefaultArgument = true;
1164 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1165 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001166 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001167 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001168 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001169 TemplateTemplateParmDecl *NewTemplateParm
1170 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001171 if (NewTemplateParm->hasDefaultArgument() &&
1172 DiagnoseDefaultTemplateArgument(*this, TPC,
1173 NewTemplateParm->getLocation(),
1174 NewTemplateParm->getDefaultArgument().getSourceRange()))
1175 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1176
1177 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001178 TemplateTemplateParmDecl *OldTemplateParm
1179 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001180 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001181 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001182 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1183 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001184 SawDefaultArgument = true;
1185 RedundantDefaultArg = true;
1186 PreviousDefaultArgLoc = NewDefaultLoc;
1187 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1188 // Merge the default argument from the old declaration to the
1189 // new declaration.
1190 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001191 // FIXME: We need to create a new kind of "default argument" expression
1192 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001193 NewTemplateParm->setDefaultArgument(
1194 OldTemplateParm->getDefaultArgument());
Douglas Gregor788cd062009-11-11 01:00:40 +00001195 PreviousDefaultArgLoc
1196 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001197 } else if (NewTemplateParm->hasDefaultArgument()) {
1198 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001199 PreviousDefaultArgLoc
1200 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001201 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001202 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001203 }
1204
1205 if (RedundantDefaultArg) {
1206 // C++ [temp.param]p12:
1207 // A template-parameter shall not be given default arguments
1208 // by two different declarations in the same scope.
1209 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1210 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1211 Invalid = true;
1212 } else if (MissingDefaultArg) {
1213 // C++ [temp.param]p11:
1214 // If a template-parameter has a default template-argument,
1215 // all subsequent template-parameters shall have a default
1216 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001217 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001218 diag::err_template_param_default_arg_missing);
1219 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1220 Invalid = true;
1221 }
1222
1223 // If we have an old template parameter list that we're merging
1224 // in, move on to the next parameter.
1225 if (OldParams)
1226 ++OldParam;
1227 }
1228
1229 return Invalid;
1230}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001231
Mike Stump1eb44332009-09-09 15:08:12 +00001232/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001233/// specifier, returning the template parameter list that applies to the
1234/// name.
1235///
1236/// \param DeclStartLoc the start of the declaration that has a scope
1237/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001238///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001239/// \param SS the scope specifier that will be matched to the given template
1240/// parameter lists. This scope specifier precedes a qualified name that is
1241/// being declared.
1242///
1243/// \param ParamLists the template parameter lists, from the outermost to the
1244/// innermost template parameter lists.
1245///
1246/// \param NumParamLists the number of template parameter lists in ParamLists.
1247///
John McCall77e8b112010-04-13 20:37:33 +00001248/// \param IsFriend Whether to apply the slightly different rules for
1249/// matching template parameters to scope specifiers in friend
1250/// declarations.
1251///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001252/// \param IsExplicitSpecialization will be set true if the entity being
1253/// declared is an explicit specialization, false otherwise.
1254///
Mike Stump1eb44332009-09-09 15:08:12 +00001255/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001256/// name that is preceded by the scope specifier @p SS. This template
1257/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001258/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001259/// template specialization), or may be NULL (if we were's declaring isn't
1260/// itself a template).
1261TemplateParameterList *
1262Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1263 const CXXScopeSpec &SS,
1264 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001265 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001266 bool IsFriend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001267 bool &IsExplicitSpecialization) {
1268 IsExplicitSpecialization = false;
1269
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001270 // Find the template-ids that occur within the nested-name-specifier. These
1271 // template-ids will match up with the template parameter lists.
1272 llvm::SmallVector<const TemplateSpecializationType *, 4>
1273 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001274 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1275 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001276 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1277 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001278 const Type *T = NNS->getAsType();
1279 if (!T) break;
1280
1281 // C++0x [temp.expl.spec]p17:
1282 // A member or a member template may be nested within many
1283 // enclosing class templates. In an explicit specialization for
1284 // such a member, the member declaration shall be preceded by a
1285 // template<> for each enclosing class template that is
1286 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001287 //
1288 // Following the existing practice of GNU and EDG, we allow a typedef of a
1289 // template specialization type.
1290 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1291 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001292
Mike Stump1eb44332009-09-09 15:08:12 +00001293 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001294 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001295 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1296 if (!Template)
1297 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Ted Kremenek6217b802009-07-29 21:53:49 +00001299 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001300 ClassTemplateSpecializationDecl *SpecDecl
1301 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1302 // If the nested name specifier refers to an explicit specialization,
1303 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001304 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1305 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001306 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001307 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001308 }
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001310 TemplateIdsInSpecifier.push_back(SpecType);
1311 }
1312 }
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001314 // Reverse the list of template-ids in the scope specifier, so that we can
1315 // more easily match up the template-ids and the template parameter lists.
1316 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001318 SourceLocation FirstTemplateLoc = DeclStartLoc;
1319 if (NumParamLists)
1320 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001322 // Match the template-ids found in the specifier to the template parameter
1323 // lists.
1324 unsigned Idx = 0;
1325 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1326 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001327 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1328 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001329 if (Idx >= NumParamLists) {
1330 // We have a template-id without a corresponding template parameter
1331 // list.
John McCall77e8b112010-04-13 20:37:33 +00001332
1333 // ...which is fine if this is a friend declaration.
1334 if (IsFriend) {
1335 IsExplicitSpecialization = true;
1336 break;
1337 }
1338
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001339 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001340 // FIXME: the location information here isn't great.
1341 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001342 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001343 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001344 << SS.getRange();
1345 } else {
1346 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1347 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001348 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001349 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001350 }
1351 return 0;
1352 }
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001354 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001355 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001356 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001357
John McCall31f17ec2010-04-27 00:57:59 +00001358 // Are there cases in (e.g.) friends where this won't match?
1359 if (const InjectedClassNameType *Injected
1360 = TemplateId->getAs<InjectedClassNameType>()) {
1361 CXXRecordDecl *Record = Injected->getDecl();
1362 if (ClassTemplatePartialSpecializationDecl *Partial =
1363 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1364 ExpectedTemplateParams = Partial->getTemplateParameters();
1365 else
1366 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1367 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001368 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001369
John McCall31f17ec2010-04-27 00:57:59 +00001370 if (ExpectedTemplateParams)
1371 TemplateParameterListsAreEqual(ParamLists[Idx],
1372 ExpectedTemplateParams,
1373 true, TPL_TemplateMatch);
1374
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001375 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001376 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001377 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001378 diag::err_template_param_list_matches_nontemplate)
1379 << TemplateId
1380 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001381 else
1382 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001385 // If there were at least as many template-ids as there were template
1386 // parameter lists, then there are no template parameter lists remaining for
1387 // the declaration itself.
1388 if (Idx >= NumParamLists)
1389 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001391 // If there were too many template parameter lists, complain about that now.
1392 if (Idx != NumParamLists - 1) {
1393 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001394 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001395 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001396 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1397 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001398 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1399 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001400
1401 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1402 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1403 diag::note_explicit_template_spec_does_not_need_header)
1404 << ExplicitSpecializationsInSpecifier.back();
1405 ExplicitSpecializationsInSpecifier.pop_back();
1406 }
1407
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001408 ++Idx;
1409 }
1410 }
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001412 // Return the last template parameter list, which corresponds to the
1413 // entity being declared.
1414 return ParamLists[NumParamLists - 1];
1415}
1416
Douglas Gregor7532dc62009-03-30 22:58:21 +00001417QualType Sema::CheckTemplateIdType(TemplateName Name,
1418 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001419 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001420 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001421 if (!Template) {
1422 // The template name does not resolve to a template, so we just
1423 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001424 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001425 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001426
Douglas Gregor40808ce2009-03-09 23:48:35 +00001427 // Check that the template argument list is well-formed for this
1428 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001429 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001430 TemplateArgs.size());
1431 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001432 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001433 return QualType();
1434
Mike Stump1eb44332009-09-09 15:08:12 +00001435 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001436 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001437 "Converted template argument list is too short!");
1438
1439 QualType CanonType;
John McCall31f17ec2010-04-27 00:57:59 +00001440 bool IsCurrentInstantiation = false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001441
Douglas Gregorcaddba02009-11-12 18:38:13 +00001442 if (Name.isDependent() ||
1443 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001444 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001445 // This class template specialization is a dependent
1446 // type. Therefore, its canonical type is another class template
1447 // specialization type that contains all of the converted
1448 // arguments in canonical form. This ensures that, e.g., A<T> and
1449 // A<T, T> have identical types when A is declared as:
1450 //
1451 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001452 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001453 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001454 Converted.getFlatArguments(),
1455 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Douglas Gregor1275ae02009-07-28 23:00:59 +00001457 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001458 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001459 // In the future, we need to teach getTemplateSpecializationType to only
1460 // build the canonical type and return that to us.
1461 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001462
1463 // This might work out to be a current instantiation, in which
1464 // case the canonical type needs to be the InjectedClassNameType.
1465 //
1466 // TODO: in theory this could be a simple hashtable lookup; most
1467 // changes to CurContext don't change the set of current
1468 // instantiations.
1469 if (isa<ClassTemplateDecl>(Template)) {
1470 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1471 // If we get out to a namespace, we're done.
1472 if (Ctx->isFileContext()) break;
1473
1474 // If this isn't a record, keep looking.
1475 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1476 if (!Record) continue;
1477
1478 // Look for one of the two cases with InjectedClassNameTypes
1479 // and check whether it's the same template.
1480 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1481 !Record->getDescribedClassTemplate())
1482 continue;
1483
1484 // Fetch the injected class name type and check whether its
1485 // injected type is equal to the type we just built.
1486 QualType ICNT = Context.getTypeDeclType(Record);
1487 QualType Injected = cast<InjectedClassNameType>(ICNT)
1488 ->getInjectedSpecializationType();
1489
1490 if (CanonType != Injected->getCanonicalTypeInternal())
1491 continue;
1492
1493 // If so, the canonical type of this TST is the injected
1494 // class name type of the record we just found.
1495 assert(ICNT.isCanonical());
1496 CanonType = ICNT;
1497 IsCurrentInstantiation = true;
1498 break;
1499 }
1500 }
Mike Stump1eb44332009-09-09 15:08:12 +00001501 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001502 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001503 // Find the class template specialization declaration that
1504 // corresponds to these arguments.
1505 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001506 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001507 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001508 Converted.flatSize(),
1509 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001510 void *InsertPos = 0;
1511 ClassTemplateSpecializationDecl *Decl
1512 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1513 if (!Decl) {
1514 // This is the first time we have referenced this class template
1515 // specialization. Create the canonical declaration and add it to
1516 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001517 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001518 ClassTemplate->getTemplatedDecl()->getTagKind(),
1519 ClassTemplate->getDeclContext(),
1520 ClassTemplate->getLocation(),
1521 ClassTemplate,
1522 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001523 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1524 Decl->setLexicalDeclContext(CurContext);
1525 }
1526
1527 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001528 assert(isa<RecordType>(CanonType) &&
1529 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001530 }
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Douglas Gregor40808ce2009-03-09 23:48:35 +00001532 // Build the fully-sugared type for this class template
1533 // specialization, which refers back to the class template
1534 // specialization we created or found.
John McCall31f17ec2010-04-27 00:57:59 +00001535 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType,
1536 IsCurrentInstantiation);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001537}
1538
Douglas Gregorcc636682009-02-17 23:15:12 +00001539Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001540Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001541 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001542 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001543 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001544 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001545
Douglas Gregor40808ce2009-03-09 23:48:35 +00001546 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001547 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001548 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001549
John McCalld5532b62009-11-23 01:53:49 +00001550 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001551 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001552
1553 if (Result.isNull())
1554 return true;
1555
John McCalla93c9342009-12-07 02:54:59 +00001556 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001557 TemplateSpecializationTypeLoc TL
1558 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1559 TL.setTemplateNameLoc(TemplateLoc);
1560 TL.setLAngleLoc(LAngleLoc);
1561 TL.setRAngleLoc(RAngleLoc);
1562 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1563 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1564
1565 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001566}
John McCallf1bbbb42009-09-04 01:14:41 +00001567
John McCall6b2becf2009-09-08 17:47:29 +00001568Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1569 TagUseKind TUK,
1570 DeclSpec::TST TagSpec,
1571 SourceLocation TagLoc) {
1572 if (TypeResult.isInvalid())
1573 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001574
John McCall833ca992009-10-29 08:12:44 +00001575 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001576 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001577 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001578
John McCall6b2becf2009-09-08 17:47:29 +00001579 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001580 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001581
John McCall6b2becf2009-09-08 17:47:29 +00001582 if (const RecordType *RT = Type->getAs<RecordType>()) {
1583 RecordDecl *D = RT->getDecl();
1584
1585 IdentifierInfo *Id = D->getIdentifier();
1586 assert(Id && "templated class must have an identifier");
1587
1588 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1589 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001590 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001591 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001592 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001593 }
1594 }
1595
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001596 ElaboratedTypeKeyword Keyword
1597 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1598 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001599
1600 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001601}
1602
John McCallf7a1a742009-11-24 19:00:30 +00001603Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1604 LookupResult &R,
1605 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001606 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001607 // FIXME: Can we do any checking at this point? I guess we could check the
1608 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001609 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001610 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001611
1612 // These should be filtered out by our callers.
1613 assert(!R.empty() && "empty lookup results when building templateid");
1614 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1615
1616 NestedNameSpecifier *Qualifier = 0;
1617 SourceRange QualifierRange;
1618 if (SS.isSet()) {
1619 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1620 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001621 }
John McCallc373d482010-01-27 01:50:18 +00001622
1623 // We don't want lookup warnings at this point.
1624 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001625
John McCallf7a1a742009-11-24 19:00:30 +00001626 bool Dependent
1627 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1628 &TemplateArgs);
1629 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001630 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001631 Qualifier, QualifierRange,
1632 R.getLookupName(), R.getNameLoc(),
1633 RequiresADL, TemplateArgs);
John McCallc373d482010-01-27 01:50:18 +00001634 ULE->addDecls(R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001635
1636 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001637}
1638
John McCallf7a1a742009-11-24 19:00:30 +00001639// We actually only call this from template instantiation.
1640Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001641Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001642 DeclarationName Name,
1643 SourceLocation NameLoc,
1644 const TemplateArgumentListInfo &TemplateArgs) {
1645 DeclContext *DC;
1646 if (!(DC = computeDeclContext(SS, false)) ||
1647 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001648 RequireCompleteDeclContext(SS, DC))
John McCallf7a1a742009-11-24 19:00:30 +00001649 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001651 bool MemberOfUnknownSpecialization;
John McCallf7a1a742009-11-24 19:00:30 +00001652 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001653 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1654 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001655
John McCallf7a1a742009-11-24 19:00:30 +00001656 if (R.isAmbiguous())
1657 return ExprError();
1658
1659 if (R.empty()) {
1660 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1661 << Name << SS.getRange();
1662 return ExprError();
1663 }
1664
1665 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1666 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1667 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1668 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1669 return ExprError();
1670 }
1671
1672 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001673}
1674
Douglas Gregorc45c2322009-03-31 00:43:58 +00001675/// \brief Form a dependent template name.
1676///
1677/// This action forms a dependent template name given the template
1678/// name and its (presumably dependent) scope specifier. For
1679/// example, given "MetaFun::template apply", the scope specifier \p
1680/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1681/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001682Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001683Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001684 CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001685 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001686 TypeTy *ObjectType,
1687 bool EnteringContext) {
Douglas Gregor0707bc52010-01-19 16:01:07 +00001688 DeclContext *LookupCtx = 0;
1689 if (SS.isSet())
1690 LookupCtx = computeDeclContext(SS, EnteringContext);
1691 if (!LookupCtx && ObjectType)
1692 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1693 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001694 // C++0x [temp.names]p5:
1695 // If a name prefixed by the keyword template is not the name of
1696 // a template, the program is ill-formed. [Note: the keyword
1697 // template may not be applied to non-template members of class
1698 // templates. -end note ] [ Note: as is the case with the
1699 // typename prefix, the template prefix is allowed in cases
1700 // where it is not strictly necessary; i.e., when the
1701 // nested-name-specifier or the expression on the left of the ->
1702 // or . is not dependent on a template-parameter, or the use
1703 // does not appear in the scope of a template. -end note]
1704 //
1705 // Note: C++03 was more strict here, because it banned the use of
1706 // the "template" keyword prior to a template-name that was not a
1707 // dependent name. C++ DR468 relaxed this requirement (the
1708 // "template" keyword is now permitted). We follow the C++0x
1709 // rules, even in C++03 mode, retroactively applying the DR.
1710 TemplateTy Template;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001711 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001712 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001713 EnteringContext, Template,
1714 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001715 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1716 isa<CXXRecordDecl>(LookupCtx) &&
1717 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001718 // This is a dependent template.
1719 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001720 Diag(Name.getSourceRange().getBegin(),
1721 diag::err_template_kw_refers_to_non_template)
1722 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001723 << Name.getSourceRange()
1724 << TemplateKWLoc;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001725 return TemplateTy();
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001726 } else {
1727 // We found something; return it.
1728 return Template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001729 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001730 }
1731
Mike Stump1eb44332009-09-09 15:08:12 +00001732 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001733 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001734
1735 switch (Name.getKind()) {
1736 case UnqualifiedId::IK_Identifier:
1737 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1738 Name.Identifier));
1739
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001740 case UnqualifiedId::IK_OperatorFunctionId:
1741 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1742 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001743
1744 case UnqualifiedId::IK_LiteralOperatorId:
1745 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1746
Douglas Gregor014e88d2009-11-03 23:16:33 +00001747 default:
1748 break;
1749 }
1750
1751 Diag(Name.getSourceRange().getBegin(),
1752 diag::err_template_kw_refers_to_non_template)
1753 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001754 << Name.getSourceRange()
1755 << TemplateKWLoc;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001756 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001757}
1758
Mike Stump1eb44332009-09-09 15:08:12 +00001759bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001760 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001761 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001762 const TemplateArgument &Arg = AL.getArgument();
1763
Anders Carlsson436b1562009-06-13 00:33:33 +00001764 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001765 switch(Arg.getKind()) {
1766 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001767 // C++ [temp.arg.type]p1:
1768 // A template-argument for a template-parameter which is a
1769 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001770 break;
1771 case TemplateArgument::Template: {
1772 // We have a template type parameter but the template argument
1773 // is a template without any arguments.
1774 SourceRange SR = AL.getSourceRange();
1775 TemplateName Name = Arg.getAsTemplate();
1776 Diag(SR.getBegin(), diag::err_template_missing_args)
1777 << Name << SR;
1778 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1779 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001780
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001781 return true;
1782 }
1783 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001784 // We have a template type parameter but the template argument
1785 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001786 SourceRange SR = AL.getSourceRange();
1787 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001788 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Anders Carlsson436b1562009-06-13 00:33:33 +00001790 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001791 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001792 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001793
John McCalla93c9342009-12-07 02:54:59 +00001794 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001795 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Anders Carlsson436b1562009-06-13 00:33:33 +00001797 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001798 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001799 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001800 return false;
1801}
1802
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001803/// \brief Substitute template arguments into the default template argument for
1804/// the given template type parameter.
1805///
1806/// \param SemaRef the semantic analysis object for which we are performing
1807/// the substitution.
1808///
1809/// \param Template the template that we are synthesizing template arguments
1810/// for.
1811///
1812/// \param TemplateLoc the location of the template name that started the
1813/// template-id we are checking.
1814///
1815/// \param RAngleLoc the location of the right angle bracket ('>') that
1816/// terminates the template-id.
1817///
1818/// \param Param the template template parameter whose default we are
1819/// substituting into.
1820///
1821/// \param Converted the list of template arguments provided for template
1822/// parameters that precede \p Param in the template parameter list.
1823///
1824/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001825static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001826SubstDefaultTemplateArgument(Sema &SemaRef,
1827 TemplateDecl *Template,
1828 SourceLocation TemplateLoc,
1829 SourceLocation RAngleLoc,
1830 TemplateTypeParmDecl *Param,
1831 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001832 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001833
1834 // If the argument type is dependent, instantiate it now based
1835 // on the previously-computed template arguments.
1836 if (ArgType->getType()->isDependentType()) {
1837 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1838 /*TakeArgs=*/false);
1839
1840 MultiLevelTemplateArgumentList AllTemplateArgs
1841 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1842
1843 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1844 Template, Converted.getFlatArguments(),
1845 Converted.flatSize(),
1846 SourceRange(TemplateLoc, RAngleLoc));
1847
1848 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1849 Param->getDefaultArgumentLoc(),
1850 Param->getDeclName());
1851 }
1852
1853 return ArgType;
1854}
1855
1856/// \brief Substitute template arguments into the default template argument for
1857/// the given non-type template parameter.
1858///
1859/// \param SemaRef the semantic analysis object for which we are performing
1860/// the substitution.
1861///
1862/// \param Template the template that we are synthesizing template arguments
1863/// for.
1864///
1865/// \param TemplateLoc the location of the template name that started the
1866/// template-id we are checking.
1867///
1868/// \param RAngleLoc the location of the right angle bracket ('>') that
1869/// terminates the template-id.
1870///
Douglas Gregor788cd062009-11-11 01:00:40 +00001871/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001872/// substituting into.
1873///
1874/// \param Converted the list of template arguments provided for template
1875/// parameters that precede \p Param in the template parameter list.
1876///
1877/// \returns the substituted template argument, or NULL if an error occurred.
1878static Sema::OwningExprResult
1879SubstDefaultTemplateArgument(Sema &SemaRef,
1880 TemplateDecl *Template,
1881 SourceLocation TemplateLoc,
1882 SourceLocation RAngleLoc,
1883 NonTypeTemplateParmDecl *Param,
1884 TemplateArgumentListBuilder &Converted) {
1885 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1886 /*TakeArgs=*/false);
1887
1888 MultiLevelTemplateArgumentList AllTemplateArgs
1889 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1890
1891 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1892 Template, Converted.getFlatArguments(),
1893 Converted.flatSize(),
1894 SourceRange(TemplateLoc, RAngleLoc));
1895
1896 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1897}
1898
Douglas Gregor788cd062009-11-11 01:00:40 +00001899/// \brief Substitute template arguments into the default template argument for
1900/// the given template template parameter.
1901///
1902/// \param SemaRef the semantic analysis object for which we are performing
1903/// the substitution.
1904///
1905/// \param Template the template that we are synthesizing template arguments
1906/// for.
1907///
1908/// \param TemplateLoc the location of the template name that started the
1909/// template-id we are checking.
1910///
1911/// \param RAngleLoc the location of the right angle bracket ('>') that
1912/// terminates the template-id.
1913///
1914/// \param Param the template template parameter whose default we are
1915/// substituting into.
1916///
1917/// \param Converted the list of template arguments provided for template
1918/// parameters that precede \p Param in the template parameter list.
1919///
1920/// \returns the substituted template argument, or NULL if an error occurred.
1921static TemplateName
1922SubstDefaultTemplateArgument(Sema &SemaRef,
1923 TemplateDecl *Template,
1924 SourceLocation TemplateLoc,
1925 SourceLocation RAngleLoc,
1926 TemplateTemplateParmDecl *Param,
1927 TemplateArgumentListBuilder &Converted) {
1928 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1929 /*TakeArgs=*/false);
1930
1931 MultiLevelTemplateArgumentList AllTemplateArgs
1932 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1933
1934 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1935 Template, Converted.getFlatArguments(),
1936 Converted.flatSize(),
1937 SourceRange(TemplateLoc, RAngleLoc));
1938
1939 return SemaRef.SubstTemplateName(
1940 Param->getDefaultArgument().getArgument().getAsTemplate(),
1941 Param->getDefaultArgument().getTemplateNameLoc(),
1942 AllTemplateArgs);
1943}
1944
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001945/// \brief If the given template parameter has a default template
1946/// argument, substitute into that default template argument and
1947/// return the corresponding template argument.
1948TemplateArgumentLoc
1949Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1950 SourceLocation TemplateLoc,
1951 SourceLocation RAngleLoc,
1952 Decl *Param,
1953 TemplateArgumentListBuilder &Converted) {
1954 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1955 if (!TypeParm->hasDefaultArgument())
1956 return TemplateArgumentLoc();
1957
John McCalla93c9342009-12-07 02:54:59 +00001958 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001959 TemplateLoc,
1960 RAngleLoc,
1961 TypeParm,
1962 Converted);
1963 if (DI)
1964 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1965
1966 return TemplateArgumentLoc();
1967 }
1968
1969 if (NonTypeTemplateParmDecl *NonTypeParm
1970 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1971 if (!NonTypeParm->hasDefaultArgument())
1972 return TemplateArgumentLoc();
1973
1974 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1975 TemplateLoc,
1976 RAngleLoc,
1977 NonTypeParm,
1978 Converted);
1979 if (Arg.isInvalid())
1980 return TemplateArgumentLoc();
1981
1982 Expr *ArgE = Arg.takeAs<Expr>();
1983 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1984 }
1985
1986 TemplateTemplateParmDecl *TempTempParm
1987 = cast<TemplateTemplateParmDecl>(Param);
1988 if (!TempTempParm->hasDefaultArgument())
1989 return TemplateArgumentLoc();
1990
1991 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1992 TemplateLoc,
1993 RAngleLoc,
1994 TempTempParm,
1995 Converted);
1996 if (TName.isNull())
1997 return TemplateArgumentLoc();
1998
1999 return TemplateArgumentLoc(TemplateArgument(TName),
2000 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2001 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2002}
2003
Douglas Gregore7526412009-11-11 19:31:23 +00002004/// \brief Check that the given template argument corresponds to the given
2005/// template parameter.
2006bool Sema::CheckTemplateArgument(NamedDecl *Param,
2007 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002008 TemplateDecl *Template,
2009 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002010 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00002011 TemplateArgumentListBuilder &Converted,
2012 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002013 // Check template type parameters.
2014 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002015 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002016
Douglas Gregord9e15302009-11-11 19:41:09 +00002017 // Check non-type template parameters.
2018 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002019 // Do substitution on the type of the non-type template parameter
2020 // with the template arguments we've seen thus far.
2021 QualType NTTPType = NTTP->getType();
2022 if (NTTPType->isDependentType()) {
2023 // Do substitution on the type of the non-type template parameter.
2024 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2025 NTTP, Converted.getFlatArguments(),
2026 Converted.flatSize(),
2027 SourceRange(TemplateLoc, RAngleLoc));
2028
2029 TemplateArgumentList TemplateArgs(Context, Converted,
2030 /*TakeArgs=*/false);
2031 NTTPType = SubstType(NTTPType,
2032 MultiLevelTemplateArgumentList(TemplateArgs),
2033 NTTP->getLocation(),
2034 NTTP->getDeclName());
2035 // If that worked, check the non-type template parameter type
2036 // for validity.
2037 if (!NTTPType.isNull())
2038 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2039 NTTP->getLocation());
2040 if (NTTPType.isNull())
2041 return true;
2042 }
2043
2044 switch (Arg.getArgument().getKind()) {
2045 case TemplateArgument::Null:
2046 assert(false && "Should never see a NULL template argument here");
2047 return true;
2048
2049 case TemplateArgument::Expression: {
2050 Expr *E = Arg.getArgument().getAsExpr();
2051 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002052 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002053 return true;
2054
2055 Converted.Append(Result);
2056 break;
2057 }
2058
2059 case TemplateArgument::Declaration:
2060 case TemplateArgument::Integral:
2061 // We've already checked this template argument, so just copy
2062 // it to the list of converted arguments.
2063 Converted.Append(Arg.getArgument());
2064 break;
2065
2066 case TemplateArgument::Template:
2067 // We were given a template template argument. It may not be ill-formed;
2068 // see below.
2069 if (DependentTemplateName *DTN
2070 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2071 // We have a template argument such as \c T::template X, which we
2072 // parsed as a template template argument. However, since we now
2073 // know that we need a non-type template argument, convert this
2074 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00002075 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2076 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002077 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00002078 DTN->getIdentifier(),
2079 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00002080
2081 TemplateArgument Result;
2082 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2083 return true;
2084
2085 Converted.Append(Result);
2086 break;
2087 }
2088
2089 // We have a template argument that actually does refer to a class
2090 // template, template alias, or template template parameter, and
2091 // therefore cannot be a non-type template argument.
2092 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2093 << Arg.getSourceRange();
2094
2095 Diag(Param->getLocation(), diag::note_template_param_here);
2096 return true;
2097
2098 case TemplateArgument::Type: {
2099 // We have a non-type template parameter but the template
2100 // argument is a type.
2101
2102 // C++ [temp.arg]p2:
2103 // In a template-argument, an ambiguity between a type-id and
2104 // an expression is resolved to a type-id, regardless of the
2105 // form of the corresponding template-parameter.
2106 //
2107 // We warn specifically about this case, since it can be rather
2108 // confusing for users.
2109 QualType T = Arg.getArgument().getAsType();
2110 SourceRange SR = Arg.getSourceRange();
2111 if (T->isFunctionType())
2112 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2113 else
2114 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2115 Diag(Param->getLocation(), diag::note_template_param_here);
2116 return true;
2117 }
2118
2119 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002120 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002121 break;
2122 }
2123
2124 return false;
2125 }
2126
2127
2128 // Check template template parameters.
2129 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2130
2131 // Substitute into the template parameter list of the template
2132 // template parameter, since previously-supplied template arguments
2133 // may appear within the template template parameter.
2134 {
2135 // Set up a template instantiation context.
2136 LocalInstantiationScope Scope(*this);
2137 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2138 TempParm, Converted.getFlatArguments(),
2139 Converted.flatSize(),
2140 SourceRange(TemplateLoc, RAngleLoc));
2141
2142 TemplateArgumentList TemplateArgs(Context, Converted,
2143 /*TakeArgs=*/false);
2144 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2145 SubstDecl(TempParm, CurContext,
2146 MultiLevelTemplateArgumentList(TemplateArgs)));
2147 if (!TempParm)
2148 return true;
2149
2150 // FIXME: TempParam is leaked.
2151 }
2152
2153 switch (Arg.getArgument().getKind()) {
2154 case TemplateArgument::Null:
2155 assert(false && "Should never see a NULL template argument here");
2156 return true;
2157
2158 case TemplateArgument::Template:
2159 if (CheckTemplateArgument(TempParm, Arg))
2160 return true;
2161
2162 Converted.Append(Arg.getArgument());
2163 break;
2164
2165 case TemplateArgument::Expression:
2166 case TemplateArgument::Type:
2167 // We have a template template parameter but the template
2168 // argument does not refer to a template.
2169 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2170 return true;
2171
2172 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002173 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002174 "Declaration argument with template template parameter");
2175 break;
2176 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002177 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002178 "Integral argument with template template parameter");
2179 break;
2180
2181 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002182 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002183 break;
2184 }
2185
2186 return false;
2187}
2188
Douglas Gregorc15cb382009-02-09 23:23:08 +00002189/// \brief Check that the given template argument list is well-formed
2190/// for specializing the given template.
2191bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2192 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002193 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002194 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002195 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002196 TemplateParameterList *Params = Template->getTemplateParameters();
2197 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002198 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002199 bool Invalid = false;
2200
John McCalld5532b62009-11-23 01:53:49 +00002201 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2202
Mike Stump1eb44332009-09-09 15:08:12 +00002203 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002204 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002206 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002207 (NumArgs < Params->getMinRequiredArguments() &&
2208 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002209 // FIXME: point at either the first arg beyond what we can handle,
2210 // or the '>', depending on whether we have too many or too few
2211 // arguments.
2212 SourceRange Range;
2213 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002214 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002215 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2216 << (NumArgs > NumParams)
2217 << (isa<ClassTemplateDecl>(Template)? 0 :
2218 isa<FunctionTemplateDecl>(Template)? 1 :
2219 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2220 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002221 Diag(Template->getLocation(), diag::note_template_decl_here)
2222 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002223 Invalid = true;
2224 }
Mike Stump1eb44332009-09-09 15:08:12 +00002225
2226 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002227 // [...] The type and form of each template-argument specified in
2228 // a template-id shall match the type and form specified for the
2229 // corresponding parameter declared by the template in its
2230 // template-parameter-list.
2231 unsigned ArgIdx = 0;
2232 for (TemplateParameterList::iterator Param = Params->begin(),
2233 ParamEnd = Params->end();
2234 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002235 if (ArgIdx > NumArgs && PartialTemplateArgs)
2236 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Douglas Gregord9e15302009-11-11 19:41:09 +00002238 // If we have a template parameter pack, check every remaining template
2239 // argument against that template parameter pack.
2240 if ((*Param)->isTemplateParameterPack()) {
2241 Converted.BeginPack();
2242 for (; ArgIdx < NumArgs; ++ArgIdx) {
2243 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2244 TemplateLoc, RAngleLoc, Converted)) {
2245 Invalid = true;
2246 break;
2247 }
2248 }
2249 Converted.EndPack();
2250 continue;
2251 }
2252
Douglas Gregorf35f8282009-11-11 21:54:23 +00002253 if (ArgIdx < NumArgs) {
2254 // Check the template argument we were given.
2255 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2256 TemplateLoc, RAngleLoc, Converted))
2257 return true;
2258
2259 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002260 }
Douglas Gregore7526412009-11-11 19:31:23 +00002261
Douglas Gregorf35f8282009-11-11 21:54:23 +00002262 // We have a default template argument that we will use.
2263 TemplateArgumentLoc Arg;
2264
2265 // Retrieve the default template argument from the template
2266 // parameter. For each kind of template parameter, we substitute the
2267 // template arguments provided thus far and any "outer" template arguments
2268 // (when the template parameter was part of a nested template) into
2269 // the default argument.
2270 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2271 if (!TTP->hasDefaultArgument()) {
2272 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2273 break;
2274 }
2275
John McCalla93c9342009-12-07 02:54:59 +00002276 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002277 Template,
2278 TemplateLoc,
2279 RAngleLoc,
2280 TTP,
2281 Converted);
2282 if (!ArgType)
2283 return true;
2284
2285 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2286 ArgType);
2287 } else if (NonTypeTemplateParmDecl *NTTP
2288 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2289 if (!NTTP->hasDefaultArgument()) {
2290 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2291 break;
2292 }
2293
2294 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2295 TemplateLoc,
2296 RAngleLoc,
2297 NTTP,
2298 Converted);
2299 if (E.isInvalid())
2300 return true;
2301
2302 Expr *Ex = E.takeAs<Expr>();
2303 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2304 } else {
2305 TemplateTemplateParmDecl *TempParm
2306 = cast<TemplateTemplateParmDecl>(*Param);
2307
2308 if (!TempParm->hasDefaultArgument()) {
2309 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2310 break;
2311 }
2312
2313 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2314 TemplateLoc,
2315 RAngleLoc,
2316 TempParm,
2317 Converted);
2318 if (Name.isNull())
2319 return true;
2320
2321 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2322 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2323 TempParm->getDefaultArgument().getTemplateNameLoc());
2324 }
2325
2326 // Introduce an instantiation record that describes where we are using
2327 // the default template argument.
2328 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2329 Converted.getFlatArguments(),
2330 Converted.flatSize(),
2331 SourceRange(TemplateLoc, RAngleLoc));
2332
2333 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002334 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002335 RAngleLoc, Converted))
2336 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002337 }
2338
2339 return Invalid;
2340}
2341
2342/// \brief Check a template argument against its corresponding
2343/// template type parameter.
2344///
2345/// This routine implements the semantics of C++ [temp.arg.type]. It
2346/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002347bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002348 TypeSourceInfo *ArgInfo) {
2349 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002350 QualType Arg = ArgInfo->getType();
2351
Douglas Gregorc15cb382009-02-09 23:23:08 +00002352 // C++ [temp.arg.type]p2:
2353 // A local type, a type with no linkage, an unnamed type or a type
2354 // compounded from any of these types shall not be used as a
2355 // template-argument for a template type-parameter.
2356 //
2357 // FIXME: Perform the recursive and no-linkage type checks.
2358 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002359 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002360 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002361 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002362 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002363 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002364 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall833ca992009-10-29 08:12:44 +00002365 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2366 << QualType(Tag, 0) << SR;
2367 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002368 !Tag->getDecl()->getTypedefForAnonDecl()) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002369 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall833ca992009-10-29 08:12:44 +00002370 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002371 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2372 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002373 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002374 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregor4b52e252009-12-21 23:17:24 +00002375 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002376 }
2377
2378 return false;
2379}
2380
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002381/// \brief Checks whether the given template argument is the address
2382/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002383static bool
2384CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2385 NonTypeTemplateParmDecl *Param,
2386 QualType ParamType,
2387 Expr *ArgIn,
2388 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002389 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002390 Expr *Arg = ArgIn;
2391 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002392
2393 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002394 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002395 Arg = Cast->getSubExpr();
2396
2397 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002398 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002399 // A template-argument for a non-type, non-template
2400 // template-parameter shall be one of: [...]
2401 //
2402 // -- the address of an object or function with external
2403 // linkage, including function templates and function
2404 // template-ids but excluding non-static class members,
2405 // expressed as & id-expression where the & is optional if
2406 // the name refers to a function or array, or if the
2407 // corresponding template-parameter is a reference; or
2408 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002409
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002410 // Ignore (and complain about) any excess parentheses.
2411 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2412 if (!Invalid) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002413 S.Diag(Arg->getSourceRange().getBegin(),
2414 diag::err_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002415 << Arg->getSourceRange();
2416 Invalid = true;
2417 }
2418
2419 Arg = Parens->getSubExpr();
2420 }
2421
Douglas Gregorb7a09262010-04-01 18:32:35 +00002422 bool AddressTaken = false;
2423 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002424 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002425 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002426 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002427 AddressTaken = true;
2428 AddrOpLoc = UnOp->getOperatorLoc();
2429 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002430 } else
2431 DRE = dyn_cast<DeclRefExpr>(Arg);
2432
Douglas Gregorb7a09262010-04-01 18:32:35 +00002433 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002434 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2435 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002436 S.Diag(Param->getLocation(), diag::note_template_param_here);
2437 return true;
2438 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002439
2440 // Stop checking the precise nature of the argument if it is value dependent,
2441 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002442 if (Arg->isValueDependent()) {
2443 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002444 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002445 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002446
Douglas Gregorb7a09262010-04-01 18:32:35 +00002447 if (!isa<ValueDecl>(DRE->getDecl())) {
2448 S.Diag(Arg->getSourceRange().getBegin(),
2449 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002450 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002451 S.Diag(Param->getLocation(), diag::note_template_param_here);
2452 return true;
2453 }
2454
2455 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002456
2457 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002458 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2459 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002460 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002461 S.Diag(Param->getLocation(), diag::note_template_param_here);
2462 return true;
2463 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002464
2465 // Cannot refer to non-static member functions
2466 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002467 if (!Method->isStatic()) {
2468 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002469 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002470 S.Diag(Param->getLocation(), diag::note_template_param_here);
2471 return true;
2472 }
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002474 // Functions must have external linkage.
2475 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002476 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002477 S.Diag(Arg->getSourceRange().getBegin(),
2478 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002479 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002480 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002481 << true;
2482 return true;
2483 }
2484
2485 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002486 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002487
Douglas Gregorb7a09262010-04-01 18:32:35 +00002488 // If the template parameter has pointer type, the function decays.
2489 if (ParamType->isPointerType() && !AddressTaken)
2490 ArgType = S.Context.getPointerType(Func->getType());
2491 else if (AddressTaken && ParamType->isReferenceType()) {
2492 // If we originally had an address-of operator, but the
2493 // parameter has reference type, complain and (if things look
2494 // like they will work) drop the address-of operator.
2495 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2496 ParamType.getNonReferenceType())) {
2497 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2498 << ParamType;
2499 S.Diag(Param->getLocation(), diag::note_template_param_here);
2500 return true;
2501 }
2502
2503 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2504 << ParamType
2505 << FixItHint::CreateRemoval(AddrOpLoc);
2506 S.Diag(Param->getLocation(), diag::note_template_param_here);
2507
2508 ArgType = Func->getType();
2509 }
2510 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002511 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002512 S.Diag(Arg->getSourceRange().getBegin(),
2513 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002514 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002515 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002516 << true;
2517 return true;
2518 }
2519
Douglas Gregorb7a09262010-04-01 18:32:35 +00002520 // A value of reference type is not an object.
2521 if (Var->getType()->isReferenceType()) {
2522 S.Diag(Arg->getSourceRange().getBegin(),
2523 diag::err_template_arg_reference_var)
2524 << Var->getType() << Arg->getSourceRange();
2525 S.Diag(Param->getLocation(), diag::note_template_param_here);
2526 return true;
2527 }
2528
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002529 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002530 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002531
2532 // If the template parameter has pointer type, we must have taken
2533 // the address of this object.
2534 if (ParamType->isReferenceType()) {
2535 if (AddressTaken) {
2536 // If we originally had an address-of operator, but the
2537 // parameter has reference type, complain and (if things look
2538 // like they will work) drop the address-of operator.
2539 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2540 ParamType.getNonReferenceType())) {
2541 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2542 << ParamType;
2543 S.Diag(Param->getLocation(), diag::note_template_param_here);
2544 return true;
2545 }
2546
2547 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2548 << ParamType
2549 << FixItHint::CreateRemoval(AddrOpLoc);
2550 S.Diag(Param->getLocation(), diag::note_template_param_here);
2551
2552 ArgType = Var->getType();
2553 }
2554 } else if (!AddressTaken && ParamType->isPointerType()) {
2555 if (Var->getType()->isArrayType()) {
2556 // Array-to-pointer decay.
2557 ArgType = S.Context.getArrayDecayedType(Var->getType());
2558 } else {
2559 // If the template parameter has pointer type but the address of
2560 // this object was not taken, complain and (possibly) recover by
2561 // taking the address of the entity.
2562 ArgType = S.Context.getPointerType(Var->getType());
2563 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2564 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2565 << ParamType;
2566 S.Diag(Param->getLocation(), diag::note_template_param_here);
2567 return true;
2568 }
2569
2570 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2571 << ParamType
2572 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2573
2574 S.Diag(Param->getLocation(), diag::note_template_param_here);
2575 }
2576 }
2577 } else {
2578 // We found something else, but we don't know specifically what it is.
2579 S.Diag(Arg->getSourceRange().getBegin(),
2580 diag::err_template_arg_not_object_or_func)
2581 << Arg->getSourceRange();
2582 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2583 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002584 }
Mike Stump1eb44332009-09-09 15:08:12 +00002585
Douglas Gregorb7a09262010-04-01 18:32:35 +00002586 if (ParamType->isPointerType() &&
2587 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2588 S.IsQualificationConversion(ArgType, ParamType)) {
2589 // For pointer-to-object types, qualification conversions are
2590 // permitted.
2591 } else {
2592 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2593 if (!ParamRef->getPointeeType()->isFunctionType()) {
2594 // C++ [temp.arg.nontype]p5b3:
2595 // For a non-type template-parameter of type reference to
2596 // object, no conversions apply. The type referred to by the
2597 // reference may be more cv-qualified than the (otherwise
2598 // identical) type of the template- argument. The
2599 // template-parameter is bound directly to the
2600 // template-argument, which shall be an lvalue.
2601
2602 // FIXME: Other qualifiers?
2603 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2604 unsigned ArgQuals = ArgType.getCVRQualifiers();
2605
2606 if ((ParamQuals | ArgQuals) != ParamQuals) {
2607 S.Diag(Arg->getSourceRange().getBegin(),
2608 diag::err_template_arg_ref_bind_ignores_quals)
2609 << ParamType << Arg->getType()
2610 << Arg->getSourceRange();
2611 S.Diag(Param->getLocation(), diag::note_template_param_here);
2612 return true;
2613 }
2614 }
2615 }
2616
2617 // At this point, the template argument refers to an object or
2618 // function with external linkage. We now need to check whether the
2619 // argument and parameter types are compatible.
2620 if (!S.Context.hasSameUnqualifiedType(ArgType,
2621 ParamType.getNonReferenceType())) {
2622 // We can't perform this conversion or binding.
2623 if (ParamType->isReferenceType())
2624 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2625 << ParamType << Arg->getType() << Arg->getSourceRange();
2626 else
2627 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2628 << Arg->getType() << ParamType << Arg->getSourceRange();
2629 S.Diag(Param->getLocation(), diag::note_template_param_here);
2630 return true;
2631 }
2632 }
2633
2634 // Create the template argument.
2635 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002636 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002637 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002638}
2639
2640/// \brief Checks whether the given template argument is a pointer to
2641/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002642bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2643 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002644 bool Invalid = false;
2645
2646 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002647 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002648 Arg = Cast->getSubExpr();
2649
2650 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002651 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002652 // A template-argument for a non-type, non-template
2653 // template-parameter shall be one of: [...]
2654 //
2655 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002656 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002657
2658 // Ignore (and complain about) any excess parentheses.
2659 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2660 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002661 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002662 diag::err_template_arg_extra_parens)
2663 << Arg->getSourceRange();
2664 Invalid = true;
2665 }
2666
2667 Arg = Parens->getSubExpr();
2668 }
2669
Douglas Gregorcaddba02009-11-12 18:38:13 +00002670 // A pointer-to-member constant written &Class::member.
2671 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002672 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2673 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2674 if (DRE && !DRE->getQualifier())
2675 DRE = 0;
2676 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002677 }
2678 // A constant of pointer-to-member type.
2679 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2680 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2681 if (VD->getType()->isMemberPointerType()) {
2682 if (isa<NonTypeTemplateParmDecl>(VD) ||
2683 (isa<VarDecl>(VD) &&
2684 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2685 if (Arg->isTypeDependent() || Arg->isValueDependent())
2686 Converted = TemplateArgument(Arg->Retain());
2687 else
2688 Converted = TemplateArgument(VD->getCanonicalDecl());
2689 return Invalid;
2690 }
2691 }
2692 }
2693
2694 DRE = 0;
2695 }
2696
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002697 if (!DRE)
2698 return Diag(Arg->getSourceRange().getBegin(),
2699 diag::err_template_arg_not_pointer_to_member_form)
2700 << Arg->getSourceRange();
2701
2702 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2703 assert((isa<FieldDecl>(DRE->getDecl()) ||
2704 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2705 "Only non-static member pointers can make it here");
2706
2707 // Okay: this is the address of a non-static member, and therefore
2708 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002709 if (Arg->isTypeDependent() || Arg->isValueDependent())
2710 Converted = TemplateArgument(Arg->Retain());
2711 else
2712 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002713 return Invalid;
2714 }
2715
2716 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002717 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002718 diag::err_template_arg_not_pointer_to_member_form)
2719 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002720 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002721 diag::note_template_arg_refers_here);
2722 return true;
2723}
2724
Douglas Gregorc15cb382009-02-09 23:23:08 +00002725/// \brief Check a template argument against its corresponding
2726/// non-type template parameter.
2727///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002728/// This routine implements the semantics of C++ [temp.arg.nontype].
2729/// It returns true if an error occurred, and false otherwise. \p
2730/// InstantiatedParamType is the type of the non-type template
2731/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002732///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002733/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002734bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002735 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002736 TemplateArgument &Converted,
2737 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002738 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2739
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002740 // If either the parameter has a dependent type or the argument is
2741 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002742 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2743 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002744 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002745 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002746 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002747
2748 // C++ [temp.arg.nontype]p5:
2749 // The following conversions are performed on each expression used
2750 // as a non-type template-argument. If a non-type
2751 // template-argument cannot be converted to the type of the
2752 // corresponding template-parameter then the program is
2753 // ill-formed.
2754 //
2755 // -- for a non-type template-parameter of integral or
2756 // enumeration type, integral promotions (4.5) and integral
2757 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002758 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002759 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002760 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002761 // C++ [temp.arg.nontype]p1:
2762 // A template-argument for a non-type, non-template
2763 // template-parameter shall be one of:
2764 //
2765 // -- an integral constant-expression of integral or enumeration
2766 // type; or
2767 // -- the name of a non-type template-parameter; or
2768 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002769 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002770 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002771 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002772 diag::err_template_arg_not_integral_or_enumeral)
2773 << ArgType << Arg->getSourceRange();
2774 Diag(Param->getLocation(), diag::note_template_param_here);
2775 return true;
2776 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002777 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002778 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2779 << ArgType << Arg->getSourceRange();
2780 return true;
2781 }
2782
Douglas Gregor02024a92010-03-28 02:42:43 +00002783 // From here on out, all we care about are the unqualified forms
2784 // of the parameter and argument types.
2785 ParamType = ParamType.getUnqualifiedType();
2786 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002787
2788 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002789 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002790 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002791 } else if (CTAK == CTAK_Deduced) {
2792 // C++ [temp.deduct.type]p17:
2793 // If, in the declaration of a function template with a non-type
2794 // template-parameter, the non-type template- parameter is used
2795 // in an expression in the function parameter-list and, if the
2796 // corresponding template-argument is deduced, the
2797 // template-argument type shall match the type of the
2798 // template-parameter exactly, except that a template-argument
2799 // deduced from an array bound may be of any integral type.
2800 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2801 << ArgType << ParamType;
2802 Diag(Param->getLocation(), diag::note_template_param_here);
2803 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002804 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2805 !ParamType->isEnumeralType()) {
2806 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002807 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002808 } else {
2809 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002810 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002811 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002812 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002813 Diag(Param->getLocation(), diag::note_template_param_here);
2814 return true;
2815 }
2816
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002817 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002818 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002819 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002820
2821 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002822 llvm::APSInt OldValue = Value;
2823
2824 // Coerce the template argument's value to the value it will have
2825 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002826 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002827 if (Value.getBitWidth() != AllowedBits)
2828 Value.extOrTrunc(AllowedBits);
2829 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002830
2831 // Complain if an unsigned parameter received a negative value.
2832 if (IntegerType->isUnsignedIntegerType()
2833 && (OldValue.isSigned() && OldValue.isNegative())) {
2834 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2835 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2836 << Arg->getSourceRange();
2837 Diag(Param->getLocation(), diag::note_template_param_here);
2838 }
2839
2840 // Complain if we overflowed the template parameter's type.
2841 unsigned RequiredBits;
2842 if (IntegerType->isUnsignedIntegerType())
2843 RequiredBits = OldValue.getActiveBits();
2844 else if (OldValue.isUnsigned())
2845 RequiredBits = OldValue.getActiveBits() + 1;
2846 else
2847 RequiredBits = OldValue.getMinSignedBits();
2848 if (RequiredBits > AllowedBits) {
2849 Diag(Arg->getSourceRange().getBegin(),
2850 diag::warn_template_arg_too_large)
2851 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2852 << Arg->getSourceRange();
2853 Diag(Param->getLocation(), diag::note_template_param_here);
2854 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002855 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002856
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002857 // Add the value of this argument to the list of converted
2858 // arguments. We use the bitwidth and signedness of the template
2859 // parameter.
2860 if (Arg->isValueDependent()) {
2861 // The argument is value-dependent. Create a new
2862 // TemplateArgument with the converted expression.
2863 Converted = TemplateArgument(Arg);
2864 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002865 }
2866
John McCall833ca992009-10-29 08:12:44 +00002867 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002868 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002869 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002870 return false;
2871 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002872
John McCall6bb80172010-03-30 21:47:33 +00002873 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2874
Douglas Gregorb7a09262010-04-01 18:32:35 +00002875 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2876 // from a template argument of type std::nullptr_t to a non-type
2877 // template parameter of type pointer to object, pointer to
2878 // function, or pointer-to-member, respectively.
2879 if (ArgType->isNullPtrType() &&
2880 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2881 Converted = TemplateArgument((NamedDecl *)0);
2882 return false;
2883 }
2884
Douglas Gregorb86b0572009-02-11 01:18:59 +00002885 // Handle pointer-to-function, reference-to-function, and
2886 // pointer-to-member-function all in (roughly) the same way.
2887 if (// -- For a non-type template-parameter of type pointer to
2888 // function, only the function-to-pointer conversion (4.3) is
2889 // applied. If the template-argument represents a set of
2890 // overloaded functions (or a pointer to such), the matching
2891 // function is selected from the set (13.4).
2892 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002893 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002894 // -- For a non-type template-parameter of type reference to
2895 // function, no conversions apply. If the template-argument
2896 // represents a set of overloaded functions, the matching
2897 // function is selected from the set (13.4).
2898 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002899 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002900 // -- For a non-type template-parameter of type pointer to
2901 // member function, no conversions apply. If the
2902 // template-argument represents a set of overloaded member
2903 // functions, the matching member function is selected from
2904 // the set (13.4).
2905 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002906 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002907 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002908
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002909 if (Arg->getType() == Context.OverloadTy) {
2910 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2911 true,
2912 FoundResult)) {
2913 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2914 return true;
2915
2916 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2917 ArgType = Arg->getType();
2918 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002919 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00002920 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002921
Douglas Gregorb7a09262010-04-01 18:32:35 +00002922 if (!ParamType->isMemberPointerType())
2923 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2924 ParamType,
2925 Arg, Converted);
2926
2927 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2928 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2929 Arg->isLvalue(Context) == Expr::LV_Valid);
2930 } else if (!Context.hasSameUnqualifiedType(ArgType,
2931 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002932 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002933 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002934 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002935 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002936 Diag(Param->getLocation(), diag::note_template_param_here);
2937 return true;
2938 }
Mike Stump1eb44332009-09-09 15:08:12 +00002939
Douglas Gregorb7a09262010-04-01 18:32:35 +00002940 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00002941 }
2942
Chris Lattnerfe90de72009-02-20 21:37:53 +00002943 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002944 // -- for a non-type template-parameter of type pointer to
2945 // object, qualification conversions (4.4) and the
2946 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002947 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002948 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002949 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002950
Douglas Gregorb7a09262010-04-01 18:32:35 +00002951 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2952 ParamType,
2953 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002954 }
Mike Stump1eb44332009-09-09 15:08:12 +00002955
Ted Kremenek6217b802009-07-29 21:53:49 +00002956 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002957 // -- For a non-type template-parameter of type reference to
2958 // object, no conversions apply. The type referred to by the
2959 // reference may be more cv-qualified than the (otherwise
2960 // identical) type of the template-argument. The
2961 // template-parameter is bound directly to the
2962 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002963 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002964 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002965
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002966 if (Arg->getType() == Context.OverloadTy) {
2967 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2968 ParamRefType->getPointeeType(),
2969 true,
2970 FoundResult)) {
2971 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2972 return true;
2973
2974 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2975 ArgType = Arg->getType();
2976 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00002977 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002978 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002979
Douglas Gregorb7a09262010-04-01 18:32:35 +00002980 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2981 ParamType,
2982 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002983 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002984
2985 // -- For a non-type template-parameter of type pointer to data
2986 // member, qualification conversions (4.4) are applied.
2987 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2988
Douglas Gregor8e6563b2009-02-11 18:22:40 +00002989 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00002990 // Types match exactly: nothing more to do here.
2991 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002992 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2993 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor658bbb52009-02-11 16:16:59 +00002994 } else {
2995 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002996 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00002997 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002998 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00002999 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003000 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003001 }
3002
Douglas Gregorcaddba02009-11-12 18:38:13 +00003003 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003004}
3005
3006/// \brief Check a template argument against its corresponding
3007/// template template parameter.
3008///
3009/// This routine implements the semantics of C++ [temp.arg.template].
3010/// It returns true if an error occurred, and false otherwise.
3011bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003012 const TemplateArgumentLoc &Arg) {
3013 TemplateName Name = Arg.getArgument().getAsTemplate();
3014 TemplateDecl *Template = Name.getAsTemplateDecl();
3015 if (!Template) {
3016 // Any dependent template name is fine.
3017 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3018 return false;
3019 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003020
3021 // C++ [temp.arg.template]p1:
3022 // A template-argument for a template template-parameter shall be
3023 // the name of a class template, expressed as id-expression. Only
3024 // primary class templates are considered when matching the
3025 // template template argument with the corresponding parameter;
3026 // partial specializations are not considered even if their
3027 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003028 //
3029 // Note that we also allow template template parameters here, which
3030 // will happen when we are dealing with, e.g., class template
3031 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003032 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003033 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003034 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003035 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003036 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003037 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003038 << Template;
3039 }
3040
3041 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3042 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003043 true,
3044 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003045 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003046}
3047
Douglas Gregor02024a92010-03-28 02:42:43 +00003048/// \brief Given a non-type template argument that refers to a
3049/// declaration and the type of its corresponding non-type template
3050/// parameter, produce an expression that properly refers to that
3051/// declaration.
3052Sema::OwningExprResult
3053Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3054 QualType ParamType,
3055 SourceLocation Loc) {
3056 assert(Arg.getKind() == TemplateArgument::Declaration &&
3057 "Only declaration template arguments permitted here");
3058 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3059
3060 if (VD->getDeclContext()->isRecord() &&
3061 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3062 // If the value is a class member, we might have a pointer-to-member.
3063 // Determine whether the non-type template template parameter is of
3064 // pointer-to-member type. If so, we need to build an appropriate
3065 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3066 // would refer to the member itself.
3067 if (ParamType->isMemberPointerType()) {
3068 QualType ClassType
3069 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3070 NestedNameSpecifier *Qualifier
3071 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3072 CXXScopeSpec SS;
3073 SS.setScopeRep(Qualifier);
3074 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3075 VD->getType().getNonReferenceType(),
3076 Loc,
3077 &SS);
3078 if (RefExpr.isInvalid())
3079 return ExprError();
3080
3081 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorc0c83002010-04-30 21:46:38 +00003082
3083 // We might need to perform a trailing qualification conversion, since
3084 // the element type on the parameter could be more qualified than the
3085 // element type in the expression we constructed.
3086 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3087 ParamType.getUnqualifiedType())) {
3088 Expr *RefE = RefExpr.takeAs<Expr>();
3089 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3090 CastExpr::CK_NoOp);
3091 RefExpr = Owned(RefE);
3092 }
3093
Douglas Gregor02024a92010-03-28 02:42:43 +00003094 assert(!RefExpr.isInvalid() &&
3095 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003096 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003097 return move(RefExpr);
3098 }
3099 }
3100
3101 QualType T = VD->getType().getNonReferenceType();
3102 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003103 // When the non-type template parameter is a pointer, take the
3104 // address of the declaration.
Douglas Gregor02024a92010-03-28 02:42:43 +00003105 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3106 if (RefExpr.isInvalid())
3107 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003108
3109 if (T->isFunctionType() || T->isArrayType()) {
3110 // Decay functions and arrays.
3111 Expr *RefE = (Expr *)RefExpr.get();
3112 DefaultFunctionArrayConversion(RefE);
3113 if (RefE != RefExpr.get()) {
3114 RefExpr.release();
3115 RefExpr = Owned(RefE);
3116 }
3117
3118 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003119 }
3120
Douglas Gregorb7a09262010-04-01 18:32:35 +00003121 // Take the address of everything else
3122 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregor02024a92010-03-28 02:42:43 +00003123 }
3124
3125 // If the non-type template parameter has reference type, qualify the
3126 // resulting declaration reference with the extra qualifiers on the
3127 // type that the reference refers to.
3128 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3129 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3130
3131 return BuildDeclRefExpr(VD, T, Loc);
3132}
3133
3134/// \brief Construct a new expression that refers to the given
3135/// integral template argument with the given source-location
3136/// information.
3137///
3138/// This routine takes care of the mapping from an integral template
3139/// argument (which may have any integral type) to the appropriate
3140/// literal value.
3141Sema::OwningExprResult
3142Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3143 SourceLocation Loc) {
3144 assert(Arg.getKind() == TemplateArgument::Integral &&
3145 "Operation is only value for integral template arguments");
3146 QualType T = Arg.getIntegralType();
3147 if (T->isCharType() || T->isWideCharType())
3148 return Owned(new (Context) CharacterLiteral(
3149 Arg.getAsIntegral()->getZExtValue(),
3150 T->isWideCharType(),
3151 T,
3152 Loc));
3153 if (T->isBooleanType())
3154 return Owned(new (Context) CXXBoolLiteralExpr(
3155 Arg.getAsIntegral()->getBoolValue(),
3156 T,
3157 Loc));
3158
3159 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3160}
3161
3162
Douglas Gregorddc29e12009-02-06 22:42:48 +00003163/// \brief Determine whether the given template parameter lists are
3164/// equivalent.
3165///
Mike Stump1eb44332009-09-09 15:08:12 +00003166/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003167/// source code as part of a new template declaration.
3168///
3169/// \param Old The old template parameter list, typically found via
3170/// name lookup of the template declared with this template parameter
3171/// list.
3172///
3173/// \param Complain If true, this routine will produce a diagnostic if
3174/// the template parameter lists are not equivalent.
3175///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003176/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003177///
3178/// \param TemplateArgLoc If this source location is valid, then we
3179/// are actually checking the template parameter list of a template
3180/// argument (New) against the template parameter list of its
3181/// corresponding template template parameter (Old). We produce
3182/// slightly different diagnostics in this scenario.
3183///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003184/// \returns True if the template parameter lists are equal, false
3185/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003186bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003187Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3188 TemplateParameterList *Old,
3189 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003190 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003191 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003192 if (Old->size() != New->size()) {
3193 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003194 unsigned NextDiag = diag::err_template_param_list_different_arity;
3195 if (TemplateArgLoc.isValid()) {
3196 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3197 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003198 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003199 Diag(New->getTemplateLoc(), NextDiag)
3200 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003201 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003202 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003203 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003204 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003205 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3206 }
3207
3208 return false;
3209 }
3210
3211 for (TemplateParameterList::iterator OldParm = Old->begin(),
3212 OldParmEnd = Old->end(), NewParm = New->begin();
3213 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3214 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003215 if (Complain) {
3216 unsigned NextDiag = diag::err_template_param_different_kind;
3217 if (TemplateArgLoc.isValid()) {
3218 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3219 NextDiag = diag::note_template_param_different_kind;
3220 }
3221 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003222 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003223 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003224 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003225 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003226 return false;
3227 }
3228
3229 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3230 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +00003231 // know we're at the same index).
Mike Stump1eb44332009-09-09 15:08:12 +00003232 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003233 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3234 // The types of non-type template parameters must agree.
3235 NonTypeTemplateParmDecl *NewNTTP
3236 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003237
3238 // If we are matching a template template argument to a template
3239 // template parameter and one of the non-type template parameter types
3240 // is dependent, then we must wait until template instantiation time
3241 // to actually compare the arguments.
3242 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3243 (OldNTTP->getType()->isDependentType() ||
3244 NewNTTP->getType()->isDependentType()))
3245 continue;
3246
Douglas Gregorddc29e12009-02-06 22:42:48 +00003247 if (Context.getCanonicalType(OldNTTP->getType()) !=
3248 Context.getCanonicalType(NewNTTP->getType())) {
3249 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003250 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3251 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003252 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003253 diag::err_template_arg_template_params_mismatch);
3254 NextDiag = diag::note_template_nontype_parm_different_type;
3255 }
3256 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003257 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003258 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003259 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003260 diag::note_template_nontype_parm_prev_declaration)
3261 << OldNTTP->getType();
3262 }
3263 return false;
3264 }
3265 } else {
3266 // The template parameter lists of template template
3267 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003268 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003269 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003270 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003271 = cast<TemplateTemplateParmDecl>(*OldParm);
3272 TemplateTemplateParmDecl *NewTTP
3273 = cast<TemplateTemplateParmDecl>(*NewParm);
3274 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3275 OldTTP->getTemplateParameters(),
3276 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003277 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003278 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003279 return false;
3280 }
3281 }
3282
3283 return true;
3284}
3285
3286/// \brief Check whether a template can be declared within this scope.
3287///
3288/// If the template declaration is valid in this scope, returns
3289/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003290bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003291Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003292 // Find the nearest enclosing declaration scope.
3293 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3294 (S->getFlags() & Scope::TemplateParamScope) != 0)
3295 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Douglas Gregorddc29e12009-02-06 22:42:48 +00003297 // C++ [temp]p2:
3298 // A template-declaration can appear only as a namespace scope or
3299 // class scope declaration.
3300 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003301 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3302 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003303 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003304 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Eli Friedman1503f772009-07-31 01:43:05 +00003306 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003307 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003308
3309 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3310 return false;
3311
Mike Stump1eb44332009-09-09 15:08:12 +00003312 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003313 diag::err_template_outside_namespace_or_class_scope)
3314 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003315}
Douglas Gregorcc636682009-02-17 23:15:12 +00003316
Douglas Gregord5cb8762009-10-07 00:13:32 +00003317/// \brief Determine what kind of template specialization the given declaration
3318/// is.
3319static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3320 if (!D)
3321 return TSK_Undeclared;
3322
Douglas Gregorf6b11852009-10-08 15:14:33 +00003323 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3324 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003325 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3326 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003327 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3328 return Var->getTemplateSpecializationKind();
3329
Douglas Gregord5cb8762009-10-07 00:13:32 +00003330 return TSK_Undeclared;
3331}
3332
Douglas Gregor9302da62009-10-14 23:50:59 +00003333/// \brief Check whether a specialization is well-formed in the current
3334/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003335///
Douglas Gregor9302da62009-10-14 23:50:59 +00003336/// This routine determines whether a template specialization can be declared
3337/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003338///
3339/// \param S the semantic analysis object for which this check is being
3340/// performed.
3341///
3342/// \param Specialized the entity being specialized or instantiated, which
3343/// may be a kind of template (class template, function template, etc.) or
3344/// a member of a class template (member function, static data member,
3345/// member class).
3346///
3347/// \param PrevDecl the previous declaration of this entity, if any.
3348///
3349/// \param Loc the location of the explicit specialization or instantiation of
3350/// this entity.
3351///
3352/// \param IsPartialSpecialization whether this is a partial specialization of
3353/// a class template.
3354///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003355/// \returns true if there was an error that we cannot recover from, false
3356/// otherwise.
3357static bool CheckTemplateSpecializationScope(Sema &S,
3358 NamedDecl *Specialized,
3359 NamedDecl *PrevDecl,
3360 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003361 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003362 // Keep these "kind" numbers in sync with the %select statements in the
3363 // various diagnostics emitted by this routine.
3364 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003365 bool isTemplateSpecialization = false;
3366 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003367 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003368 isTemplateSpecialization = true;
3369 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003370 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003371 isTemplateSpecialization = true;
3372 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003373 EntityKind = 3;
3374 else if (isa<VarDecl>(Specialized))
3375 EntityKind = 4;
3376 else if (isa<RecordDecl>(Specialized))
3377 EntityKind = 5;
3378 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003379 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3380 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003381 return true;
3382 }
3383
Douglas Gregor88b70942009-02-25 22:02:03 +00003384 // C++ [temp.expl.spec]p2:
3385 // An explicit specialization shall be declared in the namespace
3386 // of which the template is a member, or, for member templates, in
3387 // the namespace of which the enclosing class or enclosing class
3388 // template is a member. An explicit specialization of a member
3389 // function, member class or static data member of a class
3390 // template shall be declared in the namespace of which the class
3391 // template is a member. Such a declaration may also be a
3392 // definition. If the declaration is not a definition, the
3393 // specialization may be defined later in the name- space in which
3394 // the explicit specialization was declared, or in a namespace
3395 // that encloses the one in which the explicit specialization was
3396 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003397 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3398 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003399 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003400 return true;
3401 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003402
Douglas Gregor0a407472009-10-07 17:30:37 +00003403 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3404 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003405 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003406 return true;
3407 }
3408
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003409 // C++ [temp.class.spec]p6:
3410 // A class template partial specialization may be declared or redeclared
3411 // in any namespace scope in which its definition may be defined (14.5.1
3412 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003413 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003414 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003415 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003416 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003417 if ((!PrevDecl ||
3418 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3419 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3420 // There is no prior declaration of this entity, so this
3421 // specialization must be in the same context as the template
3422 // itself.
3423 if (!DC->Equals(SpecializedContext)) {
3424 if (isa<TranslationUnitDecl>(SpecializedContext))
3425 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3426 << EntityKind << Specialized;
3427 else if (isa<NamespaceDecl>(SpecializedContext))
3428 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3429 << EntityKind << Specialized
3430 << cast<NamedDecl>(SpecializedContext);
3431
3432 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3433 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003434 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003435 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003436
3437 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003438 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003439 // Note that HandleDeclarator() performs this check for explicit
3440 // specializations of function templates, static data members, and member
3441 // functions, so we skip the check here for those kinds of entities.
3442 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003443 // Should we refactor that check, so that it occurs later?
3444 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003445 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3446 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003447 if (isa<TranslationUnitDecl>(SpecializedContext))
3448 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3449 << EntityKind << Specialized;
3450 else if (isa<NamespaceDecl>(SpecializedContext))
3451 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3452 << EntityKind << Specialized
3453 << cast<NamedDecl>(SpecializedContext);
3454
Douglas Gregor9302da62009-10-14 23:50:59 +00003455 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003456 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003457
3458 // FIXME: check for specialization-after-instantiation errors and such.
3459
Douglas Gregor88b70942009-02-25 22:02:03 +00003460 return false;
3461}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003462
Douglas Gregore94866f2009-06-12 21:21:02 +00003463/// \brief Check the non-type template arguments of a class template
3464/// partial specialization according to C++ [temp.class.spec]p9.
3465///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003466/// \param TemplateParams the template parameters of the primary class
3467/// template.
3468///
3469/// \param TemplateArg the template arguments of the class template
3470/// partial specialization.
3471///
3472/// \param MirrorsPrimaryTemplate will be set true if the class
3473/// template partial specialization arguments are identical to the
3474/// implicit template arguments of the primary template. This is not
3475/// necessarily an error (C++0x), and it is left to the caller to diagnose
3476/// this condition when it is an error.
3477///
Douglas Gregore94866f2009-06-12 21:21:02 +00003478/// \returns true if there was an error, false otherwise.
3479bool Sema::CheckClassTemplatePartialSpecializationArgs(
3480 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003481 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003482 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003483 // FIXME: the interface to this function will have to change to
3484 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003485 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003486
Anders Carlssonfb250522009-06-23 01:26:57 +00003487 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Douglas Gregore94866f2009-06-12 21:21:02 +00003489 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003490 // Determine whether the template argument list of the partial
3491 // specialization is identical to the implicit argument list of
3492 // the primary template. The caller may need to diagnostic this as
3493 // an error per C++ [temp.class.spec]p9b3.
3494 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003495 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003496 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3497 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003498 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003499 MirrorsPrimaryTemplate = false;
3500 } else if (TemplateTemplateParmDecl *TTP
3501 = dyn_cast<TemplateTemplateParmDecl>(
3502 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003503 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003504 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003505 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003506 if (!ArgDecl ||
3507 ArgDecl->getIndex() != TTP->getIndex() ||
3508 ArgDecl->getDepth() != TTP->getDepth())
3509 MirrorsPrimaryTemplate = false;
3510 }
3511 }
3512
Mike Stump1eb44332009-09-09 15:08:12 +00003513 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003514 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003515 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003516 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003517 }
3518
Anders Carlsson6360be72009-06-13 18:20:51 +00003519 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003520 if (!ArgExpr) {
3521 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003522 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003523 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003524
3525 // C++ [temp.class.spec]p8:
3526 // A non-type argument is non-specialized if it is the name of a
3527 // non-type parameter. All other non-type arguments are
3528 // specialized.
3529 //
3530 // Below, we check the two conditions that only apply to
3531 // specialized non-type arguments, so skip any non-specialized
3532 // arguments.
3533 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003534 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003535 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003536 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003537 (Param->getIndex() != NTTP->getIndex() ||
3538 Param->getDepth() != NTTP->getDepth()))
3539 MirrorsPrimaryTemplate = false;
3540
Douglas Gregore94866f2009-06-12 21:21:02 +00003541 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003542 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003543
3544 // C++ [temp.class.spec]p9:
3545 // Within the argument list of a class template partial
3546 // specialization, the following restrictions apply:
3547 // -- A partially specialized non-type argument expression
3548 // shall not involve a template parameter of the partial
3549 // specialization except when the argument expression is a
3550 // simple identifier.
3551 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003552 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003553 diag::err_dependent_non_type_arg_in_partial_spec)
3554 << ArgExpr->getSourceRange();
3555 return true;
3556 }
3557
3558 // -- The type of a template parameter corresponding to a
3559 // specialized non-type argument shall not be dependent on a
3560 // parameter of the specialization.
3561 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003562 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003563 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3564 << Param->getType()
3565 << ArgExpr->getSourceRange();
3566 Diag(Param->getLocation(), diag::note_template_param_here);
3567 return true;
3568 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003569
3570 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003571 }
3572
3573 return false;
3574}
3575
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003576/// \brief Retrieve the previous declaration of the given declaration.
3577static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3578 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3579 return VD->getPreviousDeclaration();
3580 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3581 return FD->getPreviousDeclaration();
3582 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3583 return TD->getPreviousDeclaration();
3584 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3585 return TD->getPreviousDeclaration();
3586 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3587 return FTD->getPreviousDeclaration();
3588 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3589 return CTD->getPreviousDeclaration();
3590 return 0;
3591}
3592
Douglas Gregor212e81c2009-03-25 00:13:59 +00003593Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003594Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3595 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003596 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003597 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003598 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003599 SourceLocation TemplateNameLoc,
3600 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003601 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003602 SourceLocation RAngleLoc,
3603 AttributeList *Attr,
3604 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003605 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003606
Douglas Gregorcc636682009-02-17 23:15:12 +00003607 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003608 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003609 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003610 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3611
3612 if (!ClassTemplate) {
3613 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3614 << (Name.getAsTemplateDecl() &&
3615 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3616 return true;
3617 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003618
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003619 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003620 bool isPartialSpecialization = false;
3621
Douglas Gregor88b70942009-02-25 22:02:03 +00003622 // Check the validity of the template headers that introduce this
3623 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003624 // FIXME: We probably shouldn't complain about these headers for
3625 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003626 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003627 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3628 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003629 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003630 TUK == TUK_Friend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003631 isExplicitSpecialization);
Douglas Gregor05396e22009-08-25 17:23:04 +00003632 if (TemplateParams && TemplateParams->size() > 0) {
3633 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003634
Douglas Gregor05396e22009-08-25 17:23:04 +00003635 // C++ [temp.class.spec]p10:
3636 // The template parameter list of a specialization shall not
3637 // contain default template argument values.
3638 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3639 Decl *Param = TemplateParams->getParam(I);
3640 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3641 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003642 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003643 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003644 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003645 }
3646 } else if (NonTypeTemplateParmDecl *NTTP
3647 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3648 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003649 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003650 diag::err_default_arg_in_partial_spec)
3651 << DefArg->getSourceRange();
3652 NTTP->setDefaultArgument(0);
3653 DefArg->Destroy(Context);
3654 }
3655 } else {
3656 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003657 if (TTP->hasDefaultArgument()) {
3658 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003659 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003660 << TTP->getDefaultArgument().getSourceRange();
3661 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003662 }
3663 }
3664 }
Douglas Gregora735b202009-10-13 14:39:41 +00003665 } else if (TemplateParams) {
3666 if (TUK == TUK_Friend)
3667 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00003668 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00003669 SourceRange(TemplateParams->getTemplateLoc(),
3670 TemplateParams->getRAngleLoc()))
3671 << SourceRange(LAngleLoc, RAngleLoc);
3672 else
3673 isExplicitSpecialization = true;
3674 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003675 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00003676 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003677 isExplicitSpecialization = true;
3678 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003679
Douglas Gregorcc636682009-02-17 23:15:12 +00003680 // Check that the specialization uses the same tag kind as the
3681 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003682 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3683 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003684 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003685 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003686 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003687 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003688 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00003689 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003690 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003691 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003692 diag::note_previous_use);
3693 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3694 }
3695
Douglas Gregor40808ce2009-03-09 23:48:35 +00003696 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003697 TemplateArgumentListInfo TemplateArgs;
3698 TemplateArgs.setLAngleLoc(LAngleLoc);
3699 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003700 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003701
Douglas Gregorcc636682009-02-17 23:15:12 +00003702 // Check that the template argument list is well-formed for this
3703 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003704 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3705 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003706 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3707 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003708 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003709
Mike Stump1eb44332009-09-09 15:08:12 +00003710 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003711 ClassTemplate->getTemplateParameters()->size()) &&
3712 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003714 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003715 // corresponds to these arguments.
3716 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003717 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003718 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003719 if (CheckClassTemplatePartialSpecializationArgs(
3720 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003721 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003722 return true;
3723
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003724 if (MirrorsPrimaryTemplate) {
3725 // C++ [temp.class.spec]p9b3:
3726 //
Mike Stump1eb44332009-09-09 15:08:12 +00003727 // -- The argument list of the specialization shall not be identical
3728 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003729 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003730 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00003731 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003732 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003733 ClassTemplate->getIdentifier(),
3734 TemplateNameLoc,
3735 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003736 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003737 AS_none);
3738 }
3739
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003740 // FIXME: Diagnose friend partial specializations
3741
Douglas Gregorde090962010-02-09 00:37:32 +00003742 if (!Name.isDependent() &&
3743 !TemplateSpecializationType::anyDependentTemplateArguments(
3744 TemplateArgs.getArgumentArray(),
3745 TemplateArgs.size())) {
3746 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3747 << ClassTemplate->getDeclName();
3748 isPartialSpecialization = false;
3749 } else {
3750 // FIXME: Template parameter list matters, too
3751 ClassTemplatePartialSpecializationDecl::Profile(ID,
3752 Converted.getFlatArguments(),
3753 Converted.flatSize(),
3754 Context);
3755 }
3756 }
3757
3758 if (!isPartialSpecialization)
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003759 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003760 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003761 Converted.flatSize(),
3762 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003763 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003764 ClassTemplateSpecializationDecl *PrevDecl = 0;
3765
3766 if (isPartialSpecialization)
3767 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003768 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003769 InsertPos);
3770 else
3771 PrevDecl
3772 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003773
3774 ClassTemplateSpecializationDecl *Specialization = 0;
3775
Douglas Gregor88b70942009-02-25 22:02:03 +00003776 // Check whether we can declare a class template specialization in
3777 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003778 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003779 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003780 TemplateNameLoc,
3781 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003782 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003783
Douglas Gregorb88e8882009-07-30 17:40:51 +00003784 // The canonical type
3785 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003786 if (PrevDecl &&
3787 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003788 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003789 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003790 // arguments was referenced but not declared, or we're only
3791 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003792 // declaration node as our own, updating its source location to
3793 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003794 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003795 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003796 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003797 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003798 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003799 // Build the canonical type that describes the converted template
3800 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003801 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3802 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003803 Converted.getFlatArguments(),
3804 Converted.flatSize());
3805
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003806 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003807 ClassTemplatePartialSpecializationDecl *PrevPartial
3808 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003809 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3810 : ClassTemplate->getPartialSpecializations().size();
Mike Stump1eb44332009-09-09 15:08:12 +00003811 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00003812 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003813 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003814 TemplateNameLoc,
3815 TemplateParams,
3816 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003817 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003818 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003819 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003820 PrevPartial,
3821 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00003822 SetNestedNameSpecifier(Partial, SS);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003823
3824 if (PrevPartial) {
3825 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3826 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3827 } else {
3828 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3829 }
3830 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003831
Douglas Gregored9c0f92009-10-29 00:04:11 +00003832 // If we are providing an explicit specialization of a member class
3833 // template specialization, make a note of that.
3834 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3835 PrevPartial->setMemberSpecialization();
3836
Douglas Gregor031a5882009-06-13 00:26:55 +00003837 // Check that all of the template parameters of the class template
3838 // partial specialization are deducible from the template
3839 // arguments. If not, this class template partial specialization
3840 // will never be used.
3841 llvm::SmallVector<bool, 8> DeducibleParams;
3842 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003843 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003844 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003845 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003846 unsigned NumNonDeducible = 0;
3847 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3848 if (!DeducibleParams[I])
3849 ++NumNonDeducible;
3850
3851 if (NumNonDeducible) {
3852 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3853 << (NumNonDeducible > 1)
3854 << SourceRange(TemplateNameLoc, RAngleLoc);
3855 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3856 if (!DeducibleParams[I]) {
3857 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3858 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003859 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003860 diag::note_partial_spec_unused_parameter)
3861 << Param->getDeclName();
3862 else
Mike Stump1eb44332009-09-09 15:08:12 +00003863 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003864 diag::note_partial_spec_unused_parameter)
3865 << std::string("<anonymous>");
3866 }
3867 }
3868 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003869 } else {
3870 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003871 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003872 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00003873 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00003874 ClassTemplate->getDeclContext(),
3875 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003876 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003877 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003878 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003879 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregorcc636682009-02-17 23:15:12 +00003880
3881 if (PrevDecl) {
3882 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3883 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3884 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003885 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003886 InsertPos);
3887 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003888
3889 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003890 }
3891
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003892 // C++ [temp.expl.spec]p6:
3893 // If a template, a member template or the member of a class template is
3894 // explicitly specialized then that specialization shall be declared
3895 // before the first use of that specialization that would cause an implicit
3896 // instantiation to take place, in every translation unit in which such a
3897 // use occurs; no diagnostic is required.
3898 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003899 bool Okay = false;
3900 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3901 // Is there any previous explicit specialization declaration?
3902 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3903 Okay = true;
3904 break;
3905 }
3906 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003907
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003908 if (!Okay) {
3909 SourceRange Range(TemplateNameLoc, RAngleLoc);
3910 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3911 << Context.getTypeDeclType(Specialization) << Range;
3912
3913 Diag(PrevDecl->getPointOfInstantiation(),
3914 diag::note_instantiation_required_here)
3915 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003916 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003917 return true;
3918 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003919 }
3920
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003921 // If this is not a friend, note that this is an explicit specialization.
3922 if (TUK != TUK_Friend)
3923 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003924
3925 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003926 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003927 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003928 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003929 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003930 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003931 Diag(Def->getLocation(), diag::note_previous_definition);
3932 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003933 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003934 }
3935 }
3936
Douglas Gregorfc705b82009-02-26 22:19:44 +00003937 // Build the fully-sugared type for this class template
3938 // specialization as the user wrote in the specialization
3939 // itself. This means that we'll pretty-print the type retrieved
3940 // from the specialization's declaration the way that the user
3941 // actually wrote the specialization, rather than formatting the
3942 // name based on the "canonical" representation used to store the
3943 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003944 TypeSourceInfo *WrittenTy
3945 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3946 TemplateArgs, CanonType);
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003947 if (TUK != TUK_Friend)
3948 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003949 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00003950
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003951 // C++ [temp.expl.spec]p9:
3952 // A template explicit specialization is in the scope of the
3953 // namespace in which the template was defined.
3954 //
3955 // We actually implement this paragraph where we set the semantic
3956 // context (in the creation of the ClassTemplateSpecializationDecl),
3957 // but we also maintain the lexical context where the actual
3958 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00003959 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Douglas Gregorcc636682009-02-17 23:15:12 +00003961 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003962 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00003963 Specialization->startDefinition();
3964
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003965 if (TUK == TUK_Friend) {
3966 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3967 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00003968 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003969 /*FIXME:*/KWLoc);
3970 Friend->setAccess(AS_public);
3971 CurContext->addDecl(Friend);
3972 } else {
3973 // Add the specialization into its lexical context, so that it can
3974 // be seen when iterating through the list of declarations in that
3975 // context. However, specializations are not found by name lookup.
3976 CurContext->addDecl(Specialization);
3977 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00003978 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003979}
Douglas Gregord57959a2009-03-27 23:10:48 +00003980
Mike Stump1eb44332009-09-09 15:08:12 +00003981Sema::DeclPtrTy
3982Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00003983 MultiTemplateParamsArg TemplateParameterLists,
3984 Declarator &D) {
3985 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3986}
3987
Mike Stump1eb44332009-09-09 15:08:12 +00003988Sema::DeclPtrTy
3989Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00003990 MultiTemplateParamsArg TemplateParameterLists,
3991 Declarator &D) {
3992 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3993 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3994 "Not a function declarator!");
3995 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Douglas Gregor52591bf2009-06-24 00:54:41 +00003997 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00003998 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00003999 }
Mike Stump1eb44332009-09-09 15:08:12 +00004000
Douglas Gregor52591bf2009-06-24 00:54:41 +00004001 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004002
4003 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004004 move(TemplateParameterLists),
4005 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004006 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004007 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00004008 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00004009 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004010 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4011 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00004012 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00004013}
4014
John McCall75042392010-02-11 01:33:53 +00004015/// \brief Strips various properties off an implicit instantiation
4016/// that has just been explicitly specialized.
4017static void StripImplicitInstantiation(NamedDecl *D) {
4018 D->invalidateAttrs();
4019
4020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4021 FD->setInlineSpecified(false);
4022 }
4023}
4024
Douglas Gregor454885e2009-10-15 15:54:05 +00004025/// \brief Diagnose cases where we have an explicit template specialization
4026/// before/after an explicit template instantiation, producing diagnostics
4027/// for those cases where they are required and determining whether the
4028/// new specialization/instantiation will have any effect.
4029///
Douglas Gregor454885e2009-10-15 15:54:05 +00004030/// \param NewLoc the location of the new explicit specialization or
4031/// instantiation.
4032///
4033/// \param NewTSK the kind of the new explicit specialization or instantiation.
4034///
4035/// \param PrevDecl the previous declaration of the entity.
4036///
4037/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4038///
4039/// \param PrevPointOfInstantiation if valid, indicates where the previus
4040/// declaration was instantiated (either implicitly or explicitly).
4041///
4042/// \param SuppressNew will be set to true to indicate that the new
4043/// specialization or instantiation has no effect and should be ignored.
4044///
4045/// \returns true if there was an error that should prevent the introduction of
4046/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004047bool
4048Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4049 TemplateSpecializationKind NewTSK,
4050 NamedDecl *PrevDecl,
4051 TemplateSpecializationKind PrevTSK,
4052 SourceLocation PrevPointOfInstantiation,
4053 bool &SuppressNew) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004054 SuppressNew = false;
4055
4056 switch (NewTSK) {
4057 case TSK_Undeclared:
4058 case TSK_ImplicitInstantiation:
4059 assert(false && "Don't check implicit instantiations here");
4060 return false;
4061
4062 case TSK_ExplicitSpecialization:
4063 switch (PrevTSK) {
4064 case TSK_Undeclared:
4065 case TSK_ExplicitSpecialization:
4066 // Okay, we're just specializing something that is either already
4067 // explicitly specialized or has merely been mentioned without any
4068 // instantiation.
4069 return false;
4070
4071 case TSK_ImplicitInstantiation:
4072 if (PrevPointOfInstantiation.isInvalid()) {
4073 // The declaration itself has not actually been instantiated, so it is
4074 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004075 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004076 return false;
4077 }
4078 // Fall through
4079
4080 case TSK_ExplicitInstantiationDeclaration:
4081 case TSK_ExplicitInstantiationDefinition:
4082 assert((PrevTSK == TSK_ImplicitInstantiation ||
4083 PrevPointOfInstantiation.isValid()) &&
4084 "Explicit instantiation without point of instantiation?");
4085
4086 // C++ [temp.expl.spec]p6:
4087 // If a template, a member template or the member of a class template
4088 // is explicitly specialized then that specialization shall be declared
4089 // before the first use of that specialization that would cause an
4090 // implicit instantiation to take place, in every translation unit in
4091 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004092 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4093 // Is there any previous explicit specialization declaration?
4094 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4095 return false;
4096 }
4097
Douglas Gregor0d035142009-10-27 18:42:08 +00004098 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004099 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004100 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004101 << (PrevTSK != TSK_ImplicitInstantiation);
4102
4103 return true;
4104 }
4105 break;
4106
4107 case TSK_ExplicitInstantiationDeclaration:
4108 switch (PrevTSK) {
4109 case TSK_ExplicitInstantiationDeclaration:
4110 // This explicit instantiation declaration is redundant (that's okay).
4111 SuppressNew = true;
4112 return false;
4113
4114 case TSK_Undeclared:
4115 case TSK_ImplicitInstantiation:
4116 // We're explicitly instantiating something that may have already been
4117 // implicitly instantiated; that's fine.
4118 return false;
4119
4120 case TSK_ExplicitSpecialization:
4121 // C++0x [temp.explicit]p4:
4122 // For a given set of template parameters, if an explicit instantiation
4123 // of a template appears after a declaration of an explicit
4124 // specialization for that template, the explicit instantiation has no
4125 // effect.
John McCalle97c32f2010-03-02 23:09:38 +00004126 SuppressNew = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004127 return false;
4128
4129 case TSK_ExplicitInstantiationDefinition:
4130 // C++0x [temp.explicit]p10:
4131 // If an entity is the subject of both an explicit instantiation
4132 // declaration and an explicit instantiation definition in the same
4133 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004134 Diag(NewLoc,
4135 diag::err_explicit_instantiation_declaration_after_definition);
4136 Diag(PrevPointOfInstantiation,
4137 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004138 assert(PrevPointOfInstantiation.isValid() &&
4139 "Explicit instantiation without point of instantiation?");
4140 SuppressNew = true;
4141 return false;
4142 }
4143 break;
4144
4145 case TSK_ExplicitInstantiationDefinition:
4146 switch (PrevTSK) {
4147 case TSK_Undeclared:
4148 case TSK_ImplicitInstantiation:
4149 // We're explicitly instantiating something that may have already been
4150 // implicitly instantiated; that's fine.
4151 return false;
4152
4153 case TSK_ExplicitSpecialization:
4154 // C++ DR 259, C++0x [temp.explicit]p4:
4155 // For a given set of template parameters, if an explicit
4156 // instantiation of a template appears after a declaration of
4157 // an explicit specialization for that template, the explicit
4158 // instantiation has no effect.
4159 //
4160 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004161 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004162 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004163 if (!getLangOptions().CPlusPlus0x) {
4164 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004165 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004166 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004167 diag::note_previous_template_specialization);
4168 }
4169 SuppressNew = true;
4170 return false;
4171
4172 case TSK_ExplicitInstantiationDeclaration:
4173 // We're explicity instantiating a definition for something for which we
4174 // were previously asked to suppress instantiations. That's fine.
4175 return false;
4176
4177 case TSK_ExplicitInstantiationDefinition:
4178 // C++0x [temp.spec]p5:
4179 // For a given template and a given set of template-arguments,
4180 // - an explicit instantiation definition shall appear at most once
4181 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004182 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004183 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004184 Diag(PrevPointOfInstantiation,
4185 diag::note_previous_explicit_instantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00004186 SuppressNew = true;
4187 return false;
4188 }
4189 break;
4190 }
4191
4192 assert(false && "Missing specialization/instantiation case?");
4193
4194 return false;
4195}
4196
John McCallaf2094e2010-04-08 09:05:18 +00004197/// \brief Perform semantic analysis for the given dependent function
4198/// template specialization. The only possible way to get a dependent
4199/// function template specialization is with a friend declaration,
4200/// like so:
4201///
4202/// template <class T> void foo(T);
4203/// template <class T> class A {
4204/// friend void foo<>(T);
4205/// };
4206///
4207/// There really isn't any useful analysis we can do here, so we
4208/// just store the information.
4209bool
4210Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4211 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4212 LookupResult &Previous) {
4213 // Remove anything from Previous that isn't a function template in
4214 // the correct context.
4215 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4216 LookupResult::Filter F = Previous.makeFilter();
4217 while (F.hasNext()) {
4218 NamedDecl *D = F.next()->getUnderlyingDecl();
4219 if (!isa<FunctionTemplateDecl>(D) ||
4220 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4221 F.erase();
4222 }
4223 F.done();
4224
4225 // Should this be diagnosed here?
4226 if (Previous.empty()) return true;
4227
4228 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4229 ExplicitTemplateArgs);
4230 return false;
4231}
4232
Abramo Bagnarae03db982010-05-20 15:32:11 +00004233/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004234/// specialization.
4235///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004236/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004237/// explicit function template specialization. On successful completion,
4238/// the function declaration \p FD will become a function template
4239/// specialization.
4240///
4241/// \param FD the function declaration, which will be updated to become a
4242/// function template specialization.
4243///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004244/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4245/// if any. Note that this may be valid info even when 0 arguments are
4246/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4247/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004248///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004249/// \param PrevDecl the set of declarations that may be specialized by
4250/// this function specialization.
4251bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004252Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004253 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004254 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004255 // The set of function template specializations that could match this
4256 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004257 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004258
4259 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00004260 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4261 I != E; ++I) {
4262 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4263 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004264 // Only consider templates found within the same semantic lookup scope as
4265 // FD.
4266 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4267 continue;
4268
4269 // C++ [temp.expl.spec]p11:
4270 // A trailing template-argument can be left unspecified in the
4271 // template-id naming an explicit function template specialization
4272 // provided it can be deduced from the function argument type.
4273 // Perform template argument deduction to determine whether we may be
4274 // specializing this template.
4275 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004276 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004277 FunctionDecl *Specialization = 0;
4278 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004279 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004280 FD->getType(),
4281 Specialization,
4282 Info)) {
4283 // FIXME: Template argument deduction failed; record why it failed, so
4284 // that we can provide nifty diagnostics.
4285 (void)TDK;
4286 continue;
4287 }
4288
4289 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004290 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004291 }
4292 }
4293
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004294 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004295 UnresolvedSetIterator Result
4296 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4297 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004298 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004299 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004300 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004301 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004302 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004303 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004304 return true;
John McCallc373d482010-01-27 01:50:18 +00004305
4306 // Ignore access information; it doesn't figure into redeclaration checking.
4307 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004308 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004309
4310 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004311 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004312
4313 // If this is a friend declaration, then we're not really declaring
4314 // an explicit specialization.
4315 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004316
Douglas Gregord5cb8762009-10-07 00:13:32 +00004317 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004318 if (!isFriend &&
4319 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004320 Specialization->getPrimaryTemplate(),
4321 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004322 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004323 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004324
4325 // C++ [temp.expl.spec]p6:
4326 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004327 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004328 // before the first use of that specialization that would cause an implicit
4329 // instantiation to take place, in every translation unit in which such a
4330 // use occurs; no diagnostic is required.
4331 FunctionTemplateSpecializationInfo *SpecInfo
4332 = Specialization->getTemplateSpecializationInfo();
4333 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004334
4335 bool SuppressNew = false;
John McCall7ad650f2010-03-24 07:46:06 +00004336 if (!isFriend &&
4337 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004338 TSK_ExplicitSpecialization,
4339 Specialization,
4340 SpecInfo->getTemplateSpecializationKind(),
4341 SpecInfo->getPointOfInstantiation(),
4342 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004343 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004344
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004345 // Mark the prior declaration as an explicit specialization, so that later
4346 // clients know that this is an explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004347 if (!isFriend)
4348 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004349
4350 // Turn the given function declaration into a function template
4351 // specialization, with the template arguments from the previous
4352 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004353 // Take copies of (semantic and syntactic) template argument lists.
4354 const TemplateArgumentList* TemplArgs = new (Context)
4355 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4356 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4357 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004358 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004359 TemplArgs, /*InsertPos=*/0,
4360 SpecInfo->getTemplateSpecializationKind(),
4361 TemplArgsAsWritten);
4362
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004363 // The "previous declaration" for this function template specialization is
4364 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004365 Previous.clear();
4366 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004367 return false;
4368}
4369
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004370/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004371/// specialization.
4372///
4373/// This routine performs all of the semantic analysis required for an
4374/// explicit member function specialization. On successful completion,
4375/// the function declaration \p FD will become a member function
4376/// specialization.
4377///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004378/// \param Member the member declaration, which will be updated to become a
4379/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004380///
John McCall68263142009-11-18 22:49:29 +00004381/// \param Previous the set of declarations, one of which may be specialized
4382/// by this function specialization; the set will be modified to contain the
4383/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004384bool
John McCall68263142009-11-18 22:49:29 +00004385Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004386 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004387
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004388 // Try to find the member we are instantiating.
4389 NamedDecl *Instantiation = 0;
4390 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004391 MemberSpecializationInfo *MSInfo = 0;
4392
John McCall68263142009-11-18 22:49:29 +00004393 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004394 // Nowhere to look anyway.
4395 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004396 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4397 I != E; ++I) {
4398 NamedDecl *D = (*I)->getUnderlyingDecl();
4399 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004400 if (Context.hasSameType(Function->getType(), Method->getType())) {
4401 Instantiation = Method;
4402 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004403 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004404 break;
4405 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004406 }
4407 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004408 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004409 VarDecl *PrevVar;
4410 if (Previous.isSingleResult() &&
4411 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004412 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004413 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004414 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004415 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004416 }
4417 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004418 CXXRecordDecl *PrevRecord;
4419 if (Previous.isSingleResult() &&
4420 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4421 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004422 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004423 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004424 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004425 }
4426
4427 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004428 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004429 // specializations are always out-of-line, the caller will complain about
4430 // this mismatch later.
4431 return false;
4432 }
John McCall77e8b112010-04-13 20:37:33 +00004433
4434 // If this is a friend, just bail out here before we start turning
4435 // things into explicit specializations.
4436 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4437 // Preserve instantiation information.
4438 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4439 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4440 cast<CXXMethodDecl>(InstantiatedFrom),
4441 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4442 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4443 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4444 cast<CXXRecordDecl>(InstantiatedFrom),
4445 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4446 }
4447
4448 Previous.clear();
4449 Previous.addDecl(Instantiation);
4450 return false;
4451 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004452
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004453 // Make sure that this is a specialization of a member.
4454 if (!InstantiatedFrom) {
4455 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4456 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004457 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4458 return true;
4459 }
4460
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004461 // C++ [temp.expl.spec]p6:
4462 // If a template, a member template or the member of a class template is
4463 // explicitly specialized then that spe- cialization shall be declared
4464 // before the first use of that specialization that would cause an implicit
4465 // instantiation to take place, in every translation unit in which such a
4466 // use occurs; no diagnostic is required.
4467 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004468
4469 bool SuppressNew = false;
4470 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4471 TSK_ExplicitSpecialization,
4472 Instantiation,
4473 MSInfo->getTemplateSpecializationKind(),
4474 MSInfo->getPointOfInstantiation(),
4475 SuppressNew))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004476 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004477
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004478 // Check the scope of this explicit specialization.
4479 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004480 InstantiatedFrom,
4481 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004482 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004483 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004484
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004485 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004486 // the original declaration to note that it is an explicit specialization
4487 // (if it was previously an implicit instantiation). This latter step
4488 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004489 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004490 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4491 if (InstantiationFunction->getTemplateSpecializationKind() ==
4492 TSK_ImplicitInstantiation) {
4493 InstantiationFunction->setTemplateSpecializationKind(
4494 TSK_ExplicitSpecialization);
4495 InstantiationFunction->setLocation(Member->getLocation());
4496 }
4497
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004498 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4499 cast<CXXMethodDecl>(InstantiatedFrom),
4500 TSK_ExplicitSpecialization);
4501 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004502 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4503 if (InstantiationVar->getTemplateSpecializationKind() ==
4504 TSK_ImplicitInstantiation) {
4505 InstantiationVar->setTemplateSpecializationKind(
4506 TSK_ExplicitSpecialization);
4507 InstantiationVar->setLocation(Member->getLocation());
4508 }
4509
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004510 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4511 cast<VarDecl>(InstantiatedFrom),
4512 TSK_ExplicitSpecialization);
4513 } else {
4514 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004515 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4516 if (InstantiationClass->getTemplateSpecializationKind() ==
4517 TSK_ImplicitInstantiation) {
4518 InstantiationClass->setTemplateSpecializationKind(
4519 TSK_ExplicitSpecialization);
4520 InstantiationClass->setLocation(Member->getLocation());
4521 }
4522
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004523 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004524 cast<CXXRecordDecl>(InstantiatedFrom),
4525 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004526 }
4527
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004528 // Save the caller the trouble of having to figure out which declaration
4529 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004530 Previous.clear();
4531 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004532 return false;
4533}
4534
Douglas Gregor558c0322009-10-14 23:41:34 +00004535/// \brief Check the scope of an explicit instantiation.
4536static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4537 SourceLocation InstLoc,
4538 bool WasQualifiedName) {
4539 DeclContext *ExpectedContext
4540 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4541 DeclContext *CurContext = S.CurContext->getLookupContext();
4542
4543 // C++0x [temp.explicit]p2:
4544 // An explicit instantiation shall appear in an enclosing namespace of its
4545 // template.
4546 //
4547 // This is DR275, which we do not retroactively apply to C++98/03.
4548 if (S.getLangOptions().CPlusPlus0x &&
4549 !CurContext->Encloses(ExpectedContext)) {
4550 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004551 S.Diag(InstLoc,
4552 S.getLangOptions().CPlusPlus0x?
4553 diag::err_explicit_instantiation_out_of_scope
4554 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004555 << D << NS;
4556 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004557 S.Diag(InstLoc,
4558 S.getLangOptions().CPlusPlus0x?
4559 diag::err_explicit_instantiation_must_be_global
4560 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004561 << D;
4562 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4563 return;
4564 }
4565
4566 // C++0x [temp.explicit]p2:
4567 // If the name declared in the explicit instantiation is an unqualified
4568 // name, the explicit instantiation shall appear in the namespace where
4569 // its template is declared or, if that namespace is inline (7.3.1), any
4570 // namespace from its enclosing namespace set.
4571 if (WasQualifiedName)
4572 return;
4573
4574 if (CurContext->Equals(ExpectedContext))
4575 return;
4576
Douglas Gregor2166beb2010-05-11 17:39:34 +00004577 S.Diag(InstLoc,
4578 S.getLangOptions().CPlusPlus0x?
4579 diag::err_explicit_instantiation_unqualified_wrong_namespace
4580 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004581 << D << ExpectedContext;
4582 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4583}
4584
4585/// \brief Determine whether the given scope specifier has a template-id in it.
4586static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4587 if (!SS.isSet())
4588 return false;
4589
4590 // C++0x [temp.explicit]p2:
4591 // If the explicit instantiation is for a member function, a member class
4592 // or a static data member of a class template specialization, the name of
4593 // the class template specialization in the qualified-id for the member
4594 // name shall be a simple-template-id.
4595 //
4596 // C++98 has the same restriction, just worded differently.
4597 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4598 NNS; NNS = NNS->getPrefix())
4599 if (Type *T = NNS->getAsType())
4600 if (isa<TemplateSpecializationType>(T))
4601 return true;
4602
4603 return false;
4604}
4605
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004606// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004607Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004608Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004609 SourceLocation ExternLoc,
4610 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004611 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004612 SourceLocation KWLoc,
4613 const CXXScopeSpec &SS,
4614 TemplateTy TemplateD,
4615 SourceLocation TemplateNameLoc,
4616 SourceLocation LAngleLoc,
4617 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004618 SourceLocation RAngleLoc,
4619 AttributeList *Attr) {
4620 // Find the class template we're specializing
4621 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004622 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004623 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4624
4625 // Check that the specialization uses the same tag kind as the
4626 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004627 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4628 assert(Kind != TTK_Enum &&
4629 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004630 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004631 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004632 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004633 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004634 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004635 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004636 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004637 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004638 diag::note_previous_use);
4639 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4640 }
4641
Douglas Gregor558c0322009-10-14 23:41:34 +00004642 // C++0x [temp.explicit]p2:
4643 // There are two forms of explicit instantiation: an explicit instantiation
4644 // definition and an explicit instantiation declaration. An explicit
4645 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004646 TemplateSpecializationKind TSK
4647 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4648 : TSK_ExplicitInstantiationDeclaration;
4649
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004650 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004651 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004652 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004653
4654 // Check that the template argument list is well-formed for this
4655 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004656 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4657 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004658 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4659 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004660 return true;
4661
Mike Stump1eb44332009-09-09 15:08:12 +00004662 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004663 ClassTemplate->getTemplateParameters()->size()) &&
4664 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004666 // Find the class template specialization declaration that
4667 // corresponds to these arguments.
4668 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004669 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004670 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004671 Converted.flatSize(),
4672 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004673 void *InsertPos = 0;
4674 ClassTemplateSpecializationDecl *PrevDecl
4675 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4676
Douglas Gregord5cb8762009-10-07 00:13:32 +00004677 // C++0x [temp.explicit]p2:
4678 // [...] An explicit instantiation shall appear in an enclosing
4679 // namespace of its template. [...]
4680 //
4681 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004682 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4683 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004684
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004685 ClassTemplateSpecializationDecl *Specialization = 0;
4686
Douglas Gregord78f5982009-11-25 06:01:46 +00004687 bool ReusedDecl = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004688 if (PrevDecl) {
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004689 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00004690 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004691 PrevDecl,
4692 PrevDecl->getSpecializationKind(),
4693 PrevDecl->getPointOfInstantiation(),
4694 SuppressNew))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004695 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004696
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004697 if (SuppressNew)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004698 return DeclPtrTy::make(PrevDecl);
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004699
Douglas Gregor52604ab2009-09-11 21:19:12 +00004700 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4701 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4702 // Since the only prior class template specialization with these
4703 // arguments was referenced but not declared, reuse that
4704 // declaration node as our own, updating its source location to
4705 // reflect our new declaration.
4706 Specialization = PrevDecl;
4707 Specialization->setLocation(TemplateNameLoc);
4708 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004709 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004710 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004711 }
Douglas Gregor52604ab2009-09-11 21:19:12 +00004712
4713 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004714 // Create a new class template specialization declaration node for
4715 // this explicit specialization.
4716 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004717 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004718 ClassTemplate->getDeclContext(),
4719 TemplateNameLoc,
4720 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004721 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004722 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004723
Douglas Gregor52604ab2009-09-11 21:19:12 +00004724 if (PrevDecl) {
4725 // Remove the previous declaration from the folding set, since we want
4726 // to introduce a new declaration.
4727 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4728 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4729 }
4730
4731 // Insert the new specialization.
4732 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004733 }
4734
4735 // Build the fully-sugared type for this explicit instantiation as
4736 // the user wrote in the explicit instantiation itself. This means
4737 // that we'll pretty-print the type retrieved from the
4738 // specialization's declaration the way that the user actually wrote
4739 // the explicit instantiation, rather than formatting the name based
4740 // on the "canonical" representation used to store the template
4741 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004742 TypeSourceInfo *WrittenTy
4743 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4744 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004745 Context.getTypeDeclType(Specialization));
4746 Specialization->setTypeAsWritten(WrittenTy);
4747 TemplateArgsIn.release();
4748
Douglas Gregord78f5982009-11-25 06:01:46 +00004749 if (!ReusedDecl) {
4750 // Add the explicit instantiation into its lexical context. However,
4751 // since explicit instantiations are never found by name lookup, we
4752 // just put it into the declaration context directly.
4753 Specialization->setLexicalDeclContext(CurContext);
4754 CurContext->addDecl(Specialization);
4755 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004756
4757 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004758 // A definition of a class template or class member template
4759 // shall be in scope at the point of the explicit instantiation of
4760 // the class template or class member template.
4761 //
4762 // This check comes when we actually try to perform the
4763 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004764 ClassTemplateSpecializationDecl *Def
4765 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004766 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004767 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004768 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004769 else if (TSK == TSK_ExplicitInstantiationDefinition)
4770 MarkVTableUsed(TemplateNameLoc, Specialization, true);
4771
Douglas Gregor0d035142009-10-27 18:42:08 +00004772 // Instantiate the members of this class template specialization.
4773 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004774 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004775 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004776 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4777
4778 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4779 // TSK_ExplicitInstantiationDefinition
4780 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4781 TSK == TSK_ExplicitInstantiationDefinition)
4782 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004783
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004784 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004785 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004786
4787 return DeclPtrTy::make(Specialization);
4788}
4789
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004790// Explicit instantiation of a member class of a class template.
4791Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004792Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004793 SourceLocation ExternLoc,
4794 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004795 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004796 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004797 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004798 IdentifierInfo *Name,
4799 SourceLocation NameLoc,
4800 AttributeList *Attr) {
4801
Douglas Gregor402abb52009-05-28 23:31:59 +00004802 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004803 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004804 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004805 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004806 MultiTemplateParamsArg(*this, 0, 0),
4807 Owned, IsDependent);
4808 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4809
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004810 if (!TagD)
4811 return true;
4812
4813 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4814 if (Tag->isEnum()) {
4815 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4816 << Context.getTypeDeclType(Tag);
4817 return true;
4818 }
4819
Douglas Gregord0c87372009-05-27 17:30:49 +00004820 if (Tag->isInvalidDecl())
4821 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004822
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004823 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4824 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4825 if (!Pattern) {
4826 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4827 << Context.getTypeDeclType(Record);
4828 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4829 return true;
4830 }
4831
Douglas Gregor558c0322009-10-14 23:41:34 +00004832 // C++0x [temp.explicit]p2:
4833 // If the explicit instantiation is for a class or member class, the
4834 // elaborated-type-specifier in the declaration shall include a
4835 // simple-template-id.
4836 //
4837 // C++98 has the same restriction, just worded differently.
4838 if (!ScopeSpecifierHasTemplateId(SS))
4839 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4840 << Record << SS.getRange();
4841
4842 // C++0x [temp.explicit]p2:
4843 // There are two forms of explicit instantiation: an explicit instantiation
4844 // definition and an explicit instantiation declaration. An explicit
4845 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004846 TemplateSpecializationKind TSK
4847 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4848 : TSK_ExplicitInstantiationDeclaration;
4849
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004850 // C++0x [temp.explicit]p2:
4851 // [...] An explicit instantiation shall appear in an enclosing
4852 // namespace of its template. [...]
4853 //
4854 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004855 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004856
4857 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004858 CXXRecordDecl *PrevDecl
4859 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004860 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004861 PrevDecl = Record;
4862 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004863 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4864 bool SuppressNew = false;
4865 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004866 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004867 PrevDecl,
4868 MSInfo->getTemplateSpecializationKind(),
4869 MSInfo->getPointOfInstantiation(),
4870 SuppressNew))
4871 return true;
4872 if (SuppressNew)
4873 return TagD;
4874 }
4875
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004876 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004877 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004878 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004879 // C++ [temp.explicit]p3:
4880 // A definition of a member class of a class template shall be in scope
4881 // at the point of an explicit instantiation of the member class.
4882 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004883 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004884 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004885 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4886 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004887 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4888 << Pattern;
4889 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004890 } else {
4891 if (InstantiateClass(NameLoc, Record, Def,
4892 getTemplateInstantiationArgs(Record),
4893 TSK))
4894 return true;
4895
Douglas Gregor952b0172010-02-11 01:04:33 +00004896 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004897 if (!RecordDef)
4898 return true;
4899 }
4900 }
4901
4902 // Instantiate all of the members of the class.
4903 InstantiateClassMembers(NameLoc, RecordDef,
4904 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004905
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004906 if (TSK == TSK_ExplicitInstantiationDefinition)
4907 MarkVTableUsed(NameLoc, RecordDef, true);
4908
Mike Stump390b4cc2009-05-16 07:39:55 +00004909 // FIXME: We don't have any representation for explicit instantiations of
4910 // member classes. Such a representation is not needed for compilation, but it
4911 // should be available for clients that want to see all of the declarations in
4912 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004913 return TagD;
4914}
4915
Douglas Gregord5a423b2009-09-25 18:43:00 +00004916Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4917 SourceLocation ExternLoc,
4918 SourceLocation TemplateLoc,
4919 Declarator &D) {
4920 // Explicit instantiations always require a name.
4921 DeclarationName Name = GetNameForDeclarator(D);
4922 if (!Name) {
4923 if (!D.isInvalidType())
4924 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4925 diag::err_explicit_instantiation_requires_name)
4926 << D.getDeclSpec().getSourceRange()
4927 << D.getSourceRange();
4928
4929 return true;
4930 }
4931
4932 // The scope passed in may not be a decl scope. Zip up the scope tree until
4933 // we find one that is.
4934 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4935 (S->getFlags() & Scope::TemplateParamScope) != 0)
4936 S = S->getParent();
4937
4938 // Determine the type of the declaration.
4939 QualType R = GetTypeForDeclarator(D, S, 0);
4940 if (R.isNull())
4941 return true;
4942
4943 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4944 // Cannot explicitly instantiate a typedef.
4945 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4946 << Name;
4947 return true;
4948 }
4949
Douglas Gregor663b5a02009-10-14 20:14:33 +00004950 // C++0x [temp.explicit]p1:
4951 // [...] An explicit instantiation of a function template shall not use the
4952 // inline or constexpr specifiers.
4953 // Presumably, this also applies to member functions of class templates as
4954 // well.
4955 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4956 Diag(D.getDeclSpec().getInlineSpecLoc(),
4957 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00004958 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00004959
4960 // FIXME: check for constexpr specifier.
4961
Douglas Gregor558c0322009-10-14 23:41:34 +00004962 // C++0x [temp.explicit]p2:
4963 // There are two forms of explicit instantiation: an explicit instantiation
4964 // definition and an explicit instantiation declaration. An explicit
4965 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00004966 TemplateSpecializationKind TSK
4967 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4968 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00004969
John McCalla24dc2e2009-11-17 02:14:36 +00004970 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4971 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00004972
4973 if (!R->isFunctionType()) {
4974 // C++ [temp.explicit]p1:
4975 // A [...] static data member of a class template can be explicitly
4976 // instantiated from the member definition associated with its class
4977 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00004978 if (Previous.isAmbiguous())
4979 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004980
John McCall1bcee0a2009-12-02 08:25:40 +00004981 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004982 if (!Prev || !Prev->isStaticDataMember()) {
4983 // We expect to see a data data member here.
4984 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4985 << Name;
4986 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4987 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00004988 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00004989 return true;
4990 }
4991
4992 if (!Prev->getInstantiatedFromStaticDataMember()) {
4993 // FIXME: Check for explicit specialization?
4994 Diag(D.getIdentifierLoc(),
4995 diag::err_explicit_instantiation_data_member_not_instantiated)
4996 << Prev;
4997 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4998 // FIXME: Can we provide a note showing where this was declared?
4999 return true;
5000 }
5001
Douglas Gregor558c0322009-10-14 23:41:34 +00005002 // C++0x [temp.explicit]p2:
5003 // If the explicit instantiation is for a member function, a member class
5004 // or a static data member of a class template specialization, the name of
5005 // the class template specialization in the qualified-id for the member
5006 // name shall be a simple-template-id.
5007 //
5008 // C++98 has the same restriction, just worded differently.
5009 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5010 Diag(D.getIdentifierLoc(),
5011 diag::err_explicit_instantiation_without_qualified_id)
5012 << Prev << D.getCXXScopeSpec().getRange();
5013
5014 // Check the scope of this explicit instantiation.
5015 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5016
Douglas Gregor454885e2009-10-15 15:54:05 +00005017 // Verify that it is okay to explicitly instantiate here.
5018 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5019 assert(MSInfo && "Missing static data member specialization info?");
5020 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005021 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005022 MSInfo->getTemplateSpecializationKind(),
5023 MSInfo->getPointOfInstantiation(),
5024 SuppressNew))
5025 return true;
5026 if (SuppressNew)
5027 return DeclPtrTy();
5028
Douglas Gregord5a423b2009-09-25 18:43:00 +00005029 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005030 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005031 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005032 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5033 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005034
5035 // FIXME: Create an ExplicitInstantiation node?
5036 return DeclPtrTy();
5037 }
5038
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005039 // If the declarator is a template-id, translate the parser's template
5040 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005041 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005042 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005043 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5044 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005045 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5046 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005047 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5048 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005049 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005050 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005051 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005052 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005053 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005054
Douglas Gregord5a423b2009-09-25 18:43:00 +00005055 // C++ [temp.explicit]p1:
5056 // A [...] function [...] can be explicitly instantiated from its template.
5057 // A member function [...] of a class template can be explicitly
5058 // instantiated from the member definition associated with its class
5059 // template.
John McCallc373d482010-01-27 01:50:18 +00005060 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005061 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5062 P != PEnd; ++P) {
5063 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005064 if (!HasExplicitTemplateArgs) {
5065 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5066 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5067 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005068
John McCallc373d482010-01-27 01:50:18 +00005069 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005070 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5071 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005072 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005073 }
5074 }
5075
5076 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5077 if (!FunTmpl)
5078 continue;
5079
John McCall5769d612010-02-08 23:07:23 +00005080 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005081 FunctionDecl *Specialization = 0;
5082 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005083 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005084 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005085 R, Specialization, Info)) {
5086 // FIXME: Keep track of almost-matches?
5087 (void)TDK;
5088 continue;
5089 }
5090
John McCallc373d482010-01-27 01:50:18 +00005091 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005092 }
5093
5094 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005095 UnresolvedSetIterator Result
5096 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005097 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005098 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5099 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5100 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005101
John McCallc373d482010-01-27 01:50:18 +00005102 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005103 return true;
John McCallc373d482010-01-27 01:50:18 +00005104
5105 // Ignore access control bits, we don't need them for redeclaration checking.
5106 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005107
Douglas Gregor0a897e32009-10-15 17:21:20 +00005108 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005109 Diag(D.getIdentifierLoc(),
5110 diag::err_explicit_instantiation_member_function_not_instantiated)
5111 << Specialization
5112 << (Specialization->getTemplateSpecializationKind() ==
5113 TSK_ExplicitSpecialization);
5114 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5115 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005116 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005117
Douglas Gregor0a897e32009-10-15 17:21:20 +00005118 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005119 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5120 PrevDecl = Specialization;
5121
Douglas Gregor0a897e32009-10-15 17:21:20 +00005122 if (PrevDecl) {
5123 bool SuppressNew = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005124 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005125 PrevDecl,
5126 PrevDecl->getTemplateSpecializationKind(),
5127 PrevDecl->getPointOfInstantiation(),
5128 SuppressNew))
5129 return true;
5130
5131 // FIXME: We may still want to build some representation of this
5132 // explicit specialization.
5133 if (SuppressNew)
5134 return DeclPtrTy();
5135 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005136
5137 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005138
5139 if (TSK == TSK_ExplicitInstantiationDefinition)
5140 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5141 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005142
Douglas Gregor558c0322009-10-14 23:41:34 +00005143 // C++0x [temp.explicit]p2:
5144 // If the explicit instantiation is for a member function, a member class
5145 // or a static data member of a class template specialization, the name of
5146 // the class template specialization in the qualified-id for the member
5147 // name shall be a simple-template-id.
5148 //
5149 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005150 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005151 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005152 D.getCXXScopeSpec().isSet() &&
5153 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5154 Diag(D.getIdentifierLoc(),
5155 diag::err_explicit_instantiation_without_qualified_id)
5156 << Specialization << D.getCXXScopeSpec().getRange();
5157
5158 CheckExplicitInstantiationScope(*this,
5159 FunTmpl? (NamedDecl *)FunTmpl
5160 : Specialization->getInstantiatedFromMemberFunction(),
5161 D.getIdentifierLoc(),
5162 D.getCXXScopeSpec().isSet());
5163
Douglas Gregord5a423b2009-09-25 18:43:00 +00005164 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5165 return DeclPtrTy();
5166}
5167
Douglas Gregord57959a2009-03-27 23:10:48 +00005168Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005169Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5170 const CXXScopeSpec &SS, IdentifierInfo *Name,
5171 SourceLocation TagLoc, SourceLocation NameLoc) {
5172 // This has to hold, because SS is expected to be defined.
5173 assert(Name && "Expected a name in a dependent tag");
5174
5175 NestedNameSpecifier *NNS
5176 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5177 if (!NNS)
5178 return true;
5179
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005180 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005181
Douglas Gregor48c89f42010-04-24 16:38:41 +00005182 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5183 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005184 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005185 return true;
5186 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005187
5188 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5189 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCallc4e70192009-09-11 04:59:25 +00005190}
5191
John McCall63b43852010-04-29 23:50:39 +00005192static void FillTypeLoc(DependentNameTypeLoc TL,
5193 SourceLocation TypenameLoc,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005194 SourceRange QualifierRange,
5195 SourceLocation NameLoc) {
5196 TL.setKeywordLoc(TypenameLoc);
5197 TL.setQualifierRange(QualifierRange);
5198 TL.setNameLoc(NameLoc);
John McCall63b43852010-04-29 23:50:39 +00005199}
5200
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005201static void FillTypeLoc(ElaboratedTypeLoc TL,
John McCall63b43852010-04-29 23:50:39 +00005202 SourceLocation TypenameLoc,
5203 SourceRange QualifierRange) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005204 // FIXME: inner locations.
5205 TL.setKeywordLoc(TypenameLoc);
5206 TL.setQualifierRange(QualifierRange);
John McCall63b43852010-04-29 23:50:39 +00005207}
5208
John McCallc4e70192009-09-11 04:59:25 +00005209Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00005210Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5211 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005212 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005213 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5214 if (!NNS)
5215 return true;
5216
Douglas Gregor107de902010-04-24 15:35:55 +00005217 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005218 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005219 if (T.isNull())
5220 return true;
John McCall63b43852010-04-29 23:50:39 +00005221
5222 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5223 if (isa<DependentNameType>(T)) {
5224 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5225 // FIXME: fill inner type loc
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005226 FillTypeLoc(TL, TypenameLoc, SS.getRange(), IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005227 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005228 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall63b43852010-04-29 23:50:39 +00005229 // FIXME: fill inner type loc
5230 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5231 }
5232
5233 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregord57959a2009-03-27 23:10:48 +00005234}
5235
Douglas Gregor17343172009-04-01 00:28:59 +00005236Sema::TypeResult
5237Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5238 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005239 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005240 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00005241 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump1eb44332009-09-09 15:08:12 +00005242 const TemplateSpecializationType *TemplateId
John McCall183700f2009-09-21 23:43:11 +00005243 = T->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00005244 assert(TemplateId && "Expected a template specialization type");
5245
Douglas Gregor6946baf2009-09-02 13:05:45 +00005246 if (computeDeclContext(SS, false)) {
5247 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005248 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005249 // track of the nested-name-specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005250 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCall63b43852010-04-29 23:50:39 +00005251 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005252 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall63b43852010-04-29 23:50:39 +00005253 // FIXME: fill inner type loc
5254 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5255 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor6946baf2009-09-02 13:05:45 +00005256 }
Mike Stump1eb44332009-09-09 15:08:12 +00005257
John McCall63b43852010-04-29 23:50:39 +00005258 T = Context.getDependentNameType(ETK_Typename, NNS, TemplateId);
5259 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5260 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5261 // FIXME: fill inner type loc
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005262 FillTypeLoc(TL, TypenameLoc, SS.getRange(), TemplateLoc);
John McCall63b43852010-04-29 23:50:39 +00005263 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00005264}
5265
Douglas Gregord57959a2009-03-27 23:10:48 +00005266/// \brief Build the type that describes a C++ typename specifier,
5267/// e.g., "typename T::type".
5268QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005269Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5270 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005271 SourceLocation KeywordLoc, SourceRange NNSRange,
5272 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005273 CXXScopeSpec SS;
5274 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005275 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005276
John McCall77bb1aa2010-05-01 00:40:08 +00005277 DeclContext *Ctx = computeDeclContext(SS);
5278 if (!Ctx) {
5279 // If the nested-name-specifier is dependent and couldn't be
5280 // resolved to a type, build a typename type.
5281 assert(NNS->isDependent());
5282 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005283 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005284
John McCall77bb1aa2010-05-01 00:40:08 +00005285 // If the nested-name-specifier refers to the current instantiation,
5286 // the "typename" keyword itself is superfluous. In C++03, the
5287 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5288 // allows such extraneous "typename" keywords, and we retroactively
5289 // apply this DR to C++03 code. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005290
John McCall77bb1aa2010-05-01 00:40:08 +00005291 if (RequireCompleteDeclContext(SS, Ctx))
5292 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005293
5294 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005295 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005296 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005297 unsigned DiagID = 0;
5298 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005299 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005300 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005301 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005302 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005303
5304 case LookupResult::NotFoundInCurrentInstantiation:
5305 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005306 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005307
5308 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00005309 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005310 // We found a type. Build an ElaboratedType, since the
5311 // typename-specifier was just sugar.
5312 return Context.getElaboratedType(ETK_Typename, NNS,
5313 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005314 }
5315
5316 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005317 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005318 break;
5319
John McCall7ba107a2009-11-18 02:36:19 +00005320 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005321 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005322 return QualType();
5323
Douglas Gregord57959a2009-03-27 23:10:48 +00005324 case LookupResult::FoundOverloaded:
5325 DiagID = diag::err_typename_nested_not_type;
5326 Referenced = *Result.begin();
5327 break;
5328
John McCall6e247262009-10-10 05:48:19 +00005329 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005330 return QualType();
5331 }
5332
5333 // If we get here, it's because name lookup did not find a
5334 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005335 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5336 IILoc);
5337 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005338 if (Referenced)
5339 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5340 << Name;
5341 return QualType();
5342}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005343
5344namespace {
5345 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005346 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005347 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005348 SourceLocation Loc;
5349 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005350
Douglas Gregor4a959d82009-08-06 16:20:37 +00005351 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005352 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5353
Mike Stump1eb44332009-09-09 15:08:12 +00005354 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005355 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005356 DeclarationName Entity)
5357 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005358 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005359
5360 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005361 /// transformed.
5362 ///
5363 /// For the purposes of type reconstruction, a type has already been
5364 /// transformed if it is NULL or if it is not dependent.
5365 bool AlreadyTransformed(QualType T) {
5366 return T.isNull() || !T->isDependentType();
5367 }
Mike Stump1eb44332009-09-09 15:08:12 +00005368
5369 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005370 /// rebuilt.
5371 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005372
Douglas Gregor4a959d82009-08-06 16:20:37 +00005373 /// \brief Returns the name of the entity whose type is being rebuilt.
5374 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005375
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005376 /// \brief Sets the "base" location and entity when that
5377 /// information is known based on another transformation.
5378 void setBase(SourceLocation Loc, DeclarationName Entity) {
5379 this->Loc = Loc;
5380 this->Entity = Entity;
5381 }
5382
Douglas Gregor4a959d82009-08-06 16:20:37 +00005383 /// \brief Transforms an expression by returning the expression itself
5384 /// (an identity function).
5385 ///
5386 /// FIXME: This is completely unsafe; we will need to actually clone the
5387 /// expressions.
5388 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor895162d2010-04-30 18:55:50 +00005389 return getSema().Owned(E->Retain());
Douglas Gregor4a959d82009-08-06 16:20:37 +00005390 }
Mike Stump1eb44332009-09-09 15:08:12 +00005391
Douglas Gregor4a959d82009-08-06 16:20:37 +00005392 /// \brief Transforms a typename type by determining whether the type now
5393 /// refers to a member of the current instantiation, and then
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005394 /// type-checking and building an ElaboratedType (when possible).
5395 QualType TransformDependentNameType(TypeLocBuilder &TLB,
5396 DependentNameTypeLoc TL,
5397 QualType ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005398 };
5399}
5400
Mike Stump1eb44332009-09-09 15:08:12 +00005401QualType
Douglas Gregor4714c122010-03-31 17:34:00 +00005402CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5403 DependentNameTypeLoc TL,
Douglas Gregor124b8782010-02-16 19:09:40 +00005404 QualType ObjectType) {
Douglas Gregor4714c122010-03-31 17:34:00 +00005405 DependentNameType *T = TL.getTypePtr();
John McCalla2becad2009-10-21 00:40:46 +00005406
Douglas Gregor4a959d82009-08-06 16:20:37 +00005407 NestedNameSpecifier *NNS
5408 = TransformNestedNameSpecifier(T->getQualifier(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005409 TL.getQualifierRange(),
Douglas Gregor124b8782010-02-16 19:09:40 +00005410 ObjectType);
Douglas Gregor4a959d82009-08-06 16:20:37 +00005411 if (!NNS)
5412 return QualType();
5413
5414 // If the nested-name-specifier did not change, and we cannot compute the
5415 // context corresponding to the nested-name-specifier, then this
5416 // typename type will not change; exit early.
5417 CXXScopeSpec SS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005418 SS.setRange(TL.getQualifierRange());
Douglas Gregor4a959d82009-08-06 16:20:37 +00005419 SS.setScopeRep(NNS);
John McCall833ca992009-10-29 08:12:44 +00005420
5421 QualType Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005422 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall833ca992009-10-29 08:12:44 +00005423 Result = QualType(T, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00005424
5425 // Rebuild the typename type, which will probably turn into a
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005426 // ElaboratedType.
John McCall833ca992009-10-29 08:12:44 +00005427 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005428 QualType NewTemplateId
Douglas Gregor4a959d82009-08-06 16:20:37 +00005429 = TransformType(QualType(TemplateId, 0));
5430 if (NewTemplateId.isNull())
5431 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005432
Douglas Gregor4a959d82009-08-06 16:20:37 +00005433 if (NNS == T->getQualifier() &&
5434 NewTemplateId == QualType(TemplateId, 0))
John McCall833ca992009-10-29 08:12:44 +00005435 Result = QualType(T, 0);
5436 else
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005437 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
Douglas Gregor4a2023f2010-03-31 20:19:30 +00005438 NNS, NewTemplateId);
John McCall833ca992009-10-29 08:12:44 +00005439 } else
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005440 Result = getDerived().RebuildDependentNameType(T->getKeyword(), NNS,
5441 T->getIdentifier(),
5442 TL.getKeywordLoc(),
5443 TL.getQualifierRange(),
5444 TL.getNameLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00005445
Douglas Gregora50ce322010-03-07 23:26:22 +00005446 if (Result.isNull())
5447 return QualType();
5448
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005449 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5450 QualType NamedT = ElabT->getNamedType();
5451 if (isa<TemplateSpecializationType>(NamedT)) {
5452 TemplateSpecializationTypeLoc NamedTLoc
5453 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5454 // FIXME: fill locations
5455 NamedTLoc.initializeLocal(TL.getNameLoc());
5456 } else {
5457 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5458 }
5459 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5460 NewTL.setKeywordLoc(TL.getKeywordLoc());
5461 NewTL.setQualifierRange(TL.getQualifierRange());
5462 }
5463 else {
5464 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5465 NewTL.setKeywordLoc(TL.getKeywordLoc());
5466 NewTL.setQualifierRange(TL.getQualifierRange());
5467 NewTL.setNameLoc(TL.getNameLoc());
5468 }
John McCall833ca992009-10-29 08:12:44 +00005469 return Result;
Douglas Gregor4a959d82009-08-06 16:20:37 +00005470}
5471
5472/// \brief Rebuilds a type within the context of the current instantiation.
5473///
Mike Stump1eb44332009-09-09 15:08:12 +00005474/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005475/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005476/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005477/// partial specialization thereof). This routine will rebuild that type now
5478/// that we have entered the declarator's scope, which may produce different
5479/// canonical types, e.g.,
5480///
5481/// \code
5482/// template<typename T>
5483/// struct X {
5484/// typedef T* pointer;
5485/// pointer data();
5486/// };
5487///
5488/// template<typename T>
5489/// typename X<T>::pointer X<T>::data() { ... }
5490/// \endcode
5491///
Douglas Gregor4714c122010-03-31 17:34:00 +00005492/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005493/// since we do not know that we can look into X<T> when we parsed the type.
5494/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005495/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005496/// as the canonical type of T*, allowing the return types of the out-of-line
5497/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005498TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5499 SourceLocation Loc,
5500 DeclarationName Name) {
5501 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005502 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005503
Douglas Gregor4a959d82009-08-06 16:20:37 +00005504 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5505 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005506}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005507
John McCall63b43852010-04-29 23:50:39 +00005508bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5509 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005510
5511 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5512 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5513 DeclarationName());
5514 NestedNameSpecifier *Rebuilt =
5515 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005516 if (!Rebuilt) return true;
5517
5518 SS.setScopeRep(Rebuilt);
5519 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005520}
5521
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005522/// \brief Produces a formatted string that describes the binding of
5523/// template parameters to template arguments.
5524std::string
5525Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5526 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005527 // FIXME: For variadic templates, we'll need to get the structured list.
5528 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5529 Args.flat_size());
5530}
5531
5532std::string
5533Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5534 const TemplateArgument *Args,
5535 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005536 std::string Result;
5537
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005538 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005539 return Result;
5540
5541 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005542 if (I >= NumArgs)
5543 break;
5544
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005545 if (I == 0)
5546 Result += "[with ";
5547 else
5548 Result += ", ";
5549
5550 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5551 Result += Id->getName();
5552 } else {
5553 Result += '$';
5554 Result += llvm::utostr(I);
5555 }
5556
5557 Result += " = ";
5558
5559 switch (Args[I].getKind()) {
5560 case TemplateArgument::Null:
5561 Result += "<no value>";
5562 break;
5563
5564 case TemplateArgument::Type: {
5565 std::string TypeStr;
5566 Args[I].getAsType().getAsStringInternal(TypeStr,
5567 Context.PrintingPolicy);
5568 Result += TypeStr;
5569 break;
5570 }
5571
5572 case TemplateArgument::Declaration: {
5573 bool Unnamed = true;
5574 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5575 if (ND->getDeclName()) {
5576 Unnamed = false;
5577 Result += ND->getNameAsString();
5578 }
5579 }
5580
5581 if (Unnamed) {
5582 Result += "<anonymous>";
5583 }
5584 break;
5585 }
5586
Douglas Gregor788cd062009-11-11 01:00:40 +00005587 case TemplateArgument::Template: {
5588 std::string Str;
5589 llvm::raw_string_ostream OS(Str);
5590 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5591 Result += OS.str();
5592 break;
5593 }
5594
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005595 case TemplateArgument::Integral: {
5596 Result += Args[I].getAsIntegral()->toString(10);
5597 break;
5598 }
5599
5600 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005601 // FIXME: This is non-optimal, since we're regurgitating the
5602 // expression we were given.
5603 std::string Str;
5604 {
5605 llvm::raw_string_ostream OS(Str);
5606 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5607 Context.PrintingPolicy);
5608 }
5609 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005610 break;
5611 }
5612
5613 case TemplateArgument::Pack:
5614 // FIXME: Format template argument packs
5615 Result += "<template argument pack>";
5616 break;
5617 }
5618 }
5619
5620 Result += ']';
5621 return Result;
5622}